repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
zmeyc/GRDB.swift
GRDB/Core/DatabaseValueConvertible.swift
1
19434
// MARK: - DatabaseValueConvertible /// Types that adopt DatabaseValueConvertible can be initialized from /// database values. /// /// The protocol comes with built-in methods that allow to fetch cursors, /// arrays, or single values: /// /// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String> /// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String] /// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String? /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String> /// try String.fetchAll(statement, arguments:...) // [String] /// try String.fetchOne(statement, arguments:...) // String? /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. public protocol DatabaseValueConvertible : SQLExpressible { /// Returns a value that can be stored in the database. var databaseValue: DatabaseValue { get } /// Returns a value initialized from *databaseValue*, if possible. static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? } extension DatabaseValueConvertible { /// Returns the value, converted to the requested type. /// /// - returns: An optional *Self*. static func convertOptional(from databaseValue: DatabaseValue) -> Self? { // Use fromDatabaseValue first: this allows DatabaseValue to convert NULL to .null. if let value = Self.fromDatabaseValue(databaseValue) { return value } if databaseValue.isNull { // Failed conversion from nil: ok return nil } else { // Failed conversion from a non-null database value: this is data loss, a programmer error. fatalError("could not convert database value \(databaseValue) to \(Self.self)") } } /// Returns the value, converted to the requested type. /// /// - returns: A *Self*. static func convert(from databaseValue: DatabaseValue) -> Self { if let value = Self.fromDatabaseValue(databaseValue) { return value } // Failed conversion: programmer error fatalError("could not convert database value \(databaseValue) to \(Self.self)") } } // SQLExpressible adoption extension DatabaseValueConvertible { /// This property is an implementation detail of the query interface. /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface /// /// # Low Level Query Interface /// /// See SQLExpression.sqlExpression public var sqlExpression: SQLExpression { return databaseValue } } /// DatabaseValueConvertible comes with built-in methods that allow to fetch /// cursors, arrays, or single values: /// /// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String> /// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String] /// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String? /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String> /// try String.fetchAll(statement, arguments:...) // [String] /// try String.fetchOne(statement, arguments:...) // String /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension DatabaseValueConvertible { // MARK: Fetching From SelectStatement /// Returns a cursor over values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try String.fetchCursor(statement) // DatabaseCursor<String> /// while let name = try names.next() { // String /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> { // Reuse a single mutable row for performance let row = try Row(statement: statement).adapted(with: adapter, layout: statement) return statement.cursor(arguments: arguments, next: { let dbv: DatabaseValue = row.value(atIndex: 0) guard let value = Self.fromDatabaseValue(dbv) else { throw DatabaseError(resultCode: .SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments) } return value }) } /// Returns an array of values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try String.fetchAll(statement) // [String] /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from a prepared statement. /// /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let name = try String.fetchOne(statement) // String? /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { // Reuse a single mutable row for performance let row = try Row(statement: statement).adapted(with: adapter, layout: statement) let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: { let dbv: DatabaseValue = row.value(atIndex: 0) if let value = Self.fromDatabaseValue(dbv) { return value } else if dbv.isNull { return nil } else { throw DatabaseError(resultCode: .SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments) } }) return try cursor.next() ?? nil } } extension DatabaseValueConvertible { // MARK: Fetching From Request /// Returns a cursor over values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try String.fetchCursor(db, request) // DatabaseCursor<String> /// for let name = try names.next() { // String /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - request: A fetch request. /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> { let (statement, adapter) = try request.prepare(db) return try fetchCursor(statement, adapter: adapter) } /// Returns an array of values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try String.fetchAll(db, request) // [String] /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] { let (statement, adapter) = try request.prepare(db) return try fetchAll(statement, adapter: adapter) } /// Returns a single value fetched from a fetch request. /// /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let name = try String.fetchOne(db, request) // String? /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? { let (statement, adapter) = try request.prepare(db) return try fetchOne(statement, adapter: adapter) } } extension DatabaseValueConvertible { // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. /// /// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String> /// while let name = try name.next() { // String /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> { return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of values fetched from an SQL query. /// /// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String] /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from an SQL query. /// /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// /// let name = try String.fetchOne(db, "SELECT name FROM ...") // String? /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } /// Swift's Optional comes with built-in methods that allow to fetch cursors /// and arrays of optional DatabaseValueConvertible: /// /// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String?> /// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?] /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// try Optional<String>.fetchCursor(statement, arguments:...) // DatabaseCursor<String?> /// try Optional<String>.fetchAll(statement, arguments:...) // [String?] /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From SelectStatement /// Returns a cursor over optional values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try Optional<String>.fetchCursor(statement) // DatabaseCursor<String?> /// while let name = try names.next() { // String? /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> { // Reuse a single mutable row for performance let row = try Row(statement: statement).adapted(with: adapter, layout: statement) return statement.cursor(arguments: arguments, next: { let dbv: DatabaseValue = row.value(atIndex: 0) if let value = Wrapped.fromDatabaseValue(dbv) { return value } else if dbv.isNull { return nil } else { throw DatabaseError(resultCode: .SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Wrapped.self)", sql: statement.sql, arguments: arguments) } }) } /// Returns an array of optional values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try Optional<String>.fetchAll(statement) // [String?] /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From Request /// Returns a cursor over optional values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try Optional<String>.fetchCursor(db, request) // DatabaseCursor<String?> /// while let name = try names.next() { // String? /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - requet: A fetch request. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Wrapped?> { let (statement, adapter) = try request.prepare(db) return try fetchCursor(statement, adapter: adapter) } /// Returns an array of optional values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try Optional<String>.fetchAll(db, request) // [String?] /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] { let (statement, adapter) = try request.prepare(db) return try fetchAll(statement, adapter: adapter) } } extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From SQL /// Returns a cursor over optional values fetched from an SQL query. /// /// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String?> /// while let name = try names.next() { // String? /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> { return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of optional values fetched from an SQL query. /// /// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?] /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - parameter arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } }
mit
160b039b15d0eb652f9d963f2036af2e
43.369863
175
0.627354
4.733074
false
false
false
false
uasys/swift
test/SILGen/objc_thunks.swift
1
30020
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo import ansible class Hoozit : Gizmo { @objc func typical(_ x: Int, y: Gizmo) -> Gizmo { return y } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[X:%.*]] : @trivial $Int, [[Y:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[Y_COPY:%.*]] = copy_value [[Y]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.typical // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytF : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y_COPY]], [[BORROWED_THIS_COPY]]) {{.*}} line:[[@LINE-8]]:14:auto_gen // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit // CHECK-NEXT: return [[RES]] : $Gizmo{{.*}} line:[[@LINE-11]]:14:auto_gen // CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo' // NS_CONSUMES_SELF by inheritance override func fork() { } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4forkyyFTo : $@convention(objc_method) (@owned Hoozit) -> () { // CHECK: bb0([[THIS:%.*]] : @owned $Hoozit): // CHECK-NEXT: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC4forkyyF : $@convention(method) (@guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[BORROWED_THIS]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS]] from [[THIS]] // CHECK-NEXT: destroy_value [[THIS]] // CHECK-NEXT: return // CHECK-NEXT: } // NS_CONSUMED 'gizmo' argument by inheritance override class func consume(_ gizmo: Gizmo?) { } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZTo : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () { // CHECK: bb0([[GIZMO:%.*]] : @owned $Optional<Gizmo>, [[THIS:%.*]] : @trivial $@objc_metatype Hoozit.Type): // CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type // CHECK: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZ : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> () // CHECK-NEXT: apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]]) // CHECK-NEXT: return // CHECK-NEXT: } // NS_RETURNS_RETAINED by family (-copy) @objc func copyFoo() -> Gizmo { return self } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // Override the normal family conventions to make this non-consuming and // returning at +0. @objc func initFoo() -> Gizmo { return self } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7initFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7initFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } @objc var typicalProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.getter // CHECK-NEXT: [[GETIMPL:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg // CHECK-NEXT: [[RES:%.*]] = apply [[GETIMPL]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RES]] : $Gizmo // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK: bb0(%0 : @guaranteed $Hoozit): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.typicalProperty // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo // CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]] {{.*}} // CHECK-NEXT: end_access [[READ]] : $*Gizmo // CHECK-NEXT: return [[RES]] // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Gizmo // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Hoozit // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: // function_ref objc_thunks.Hoozit.typicalProperty.setter // CHECK: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs // CHECK: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: return [[RES]] : $(), scope {{.*}} // id: {{.*}} line:[[@LINE-34]]:13:auto_gen // CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo' // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs // CHECK: bb0([[ARG0:%.*]] : @owned $Gizmo, [[ARG1:%.*]] : @guaranteed $Hoozit): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[ARG0_COPY:%.*]] = copy_value [[BORROWED_ARG0]] // CHECK: [[ADDR:%.*]] = ref_element_addr [[ARG1]] : {{.*}}, #Hoozit.typicalProperty // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo // CHECK: assign [[ARG0_COPY]] to [[WRITE]] : $*Gizmo // CHECK: end_access [[WRITE]] : $*Gizmo // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs' // NS_RETURNS_RETAINED getter by family (-copy) @objc var copyProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo { // CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.getter // CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg // CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg // CHECK: bb0(%0 : @guaranteed $Hoozit): // CHECK: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.copyProperty // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo // CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Gizmo // CHECK-NEXT: return [[RES]] // -- setter is normal // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.setter // CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs // CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs // CHECK: bb0([[ARG1:%.*]] : @owned $Gizmo, [[SELF:%.*]] : @guaranteed $Hoozit): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[ADDR:%.*]] = ref_element_addr [[SELF]] : {{.*}}, #Hoozit.copyProperty // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo // CHECK: assign [[ARG1_COPY]] to [[WRITE]] // CHECK: end_access [[WRITE]] : $*Gizmo // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: } // end sil function '_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs' @objc var roProperty: Gizmo { return self } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit // CHECK-NEXT: return [[RES]] : $Gizmo // CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo' // -- no setter // CHECK-NOT: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvsTo @objc var rwProperty: Gizmo { get { return self } set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } @objc var copyRWProperty: Gizmo { get { return self } set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NOT: return // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter is normal // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } @objc var initProperty: Gizmo // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } @objc var propComputed: Gizmo { @objc(initPropComputedGetter) get { return self } @objc(initPropComputedSetter:) set {} } // -- getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo { // CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo // CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return [[RES]] // CHECK-NEXT: } // -- setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit): // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> () // CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK-NEXT: destroy_value [[THIS_COPY]] // CHECK-NEXT: return // CHECK-NEXT: } // Don't export generics to ObjC yet func generic<T>(_ x: T) {} // CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}} // Constructor. // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSi7bellsOn_tcfc : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[GIZMO:%[0-9]+]] = upcast [[SELF:%[0-9]+]] : $Hoozit to $Gizmo // CHECK: [[BORROWED_GIZMO:%.*]] = begin_borrow [[GIZMO]] // CHECK: [[CAST_BORROWED_GIZMO:%.*]] = unchecked_ref_cast [[BORROWED_GIZMO]] : $Gizmo to $Hoozit // CHECK: [[SUPERMETHOD:%[0-9]+]] = super_method [volatile] [[CAST_BORROWED_GIZMO]] : $Hoozit, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK-NEXT: end_borrow [[BORROWED_GIZMO]] from [[GIZMO]] // CHECK-NEXT: [[SELF_REPLACED:%[0-9]+]] = apply [[SUPERMETHOD]](%0, [[X:%[0-9]+]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK-NOT: unconditional_checked_cast downcast [[SELF_REPLACED]] : $Gizmo to $Hoozit // CHECK: unchecked_ref_cast // CHECK: return override init(bellsOn x : Int) { super.init(bellsOn: x) other() } // Subscript @objc subscript (i: Int) -> Hoozit { // Getter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicigTo : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit // CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicig : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RESULT]] : $Hoozit get { return self } // Setter // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicisTo : $@convention(objc_method) (Hoozit, Int, Hoozit) -> () // CHECK: bb0([[VALUE:%[0-9]+]] : @unowned $Hoozit, [[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Hoozit // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicis : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[VALUE_COPY]], [[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] : $() // CHECK: } // end sil function '_T011objc_thunks6HoozitCACSicisTo' set {} } } class Wotsit<T> : Gizmo { // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC5plainyyFTo : $@convention(objc_method) <T> (Wotsit<T>) -> () { // CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T> // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC5plainyyF : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> () // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T> // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } @objc func plain() { } func generic<U>(_ x: U) {} var property : T init(t: T) { self.property = t super.init() } // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC11descriptionSSvgTo : $@convention(objc_method) <T> (Wotsit<T>) -> @autoreleased NSString { // CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T> // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC11descriptionSSvg : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String // CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE:%.*]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T> // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-NEXT: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]] // CHECK-NEXT: [[NSRESULT:%.*]] = apply [[BRIDGE]]([[BORROWED_RESULT]]) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK-NEXT: end_borrow [[BORROWED_RESULT]] from [[RESULT]] // CHECK-NEXT: destroy_value [[RESULT]] // CHECK-NEXT: return [[NSRESULT]] : $NSString // CHECK-NEXT: } override var description : String { return "Hello, world." } // Ivar destroyer // CHECK: sil hidden @_T011objc_thunks6WotsitCfETo // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGycfcTo : $@convention(objc_method) <T> (@owned Wotsit<T>) -> @owned Optional<Wotsit<T>> // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>> } // CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}} // Extension initializers, properties and methods need thunks too. extension Hoozit { // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSi3int_tcfcTo : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit @objc dynamic convenience init(int i: Int) { self.init(bellsOn: i) } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSd6double_tcfc : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit convenience init(double d: Double) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[X_BOX:%[0-9]+]] = alloc_box ${ var X } var x = X() // CHECK: [[CTOR:%[0-9]+]] = class_method [volatile] [[SELF:%[0-9]+]] : $Hoozit, #Hoozit.init!initializer.1.foreign : (Hoozit.Type) -> (Int) -> Hoozit, $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit // CHECK: [[NEW_SELF:%[0-9]+]] = apply [[CTOR]] // CHECK: store [[NEW_SELF]] to [init] [[PB_BOX]] : $*Hoozit // CHECK: [[RELOADED_SELF:%.*]] = load_borrow [[PB_BOX]] // CHECK: [[NONNULL:%[0-9]+]] = is_nonnull [[RELOADED_SELF]] : $Hoozit // CHECK: end_borrow [[RELOADED_SELF]] from [[PB_BOX]] // CHECK-NEXT: cond_br [[NONNULL]], [[NONNULL_BB:bb[0-9]+]], [[NULL_BB:bb[0-9]+]] // CHECK: [[NULL_BB]]: // CHECK-NEXT: destroy_value [[X_BOX]] : ${ var X } // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]] // CHECK: [[NONNULL_BB]]: // CHECK: [[OTHER_REF:%[0-9]+]] = function_ref @_T011objc_thunks5otheryyF : $@convention(thin) () -> () // CHECK-NEXT: apply [[OTHER_REF]]() : $@convention(thin) () -> () // CHECK-NEXT: destroy_value [[X_BOX]] : ${ var X } // CHECK-NEXT: br [[EPILOG_BB]] // CHECK: [[EPILOG_BB]]: // CHECK-NOT: super_method // CHECK: return self.init(int:Int(d)) other() } func foof() {} // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4foofyyFTo : $@convention(objc_method) (Hoozit) -> () { var extensionProperty: Int { return 0 } // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC17extensionPropertySivg : $@convention(method) (@guaranteed Hoozit) -> Int } // Calling objc methods of subclass should go through native entry points func useHoozit(_ h: Hoozit) { // sil @_T011objc_thunks9useHoozityAA0D0C1h_tF // In the class decl, overrides importd method, 'dynamic' was inferred h.fork() // CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Hoozit.fork!1.foreign // In an extension, 'dynamic' was inferred. h.foof() // CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Hoozit.foof!1.foreign } func useWotsit(_ w: Wotsit<String>) { // sil @_T011objc_thunks9useWotsitySo0D0CySSG1w_tF w.plain() // CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 : w.generic(2) // CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.generic!1 : // Inherited methods only have objc entry points w.clone() // CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Gizmo.clone!1.foreign } func other() { } class X { } // CHECK-LABEL: sil hidden @_T011objc_thunks8propertySiSo5GizmoCF func property(_ g: Gizmo) -> Int { // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.count!getter.1.foreign return g.count } // CHECK-LABEL: sil hidden @_T011objc_thunks13blockPropertyySo5GizmoCF func blockProperty(_ g: Gizmo) { // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!setter.1.foreign g.block = { } // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!getter.1.foreign g.block() } class DesignatedStubs : Gizmo { var i: Int override init() { i = 5 } // CHECK-LABEL: sil hidden @_T011objc_thunks15DesignatedStubsCSQyACGSi7bellsOn_tcfc // CHECK: function_ref @_T0s25_unimplementedInitializers5NeverOs12StaticStringV9className_AE04initG0AE4fileSu4lineSu6columntF // CHECK: string_literal utf8 "objc_thunks.DesignatedStubs" // CHECK: string_literal utf8 "init(bellsOn:)" // CHECK: string_literal utf8 "{{.*}}objc_thunks.swift" // CHECK: return // CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}} } class DesignatedOverrides : Gizmo { var i: Int = 5 // CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGycfc // CHECK-NOT: return // CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int // CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> () -> Gizmo!, $@convention(objc_method) (@owned Gizmo) -> @owned Optional<Gizmo> // CHECK: return // CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGSi7bellsOn_tcfc // CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int // CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK: return } // Make sure we copy blocks passed in as IUOs - <rdar://problem/22471309> func registerAnsible() { // CHECK: function_ref @_T011objc_thunks15registerAnsibleyyFyyycSgcfU_ Ansible.anseAsync({ completion in completion!() }) }
apache-2.0
d24882998268dc8cade76eb574cc46ac
54.577778
237
0.625783
3.344328
false
false
false
false
bigL055/SPKit
Sources/UIColor/UIColor.swift
2
3177
// // SPKit // // Copyright (c) 2017 linhay - https:// github.com/linhay // // 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 import UIKit public extension UIColor{ /// 随机色 public class var random: UIColor { get{ return UIColor(red: CGFloat(arc4random_uniform(255)) / 255.0, green: CGFloat(arc4random_uniform(255)) / 255.0, blue: CGFloat(arc4random_uniform(255)) / 255.0, alpha: 1) } } /// 设置透明度 /// /// - Parameter alpha: 透明度 /// - Returns: uicolor public func with(alpha: CGFloat) -> UIColor { return self.withAlphaComponent(alpha) } /// 十六进制色: 0x666666 /// /// - Parameter RGBValue: 十六进制颜色 convenience init(value: UInt) { self.init( red: CGFloat((value & 0xFF0000) >> 16) / 255.0, green: CGFloat((value & 0x00FF00) >> 8) / 255.0, blue: CGFloat(value & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } /// 十六进制色: 0x666666 /// /// - Parameter str: "#666666" / "0X666666" / "0x666666" convenience init(str: String){ var cString = str.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if cString.hasPrefix("0X") { cString = String(cString[String.Index(encodedOffset: 2)...]) } if cString.hasPrefix("#") { cString = String(cString[String.Index(encodedOffset: 1)...]) } if cString.count != 6 { self.init(red: 1, green: 1, blue: 1, alpha: 1) return } let rStr = cString[String.Index(encodedOffset: 0)..<String.Index(encodedOffset: 2)] let gStr = cString[String.Index(encodedOffset: 2)..<String.Index(encodedOffset: 4)] let bStr = cString[String.Index(encodedOffset: 4)..<String.Index(encodedOffset: 6)] var r: UInt32 = 0x0 var g: UInt32 = 0x0 var b: UInt32 = 0x0 Scanner(string: String(rStr)).scanHexInt32(&r) Scanner(string: String(gStr)).scanHexInt32(&g) Scanner(string: String(bStr)).scanHexInt32(&b) self.init( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1 ) } }
apache-2.0
928ec07740ed070260408714b583196f
34.089888
95
0.652898
3.700237
false
false
false
false
wayfindrltd/wayfindr-demo-ios
Wayfindr Demo/Classes/Controller/Developer/DeveloperOptionsTableViewController.swift
1
6008
// // DeveloperOptionsTableViewController.swift // Wayfindr Demo // // Created by Wayfindr on 30/11/2015. // Copyright (c) 2016 Wayfindr (http://www.wayfindr.net) // // 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 /// Table view for viewing and adjusting developer/tester settings. final class DeveloperOptionsTableViewController: UITableViewController { // MARK: - Types /// List of options to show the user. fileprivate enum DeveloperOptions: Int { case showForceNext case showRepeatInAccessibility case stopwatchEnabled case audioFlashEnabled case strictRouting static let allValues = [showForceNext, showRepeatInAccessibility, stopwatchEnabled, audioFlashEnabled, strictRouting] } // MARK: - Properties /// Reuse identifier for the table cells. fileprivate let reuseIdentifier = "OptionCell" // MARK: - Initializers init() { super.init(style: .grouped) } // override init(style: UITableView.Style) { // super.init(style: .grouped) // } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.register(SwitchTableViewCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.estimatedRowHeight = WAYConstants.WAYSizes.EstimatedCellHeight tableView.rowHeight = UITableView.automaticDimension title = WAYStrings.CommonStrings.DeveloperOptions } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return DeveloperOptions.allValues.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) if let switchCell = cell as? SwitchTableViewCell { if let selectedOption = DeveloperOptions(rawValue: indexPath.row) { switch selectedOption { case .showForceNext: switchCell.textLabel?.text = WAYStrings.DeveloperOptions.ShowForceNextButton switchCell.switchControl.isOn = WAYDeveloperSettings.sharedInstance.showForceNextButton case .showRepeatInAccessibility: switchCell.textLabel?.text = WAYStrings.DeveloperOptions.ShowRepeatButton switchCell.switchControl.isOn = WAYDeveloperSettings.sharedInstance.showRepeatButton case .stopwatchEnabled: switchCell.textLabel?.text = WAYStrings.DeveloperOptions.StopwatchEnabled switchCell.switchControl.isOn = WAYDeveloperSettings.sharedInstance.stopwatchEnabled case .audioFlashEnabled: switchCell.textLabel?.text = WAYStrings.DeveloperOptions.AudioFlashEnabled switchCell.switchControl.isOn = WAYDeveloperSettings.sharedInstance.audioFlashEnabled case .strictRouting: switchCell.textLabel?.text = WAYStrings.DeveloperOptions.StrictRouting switchCell.switchControl.isOn = WAYDeveloperSettings.sharedInstance.strictRouting } } switchCell.textLabel?.numberOfLines = 0 switchCell.textLabel?.lineBreakMode = .byWordWrapping switchCell.switchControl.addTarget(self, action: #selector(DeveloperOptionsTableViewController.switchValueChanged(_:)), for: .valueChanged) switchCell.switchControl.tag = indexPath.row } return cell } // MARK: - Control Actions /** Action when the user flips a switch. - parameter sender: `UISwitch` that changed value. */ @objc func switchValueChanged(_ sender: UISwitch) { if let selectedOption = DeveloperOptions(rawValue: sender.tag) { switch selectedOption { case .showForceNext: WAYDeveloperSettings.sharedInstance.showForceNextButton = sender.isOn case .showRepeatInAccessibility: WAYDeveloperSettings.sharedInstance.showRepeatButton = sender.isOn case .stopwatchEnabled: WAYDeveloperSettings.sharedInstance.stopwatchEnabled = sender.isOn case .audioFlashEnabled: WAYDeveloperSettings.sharedInstance.audioFlashEnabled = sender.isOn case .strictRouting: WAYDeveloperSettings.sharedInstance.strictRouting = sender.isOn } } } }
mit
392e19c009c2ee791fd09ceb044ee8d8
38.267974
151
0.657623
5.547553
false
false
false
false
thatseeyou/SpriteKitExamples.playground
Pages/dragField.xcplaygroundpage/Contents.swift
1
3207
/*: ### dragField - physicsWorld.gravity에 맞서는 것을 확인할 수 있다. - 속도가 점점 커지지만 dragField 안에서는 일종 속도가 유지되는 것을 확인할 수 있다. - field.region을 없애고 ball.physicsBody의 velocity를 관찰하면 알 수 있다. */ import UIKit import SpriteKit class GameScene: SKScene { var contentCreated = false let pi:CGFloat = CGFloat(M_PI) override func didMove(to view: SKView) { if self.contentCreated != true { // distribute small physics bobies for x in 0...10 { for y in (0...15).reversed() { let orgX:CGFloat = 10.0 let orgY:CGFloat = 15.0 addBall( CGPoint( x:orgX + 30.0 * CGFloat(x), y:orgY + 30.0 * CGFloat(y) ), hue: CGFloat(x) / 10.0, saturation: CGFloat(y) / 15.0) } } // add dragField node do { let position = CGPoint(x: 160, y: 120) let radius:Float = 50.0 let shapeNode = SKShapeNode(circleOfRadius: CGFloat(radius)) shapeNode.position = position addChild(shapeNode) let field = SKFieldNode.dragField() field.strength = 100.0 // default = 1 field.position = position field.region = SKRegion(radius: radius) addChild(field) } self.physicsWorld.speed = 0.5 self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.0) self.contentCreated = true } } override func update(_ currentTime: TimeInterval) { // Only first ball returned let ball = childNode(withName: "Ball") -(ball!.physicsBody!.velocity.dy) } func addBall(_ position:CGPoint, hue:CGFloat, saturation:CGFloat) { let radius = CGFloat(5.0) let ball = SKShapeNode(circleOfRadius: radius) ball.name = "Ball" ball.position = position ball.physicsBody = SKPhysicsBody(circleOfRadius: radius) ball.physicsBody?.friction = 0.8 ball.physicsBody?.mass = 1.0 ball.physicsBody?.linearDamping = 0.5 ball.strokeColor = UIColor.clear ball.fillColor = UIColor(hue: hue, saturation: saturation, brightness: 1.0, alpha: 1.0) addChild(ball) } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // add SKView do { let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480)) skView.showsFPS = true //skView.showsNodeCount = true skView.showsFields = true skView.ignoresSiblingOrder = true let scene = GameScene(size: CGSize(width: 320, height: 480)) scene.scaleMode = .aspectFit skView.presentScene(scene) self.view.addSubview(skView) } } } PlaygroundHelper.showViewController(ViewController())
isc
964d23c16876c7c9ec4e2b07e2a1da29
27.925234
95
0.538288
4.340813
false
false
false
false
hackcity2017/iOS-client-application
hackcity/ChartView.swift
1
2353
// // ChartView.swift // hackcity // // Created by Remi Robert on 26/03/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit import SwiftChart import SnapKit class ChartView: UIView { private var valuesX = [Float]() private var valuesY = [Float]() private var valuesZ = [Float]() private var chart: Chart! override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.clear for _ in 0...20 { valuesX.append(0) valuesY.append(0) valuesZ.append(0) } } func addValue(x: Double, y: Double, z: Double) { if valuesX.count > 20 { valuesX.removeFirst() } if valuesY.count > 20 { valuesY.removeFirst() } if valuesZ.count > 20 { valuesZ.removeFirst() } valuesX.append(Float(x)) valuesY.append(Float(y)) valuesZ.append(Float(z)) self.configure() } func configure() { if chart != nil { self.chart.removeFromSuperview() } chart = Chart() chart.backgroundColor = UIColor.clear chart.axesColor = UIColor.clear chart.gridColor = UIColor.clear chart.lineWidth = 7 chart.xLabels = nil chart.yLabels = nil chart.minY = 0 chart.maxY = 10 chart.labelFont = UIFont.boldSystemFont(ofSize: 0) self.addSubview(chart) chart.snp.makeConstraints({ make in make.edges.equalTo(self) }) let series1 = ChartSeries(valuesX) series1.color = ChartColors.greenColor() series1.area = true let series2 = ChartSeries(valuesY) series2.color = ChartColors.blueColor() series2.area = true let series3 = ChartSeries(valuesZ) series3.color = ChartColors.redColor() series3.area = true chart.removeAllSeries() chart.add(series1) chart.add(series2) chart.add(series3) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) guard let view = Bundle.main.loadNibNamed("ChartView", owner: self, options: nil)?[0] as? UIView else { return } self.addSubview(view) view.frame = self.bounds } }
mit
78c0d94cc8747608b6e365a8abb7f0ce
24.021277
111
0.572279
4.148148
false
false
false
false
yidahis/ShopingCart
ShopingCart/ShopingCartViewBottomCell.swift
1
1390
// // ShopingCartViewBottom.swift // ShopingCart // // Created by zhouyi on 2017/9/18. // Copyright © 2017年 NewBornTown, Inc. All rights reserved. // import UIKit class ShopingCartViewBottomCell: UITableViewCell { var tipLabel: UILabel = UILabel() var lineView: UIView = UIView() var countView: CountView = CountView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none contentView.addSubview(tipLabel) contentView.addSubview(lineView) contentView.addSubview(countView) tipLabel.font = UIFont.systemFont(ofSize: 14) tipLabel.text = "数量" lineView.backgroundColor = UIColor.groupTableViewBackground } override func layoutSubviews() { super.layoutSubviews() tipLabel.frame = CGRect(x: XSpace, y: 0, width: 100, height: 16) tipLabel.centerY = contentView.height/2 lineView.frame = CGRect(x: 0, y: contentView.height - 1, width: contentView.width, height: 1) countView.frame = CGRect(x: contentView.width - 120 - XSpace, y: 0, width: 120, height: 26) countView.centerY = tipLabel.centerY } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
apache-2.0
6a397c45149b0a3828c4eeec3aa23308
31.162791
101
0.650759
4.321875
false
false
false
false
heilb1314/500px_Challenge
PhotoWall_500px_challenge/PhotoWall_500px_challenge/ParsingConstants.swift
1
2605
// // ParsingConstants.swift // demo_500px // // Created by Jianxiong Wang on 1/29/17. // Copyright © 2017 JianxiongWang. All rights reserved. // import Foundation /// Query fields public struct QueryFields { static let totalItems = "total_items" static let photos = "photos" static let currentPage = "current_page" static let totalPages = "total_pages" } /// Photo fields in `QueryFields.photos` public struct PhotoFields { static let aperture = "aperture" static let category = "category" static let collectionsCount = "collections_count" static let commentsCount = "comments_count" static let convertedBits = "converted_bits" static let description = "description" static let favoritesCount = "favorites_count" static let focalLength = "focal_length" static let forSaleDate = "for_sale_date" static let height = "height" static let highestRating = "highest_rating" static let hiResUploaded = "hi_res_uploaded" static let id = "id" static let imageFormat = "image_format" static let images = "images" static let imageUrl = "image_url" static let latitude = "latitude" static let licensingRequested = "licensing_requested" static let longitude = "longitude" static let name = "name" static let nsfw = "nsfw" static let privacy = "privacy" static let takenAt = "takenAt" static let timesViewed = "times_viewed" static let url = "url" static let user = "user" static let votesCount = "votes_count" static let width = "width" } /// Images fields in `PhotoFields.images` public struct ImagesFields { static let format = "format" static let httpsUrl = "https_url" static let size = "size" static let url = "url" } public struct UserFields { static let city = "city" static let country = "country" static let firstname = "firstname" static let fullname = "fullname" static let id = "id" static let lastname = "lastname" static let username = "username" static let userpicUrl = "userpic_url" } let CATEGORIES = [ "Popular", "Upcoming", "Uncategorized", "Abstract", "Animals", "Black and White", "Celebrities", "City and Architecture", "Commercial", "Concert", "Family", "Fashion", "Film", "Fine Art", "Food", "Journalism", "Landscapes", "Macro", "Nature", "Nude", "People", "Performing Arts", "Sport", "Still Life", "Street", "Transportation", "Travel", "Underwater", "Urban Exploration", "Wedding" ]
mit
833262d0ef29fb3dbe3c91fad18ca76a
24.038462
57
0.647465
3.835052
false
false
false
false
BradLarson/GPUImage2
framework/Source/Operations/LineGenerator.swift
1
2274
#if canImport(OpenGL) import OpenGL.GL3 #endif #if canImport(OpenGLES) import OpenGLES #endif #if canImport(COpenGLES) import COpenGLES.gles2 #endif #if canImport(COpenGL) import COpenGL #endif public enum Line { case infinite(slope:Float, intercept:Float) case segment(p1:Position, p2:Position) func toGLEndpoints() -> [GLfloat] { switch self { case .infinite(let slope, let intercept): if (slope > 9000.0) {// Vertical line return [intercept, -1.0, intercept, 1.0] } else { return [-1.0, GLfloat(slope * -1.0 + intercept), 1.0, GLfloat(slope * 1.0 + intercept)] } case .segment(let p1, let p2): return [p1.x, p1.y, p2.x, p2.y].map {GLfloat($0)} } } } public class LineGenerator: ImageGenerator { public var lineColor:Color = Color.green { didSet { uniformSettings["lineColor"] = lineColor } } public var lineWidth:Float = 1.0 { didSet { lineShader.use() glLineWidth(lineWidth) } } let lineShader:ShaderProgram var uniformSettings = ShaderUniformSettings() public override init(size:Size) { lineShader = crashOnShaderCompileFailure("LineGenerator"){try sharedImageProcessingContext.programForVertexShader(LineVertexShader, fragmentShader:LineFragmentShader)} super.init(size:size) ({lineWidth = 1.0})() ({lineColor = Color.red})() } public func renderLines(_ lines:[Line]) { imageFramebuffer.activateFramebufferForRendering() lineShader.use() uniformSettings.restoreShaderSettings(lineShader) clearFramebufferWithColor(Color.transparent) guard let positionAttribute = lineShader.attributeIndex("position") else { fatalError("A position attribute was missing from the shader program during rendering.") } let lineEndpoints = lines.flatMap{$0.toGLEndpoints()} glVertexAttribPointer(positionAttribute, 2, GLenum(GL_FLOAT), 0, 0, lineEndpoints) enableAdditiveBlending() glDrawArrays(GLenum(GL_LINES), 0, GLsizei(lines.count) * 2) disableBlending() notifyTargets() } }
bsd-3-clause
09a769ba58c2aea5d2c34a5c59f09d5d
27.78481
175
0.633245
4.290566
false
false
false
false
ddki/my_study_project
language/swift/SimpleTunnelCustomizedNetworkingUsingtheNetworkExtensionFramework/tunnel_server/ServerTunnel.swift
1
10159
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the ServerTunnel class. The ServerTunnel class implements the server side of the SimpleTunnel tunneling protocol. */ import Foundation import SystemConfiguration /// The server-side implementation of the SimpleTunnel protocol. class ServerTunnel: Tunnel, TunnelDelegate, NSStreamDelegate { // MARK: Properties /// The stream used to read data from the tunnel TCP connection. var readStream: NSInputStream? /// The stream used to write data to the tunnel TCP connection. var writeStream: NSOutputStream? /// A buffer where the data for the current packet is accumulated. let packetBuffer = NSMutableData() /// The number of bytes remaining to be read for the current packet. var packetBytesRemaining = 0 /// The server configuration parameters. static var configuration = ServerConfiguration() /// The delegate for the network service published by the server. static var serviceDelegate = ServerDelegate() // MARK: Initializers init(newReadStream: NSInputStream, newWriteStream: NSOutputStream) { super.init() delegate = self for stream in [newReadStream, newWriteStream] { stream.delegate = self stream.open() stream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } readStream = newReadStream writeStream = newWriteStream } // MARK: Class Methods /// Start the network service. class func startListeningOnPort(port: Int32) -> NSNetService { let service = NSNetService(domain:Tunnel.serviceDomain, type:Tunnel.serviceType, name: "", port: port) simpleTunnelLog("Starting network service on port \(port)") service.delegate = ServerTunnel.serviceDelegate service.publishWithOptions(NSNetServiceOptions.ListenForConnections) service.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode) return service } /// Load the configuration from disk. class func initializeWithConfigurationFile(path: String) -> Bool { return ServerTunnel.configuration.loadFromFileAtPath(path) } // MARK: Interface /// Handle a bytes available event on the read stream. func handleBytesAvailable() -> Bool { guard let stream = readStream else { return false } var readBuffer = [UInt8](count: Tunnel.maximumMessageSize, repeatedValue: 0) repeat { var toRead = 0 var bytesRead = 0 if packetBytesRemaining == 0 { // Currently reading the total length of the packet. toRead = sizeof(UInt32.self) - packetBuffer.length } else { // Currently reading the packet payload. toRead = packetBytesRemaining > readBuffer.count ? readBuffer.count : packetBytesRemaining } bytesRead = stream.read(&readBuffer, maxLength: toRead) guard bytesRead > 0 else { return false } packetBuffer.appendBytes(readBuffer, length: bytesRead) if packetBytesRemaining == 0 { // Reading the total length, see if the 4 length bytes have been received. if packetBuffer.length == sizeof(UInt32.self) { var totalLength: UInt32 = 0 packetBuffer.getBytes(&totalLength, length: sizeofValue(totalLength)) guard totalLength <= UInt32(Tunnel.maximumMessageSize) else { return false } // Compute the length of the payload. packetBytesRemaining = Int(totalLength) - sizeofValue(totalLength) packetBuffer.length = 0 } } else { // Read a portion of the payload. packetBytesRemaining -= bytesRead if packetBytesRemaining == 0 { // The entire packet has been received, process it. if !handlePacket(packetBuffer) { return false } packetBuffer.length = 0 } } } while stream.hasBytesAvailable return true } /// Send an "Open Result" message to the client. func sendOpenResultForConnection(connectionIdentifier: Int, resultCode: TunnelConnectionOpenResult) { let properties = createMessagePropertiesForConnection(connectionIdentifier, commandType: .OpenResult, extraProperties:[ TunnelMessageKey.ResultCode.rawValue: resultCode.rawValue ]) if !sendMessage(properties) { simpleTunnelLog("Failed to send an open result for connection \(connectionIdentifier)") } } /// Handle a "Connection Open" message received from the client. func handleConnectionOpen(properties: [String: AnyObject]) { guard let connectionIdentifier = properties[TunnelMessageKey.Identifier.rawValue] as? Int, tunnelLayerNumber = properties[TunnelMessageKey.TunnelType.rawValue] as? Int, tunnelLayer = TunnelLayer(rawValue: tunnelLayerNumber) else { return } switch tunnelLayer { case .App: guard let flowKindNumber = properties[TunnelMessageKey.AppProxyFlowType.rawValue] as? Int, flowKind = AppProxyFlowKind(rawValue: flowKindNumber) else { break } switch flowKind { case .TCP: guard let host = properties[TunnelMessageKey.Host.rawValue] as? String, port = properties[TunnelMessageKey.Port.rawValue] as? NSNumber else { break } let newConnection = ServerConnection(connectionIdentifier: connectionIdentifier, parentTunnel: self) guard newConnection.open(host, port: port.integerValue) else { newConnection.closeConnection(.All) break } case .UDP: let _ = UDPServerConnection(connectionIdentifier: connectionIdentifier, parentTunnel: self) sendOpenResultForConnection(connectionIdentifier, resultCode: .Success) } case .IP: let newConnection = ServerTunnelConnection(connectionIdentifier: connectionIdentifier, parentTunnel: self) guard newConnection.open() else { newConnection.closeConnection(.All) break } } } // MARK: NSStreamDelegate /// Handle a stream event. func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) { switch aStream { case writeStream!: switch eventCode { case [.HasSpaceAvailable]: // Send any buffered data. if !savedData.isEmpty { guard savedData.writeToStream(writeStream!) else { closeTunnel() delegate?.tunnelDidClose(self) break } if savedData.isEmpty { for connection in connections.values { connection.resume() } } } case [.ErrorOccurred]: closeTunnel() delegate?.tunnelDidClose(self) default: break } case readStream!: var needCloseTunnel = false switch eventCode { case [.HasBytesAvailable]: needCloseTunnel = !handleBytesAvailable() case [.OpenCompleted]: delegate?.tunnelDidOpen(self) case [.ErrorOccurred], [.EndEncountered]: needCloseTunnel = true default: break } if needCloseTunnel { closeTunnel() delegate?.tunnelDidClose(self) } default: break } } // MARK: Tunnel /// Close the tunnel. override func closeTunnel() { if let stream = readStream { if let error = stream.streamError { simpleTunnelLog("Tunnel read stream error: \(error)") } let socketData = CFReadStreamCopyProperty(stream, kCFStreamPropertySocketNativeHandle) as? NSData stream.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) stream.close() stream.delegate = nil readStream = nil if let data = socketData { var socket: CFSocketNativeHandle = 0 data.getBytes(&socket, length: sizeofValue(socket)) close(socket) } } if let stream = writeStream { if let error = stream.streamError { simpleTunnelLog("Tunnel write stream error: \(error)") } stream.removeFromRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode) stream.close() stream.delegate = nil } super.closeTunnel() } /// Handle a message received from the client. override func handleMessage(commandType: TunnelCommand, properties: [String: AnyObject], connection: Connection?) -> Bool { switch commandType { case .Open: handleConnectionOpen(properties) case .FetchConfiguration: var personalized = ServerTunnel.configuration.configuration personalized.removeValueForKey(SettingsKey.IPv4.rawValue) let messageProperties = createMessagePropertiesForConnection(0, commandType: .FetchConfiguration, extraProperties: [TunnelMessageKey.Configuration.rawValue: personalized]) sendMessage(messageProperties) default: break } return true } /// Write data to the tunnel connection. override func writeDataToTunnel(data: NSData, startingAtOffset: Int) -> Int { guard let stream = writeStream else { return -1 } return writeData(data, toStream: stream, startingAtOffset:startingAtOffset) } // MARK: TunnelDelegate /// Handle the "tunnel open" event. func tunnelDidOpen(targetTunnel: Tunnel) { } /// Handle the "tunnel closed" event. func tunnelDidClose(targetTunnel: Tunnel) { } /// Handle the "tunnel did send configuration" event. func tunnelDidSendConfiguration(targetTunnel: Tunnel, configuration: [String : AnyObject]) { } } /// An object that servers as the delegate for the network service published by the server. class ServerDelegate : NSObject, NSNetServiceDelegate { // MARK: NSNetServiceDelegate /// Handle the "failed to publish" event. func netService(sender: NSNetService, didNotPublish errorDict: [String : NSNumber]) { simpleTunnelLog("Failed to publish network service") exit(1) } /// Handle the "published" event. func netServiceDidPublish(sender: NSNetService) { simpleTunnelLog("Network service published successfully") } /// Handle the "new connection" event. func netService(sender: NSNetService, didAcceptConnectionWithInputStream inputStream: NSInputStream, outputStream: NSOutputStream) { simpleTunnelLog("Accepted a new connection") _ = ServerTunnel(newReadStream: inputStream, newWriteStream: outputStream) } /// Handle the "stopped" event. func netServiceDidStop(sender: NSNetService) { simpleTunnelLog("Network service stopped") exit(0) } }
mit
fbe4d3cd3b1109721e77fd05a8636f03
28.785924
175
0.71399
4.191911
false
false
false
false
nathawes/swift
test/SILOptimizer/definite-init-convert-to-escape.swift
9
5955
// RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module %s | %FileCheck %s // RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module -Xllvm -sil-disable-convert-escape-to-noescape-switch-peephole %s | %FileCheck %s --check-prefix=NOPEEPHOLE // REQUIRES: objc_interop import Foundation // Make sure that we keep the escaping closures alive accross the ultimate call. // CHECK-LABEL: sil @$s1A19bridgeNoescapeBlock5optFn0D3Fn2yySSSgcSg_AFtF // CHECK: bb0 // CHECK: retain_value %0 // CHECK: retain_value %0 // CHECK: bb1 // CHECK: convert_escape_to_noescape % // CHECK: strong_release // CHECK: bb5 // CHECK: retain_value %1 // CHECK: retain_value %1 // CHECK: bb6 // CHECK: convert_escape_to_noescape % // CHECK: strong_release // CHECK: bb10 // CHECK: [[F:%.*]] = function_ref @noescapeBlock3 // CHECK: apply [[F]] // CHECK: release_value {{.*}} : $Optional<NSString> // CHECK: release_value %1 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()> // CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>) -> ()> // CHECK: release_value %0 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()> // CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>) public func bridgeNoescapeBlock( optFn: ((String?) -> ())?, optFn2: ((String?) -> ())?) { noescapeBlock3(optFn, optFn2, "Foobar") } @_silgen_name("_returnOptionalEscape") public func returnOptionalEscape() -> (() ->())? // Make sure that we keep the escaping closure alive accross the ultimate call. // CHECK-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[NONE:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // CHECK: [[V0:%.*]] = function_ref @_returnOptionalEscape // CHECK: [[V1:%.*]] = apply [[V0]] // CHECK: retain_value [[V1]] // CHECK: switch_enum [[V1]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[V2:%.*]] : $@callee_guaranteed () -> ()): // CHECK: [[V1_UNWRAPPED:%.*]] = unchecked_enum_data [[V1]] // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[V1_UNWRAPPED]] // CHECK: [[SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[CVT]] // CHECK: strong_release [[V2]] // CHECK: br [[NEXT_BB:bb[0-9]+]]([[SOME]] : // // CHECK: [[NEXT_BB]]([[SOME_PHI:%.*]] : // CHECK: switch_enum [[SOME_PHI]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB_2:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB_2:bb[0-9]+]] // // CHECK: [[SOME_BB_2]]([[SOME_PHI_PAYLOAD:%.*]] : // CHECK: [[PAI:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[SOME_PHI_PAYLOAD]]) // CHECK: [[MDI:%.*]] = mark_dependence [[PAI]] // CHECK: strong_retain [[MDI]] // CHECK: [[BLOCK_SLOT:%.*]] = alloc_stack // CHECK: [[BLOCK_PROJ:%.*]] = project_block_storage [[BLOCK_SLOT]] // CHECK: store [[MDI]] to [[BLOCK_PROJ]] // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_SLOT]] // CHECK: release_value [[NONE]] // CHECK: [[SOME_2:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[MDI]] // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BLOCK_SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[BLOCK_COPY]] // CHECK: br bb5([[BLOCK_SOME]] : ${{.*}}, [[SOME_2]] : // // CHECK: bb4: // CHECK: [[NONE_BLOCK:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // CHECK: br bb5([[NONE_BLOCK]] : {{.*}}, [[NONE]] : // // CHECK: bb5([[BLOCK_PHI:%.*]] : $Optional<{{.*}}>, [[SWIFT_CLOSURE_PHI:%.*]] : // CHECK: [[F:%.*]] = function_ref @noescapeBlock // CHECK: apply [[F]]([[BLOCK_PHI]]) // CHECK: release_value [[BLOCK_PHI]] // CHECK: release_value [[SWIFT_CLOSURE_PHI]] // CHECK-NEXT: return // NOPEEPHOLE-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () { // NOPEEPHOLE: bb0: // NOPEEPHOLE: [[NONE_1:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // NOPEEPHOLE: [[NONE_2:%.*]] = enum $Optional<{{.*}}>, #Optional.none!enumelt // NOPEEPHOLE: [[V0:%.*]] = function_ref @_returnOptionalEscape // NOPEEPHOLE: [[V1:%.*]] = apply [[V0]] // NOPEEPHOLE: switch_enum [[V1]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // NOPEEPHOLE: [[SOME_BB]]([[V2:%.*]]: $@callee_guaranteed () -> ()): // NOPEEPHOLE-NEXT: release_value [[NONE_2]] // NOPEEPHOLE-NEXT: [[CVT:%.*]] = convert_escape_to_noescape [[V2]] // NOPEEPHOLE-NEXT: [[SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[V2]] // NOPEEPHOLE-NEXT: [[NOESCAPE_SOME:%.*]] = enum $Optional<{{.*}}>, #Optional.some!enumelt, [[CVT]] // NOPEEPHOLE-NEXT: br bb2([[NOESCAPE_SOME]] : $Optional<{{.*}}>, [[SOME]] : // // NOPEEPHOLE: bb2([[NOESCAPE_SOME:%.*]] : $Optional<{{.*}}>, [[SOME:%.*]] : // NOPEEPHOLE: switch_enum [[NOESCAPE_SOME]] : $Optional<{{.*}}>, case #Optional.some!enumelt: [[SOME_BB_2:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB_2:bb[0-9]+]] // // NOPEEPHOLE: [[SOME_BB_2]]( // NOPEEPHOLE: br bb5 // // NOPEEPHOLE: [[NONE_BB_2]]: // NOPEEPHOLE: br bb5 // // NOPEEPHOLE: bb5([[BLOCK_PHI:%.*]] : $Optional<{{.*}}>, [[SWIFT_CLOSURE_PHI:%.*]] : // NOPEEPHOLE-NEXT: function_ref noescapeBlock // NOPEEPHOLE-NEXT: [[F:%.*]] = function_ref @noescapeBlock : // NOPEEPHOLE-NEXT: apply [[F]]([[BLOCK_PHI]]) // NOPEEPHOLE-NEXT: release_value [[BLOCK_PHI]] // NOPEEPHOLE-NEXT: tuple // NOPEEPHOLE-NEXT: release_value [[SOME]] // NOPEEPHOLE-NEXT: release_value [[SWIFT_CLOSURE_PHI]] // NOPEEPHOLE-NEXT: return // NOPEEPHOLE: } // end sil function '$s1A19bridgeNoescapeBlockyyF' public func bridgeNoescapeBlock() { noescapeBlock(returnOptionalEscape()) }
apache-2.0
b0c23b832947b2879784b8c4c407d2bf
48.214876
257
0.613938
3.060123
false
false
false
false
ileitch/SwiftState
SwiftState/StateRoute.swift
2
2202
// // StateRoute.swift // SwiftState // // Created by Yasuhiro Inami on 2014/08/04. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // public struct StateRoute<S: StateType> { public typealias Condition = ((transition: Transition) -> Bool) public typealias State = S public typealias Transition = StateTransition<State> public let transition: Transition public let condition: Condition? public init(transition: Transition, condition: Condition?) { self.transition = transition self.condition = condition } public init(transition: Transition, @autoclosure(escaping) condition: () -> Bool) { self.init(transition: transition, condition: { t in condition() }) } public func toTransition() -> Transition { return self.transition } public func toRouteChain() -> StateRouteChain<State> { var routes: [StateRoute<State>] = [] routes += [self] return StateRouteChain(routes: routes) } } //-------------------------------------------------- // MARK: - Custom Operators //-------------------------------------------------- /// e.g. [.State0, .State1] => .State2, allowing [0 => 2, 1 => 2] public func => <S: StateType>(leftStates: [S], right: S) -> StateRoute<S> { // NOTE: don't reuse "nil => nil + condition" for efficiency return StateRoute(transition: nil => right, condition: { transition -> Bool in return leftStates.contains(transition.fromState) }) } /// e.g. .State0 => [.State1, .State2], allowing [0 => 1, 0 => 2] public func => <S: StateType>(left: S, rightStates: [S]) -> StateRoute<S> { return StateRoute(transition: left => nil, condition: { transition -> Bool in return rightStates.contains(transition.toState) }) } /// e.g. [.State0, .State1] => [.State2, .State3], allowing [0 => 2, 0 => 3, 1 => 2, 1 => 3] public func => <S: StateType>(leftStates: [S], rightStates: [S]) -> StateRoute<S> { return StateRoute(transition: nil => nil, condition: { transition -> Bool in return leftStates.contains(transition.fromState) && rightStates.contains(transition.toState) }) }
mit
2b77cd18b47a33719fcbc06e3f276949
30.442857
100
0.601818
3.963964
false
false
false
false
intelygenz/NetClient-iOS
Example/Article.swift
1
956
// // Article.swift // Example // // Created by Alejandro Ruperez Hernando on 23/8/17. // import Foundation struct Article: Codable { public let title: String public init(title: String) { self.title = title } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let entry = try values.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .entry) title = try entry.decode(String.self, forKey: .title) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) var entry = container.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .entry) try entry.encode(title, forKey: .title) } enum CodingKeys: String, CodingKey { case entry = "entry" } enum AdditionalInfoKeys: String, CodingKey { case title = "title" } }
mit
e5429c6cc3158f41f43ba0cfa2560905
24.157895
96
0.656904
4.103004
false
false
false
false
mdmsua/Ausgaben.iOS
Ausgaben/Ausgaben/Picker.swift
1
1834
// // Picker.swift // Ausgaben // // Created by Dmytro Morozov on 20.02.16. // Copyright © 2016 Dmytro Morozov. All rights reserved. // public class Picker : NSObject, UIPickerViewDataSource, UIPickerViewDelegate { init(_ count: Int, value: Double? = 0.0, updated: (Double -> Void)? = nil) { self.count = count self.segments = [Int](count: count, repeatedValue: 0) self.updated = updated } private let count : Int private let updated: (Double -> Void)? private var last : Int { get { return self.count - 1 } } private var segments: [Int] private var decimals = [0, 0] public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return self.count + 3 } public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return component == self.count ? 1 : 10 } public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return component == self.count ? "," : String(row) } public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0...self.count: self.segments[component] = row case self.count+1...self.count+3: self.decimals[self.count+2-component] = row default: break } let m = self.segments.enumerate().reduce(0, combine: { $0 + Double($1.1) * pow(10.0, Double(self.last-$1.0)) }) let e = self.decimals.enumerate().reduce(0, combine: { $0 + Double($1.1) * pow(10.0, Double(-2+$1.0)) }) let temp = m + e if self.updated != nil { self.updated!(temp) } } }
mit
06526278bee84dc20beaa1e48d892c71
31.732143
119
0.592471
3.984783
false
false
false
false
kstaring/swift
test/SILOptimizer/devirt_contravariant_args.swift
7
1761
// RUN: %target-swift-frontend -O -primary-file %s -emit-sil -sil-inline-threshold 1000 -sil-verify-all | %FileCheck %s // Make sure that we can dig all the way through the class hierarchy and // protocol conformances. // CHECK-LABEL: sil hidden @_TF25devirt_contravariant_args6driverFT_T_ : $@convention(thin) () -> () { // CHECK: function_ref unknownC2 // CHECK: function_ref unknownC1 // CHECK: function_ref unknownC0 // CHECK: return // CHECK-NEXT: } @_silgen_name("unknownC0") func unknownC0(_ c : C0) -> () @_silgen_name("unknownC1") func unknownC1(_ c : C1) -> () @_silgen_name("unknownC2") func unknownC2(_ c : C2) -> () protocol P {} class C0 : P {} class C1 : C0 {} class C2 : C1 {} class B<T> { func performSomething(_ p : P) { doSomething(p as! C2) } func doSomething(_ c : C2) { unknownC2(c) } // See comment in protocol P //class func doSomethingMeta() { // unknown1b() //} } class B2<T> : B<T> { override func performSomething(_ p : P) { doSomething(p as! C1) } // When we have covariance in protocols, change this to B2. // We do not specialize typealias correctly now. //typealias X = B override func doSomething(_ c : C1) { unknownC1(c) } // See comment in protocol P //override class func doSomethingMeta() { // unknown2b() //} } class B3<T> : B2<T> { override func performSomething(_ p : P) { doSomething(p as! C0) } override func doSomething(_ c : C0) { unknownC0(c) } } func doSomething<T : P>(_ b : B<T>, _ t : T) { b.performSomething(t) } func driver() -> () { let b = B<C2>() let b2 = B2<C1>() let b3 = B3<C0>() let c0 = C0() let c1 = C1() let c2 = C2() doSomething(b, c2) doSomething(b2, c1) doSomething(b3, c0) } driver()
apache-2.0
72de05ff31f8579193fce580a815952f
18.786517
119
0.613856
2.88216
false
false
false
false
natecook1000/swift
test/expr/unary/keypath/salvage-with-other-type-errors.swift
2
1373
// RUN: %target-typecheck-verify-swift // Ensure that key path exprs can tolerate being re-type-checked when necessary // to diagnose other errors in adjacent exprs. struct P<T: K> { } struct S { init<B>(_ a: P<B>) { // expected-note {{where 'B' = 'String'}} fatalError() } } protocol K { } func + <Object>(lhs: KeyPath<A, Object>, rhs: String) -> P<Object> { fatalError() } // expected-error@+1{{}} func + (lhs: KeyPath<A, String>, rhs: String) -> P<String> { fatalError() } struct A { let id: String } extension A: K { static let j = S(\A.id + "id") // expected-error {{initializer 'init' requires that 'String' conform to 'K'}} } // SR-5034 struct B { let v: String func f1<T, E>(block: (T) -> E) -> B { return self } func f2<T, E: Equatable>(keyPath: KeyPath<T, E>) { } } func f3() { B(v: "").f1(block: { _ in }).f2(keyPath: \B.v) // expected-error{{}} } // SR-5375 protocol Bindable: class { } extension Bindable { func test<Value>(to targetKeyPath: ReferenceWritableKeyPath<Self, Value>, change: Value?) { if self[keyPath:targetKeyPath] != change { // expected-error{{}} // expected-note@-1{{overloads for '!=' exist with these partially matching parameter lists: (Self, Self), (_OptionalNilComparisonType, Wrapped?)}} self[keyPath: targetKeyPath] = change! } } }
apache-2.0
92af886a7614a0aa1f94f91e0d3bee6f
22.271186
153
0.608157
3.215457
false
false
false
false
makezwl/zhao
Nimble/Matchers/RaisesException.swift
80
3493
import Foundation internal func raiseExceptionMatcher<T>(message: String, matches: (NSException?) -> Bool) -> MatcherFunc<T> { return MatcherFunc { actualExpression, failureMessage in failureMessage.actualValue = nil failureMessage.postfixMessage = message // It would be better if this was part of Expression, but // Swift compiler crashes when expect() is inside a closure. var exception: NSException? var result: T? var capture = NMBExceptionCapture(handler: ({ e in exception = e }), finally: nil) capture.tryBlock { actualExpression.evaluate() return } return matches(exception) } } /// A Nimble matcher that succeeds when the actual expression raises an exception with /// the specified name and reason. public func raiseException(#named: String, #reason: String?) -> MatcherFunc<Any> { var theReason = "" if let reason = reason { theReason = reason } return raiseExceptionMatcher("raise exception named <\(named)> and reason <\(theReason)>") { exception in return exception?.name == named && exception?.reason == reason } } /// A Nimble matcher that succeeds when the actual expression raises an exception with /// the specified name. public func raiseException(#named: String) -> MatcherFunc<Any> { return raiseExceptionMatcher("raise exception named <\(named)>") { exception in return exception?.name == named } } /// A Nimble matcher that succeeds when the actual expression raises any exception. /// Please use a more specific raiseException() matcher when possible. public func raiseException() -> MatcherFunc<Any> { return raiseExceptionMatcher("raise any exception") { exception in return exception != nil } } @objc public class NMBObjCRaiseExceptionMatcher : NMBMatcher { var _name: String? var _reason: String? init(name: String?, reason: String?) { _name = name _reason = reason } public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let block: () -> Any? = ({ actualBlock(); return nil }) let expr = Expression(expression: block, location: location) if _name != nil && _reason != nil { return raiseException(named: _name!, reason: _reason).matches(expr, failureMessage: failureMessage) } else if _name != nil { return raiseException(named: _name!).matches(expr, failureMessage: failureMessage) } else { return raiseException().matches(expr, failureMessage: failureMessage) } } public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { return !matches(actualBlock, failureMessage: failureMessage, location: location) } var named: (name: String) -> NMBObjCRaiseExceptionMatcher { return ({ name in return NMBObjCRaiseExceptionMatcher(name: name, reason: self._reason) }) } var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher { return ({ reason in return NMBObjCRaiseExceptionMatcher(name: self._name, reason: reason) }) } } extension NMBObjCMatcher { public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher { return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil) } }
apache-2.0
4b3cc8c65f1b617ecef1d11c6a8b600b
35.768421
126
0.661609
5.069666
false
false
false
false
carabina/SwiftCSP
SwiftCSP/SwiftCSP/CircuitBoard.swift
1
1845
// // CircuitBoard.swift // SwiftCSP // // The SwiftCSP License (MIT) // // Copyright (c) 2015 David Kopec // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Cocoa class CircuitBoard: NSObject { //get hashable for free and dynamic access var height: Int = 1 var width: Int = 1 var color: NSColor = NSColor.redColor() var location: (Int, Int)? //generate the domain as a list of tuples of bottom left corners func generateDomain(boardWidth: Int, boardHeight: Int) -> [(Int, Int)] { var domain: [(Int, Int)] = [] for (var x: Int = 0; x < (boardWidth - width + 1); x++) { for (var y: Int = 0; y < (boardHeight - height + 1); y++) { let temp = (x, y) domain.append(temp) } } return domain } }
mit
00fa33f7cdfcd5ef349e5b9bc46c2411
39.130435
81
0.678591
4.183673
false
false
false
false
Walkersneps/SnepsBot_Discord
Sources/SnepsBot_Discord/Commands/Control.swift
1
1780
// // Control.swift // SnepsBot_Discord // // Created by Walter Carli on 11/09/17. // // import Foundation import Sword struct Control { init(bot: Sword, firstPrefix: Character) { var p = firstPrefix //use variable so we can change it //every time a message is recieved... bot.on(.messageCreate) { data in let msg = data as! Message let txt = msg.content //ping if txt == "\(p)ping" { msg.reply(with: "Pong!") } //join server via invite if txt.hasPrefix("\(p)joinServer") { let inviteId = txt.substring(from: txt.index(txt.startIndex, offsetBy: 12)) msg.reply(with: "InviteId is '\(inviteId)'. Joining NOW!") bot.getInvite(inviteId, then: { array, error in}) msg.reply(with: "Joined Server!") } //change prefix if txt.hasPrefix("\(p)prefix") { let newPrefix = txt.substring(from: txt.index(txt.startIndex, offsetBy: 8)) if newPrefix.characters.array.count == 1 { p = newPrefix.characters.array[0] msg.reply(with: "Prefix successfully changed to '\(p)' ! YAY! Party!") } else { msg.reply(with: "Please, insert a single character as a prefix!") } } //change status if txt.hasPrefix("\(p)status") { let newStatus = txt.substring(from: txt.index(txt.startIndex, offsetBy: 8)) bot.editStatus(to: "online", playing: newStatus) msg.reply(with: "Status updated!") } } } }
mit
16d1ab9c6b924f2e1255336c214624ee
24.070423
91
0.499438
4.309927
false
false
false
false
SteveKChiu/CoreDataMonk
CoreDataMonk/ViewDataProvider.swift
1
4261
// // https://github.com/SteveKChiu/CoreDataMonk // // Copyright 2015, Steve K. Chiu <[email protected]> // // The MIT License (http://www.opensource.org/licenses/mit-license.php) // // 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 CoreData //--------------------------------------------------------------------------- open class ViewDataProvider<EntityType: NSManagedObject> { private var controller: NSFetchedResultsController<EntityType>? private var filteredSections: [[EntityType]]? public typealias ObjectFilter = ([[EntityType]]) -> [[EntityType]] public var objectFilter: ObjectFilter? open var fetchedResultsController: NSFetchedResultsController<EntityType>? { get { return self.controller } set { self.controller = newValue } } open func numberOfSections() -> Int { if let sections = self.filteredSections { return sections.count } else { return self.controller?.sections?.count ?? 0 } } open func numberOfObjectsInSection(_ section: Int) -> Int { if let sections = self.filteredSections { if section < sections.count { return sections[section].count } } else { if let sections = self.controller?.sections, section < sections.count { return sections[section].numberOfObjects } } return 0 } open func objectAtIndexPath(_ indexPath: IndexPath) -> EntityType? { if let sections = self.filteredSections { if indexPath.section < sections.count { let objects = sections[indexPath.section] if indexPath.item < objects.count { return objects[indexPath.item] } } return nil } else { return self.controller?.object(at: indexPath) } } open func indexPathForObject(_ object: EntityType) -> IndexPath? { if let sections = self.filteredSections { for (sidx, section) in sections.enumerated() { for (idx, item) in section.enumerated() { if item == object { return IndexPath(item: idx, section: sidx) } } } return nil } else { return self.controller?.indexPath(forObject: object) } } open func filter() { if let objectFilter = self.objectFilter, let sections = self.controller?.sections { var filteredSections = [[EntityType]]() for section in sections { if let objects = section.objects as? [EntityType] { filteredSections.append(objects) } else { filteredSections.append([EntityType]()) } } self.filteredSections = objectFilter(filteredSections) } else { self.filteredSections = nil } } open func reload() throws { try self.fetchedResultsController?.performFetch() self.filter() } }
mit
4161f298e4aaa1556b912bd843aafe76
34.806723
83
0.597747
5.152358
false
false
false
false
clwm01/RTKitDemo
RCToolsDemo/RCToolsDemo/ChartViewController.swift
2
8081
// // ChartViewController.swift // RCToolsDemo // // Created by Rex Tsao on 31/5/2016. // Copyright © 2016 rexcao. All rights reserved. // import UIKit class ChartViewController: UIViewController { private var dataGroup: [[CGFloat]] = [ [5, 4, 10, 22, 16, 14], [26, 18, 10, 3, 16, 14], [45, 4, 2, 32, 19, 14], [30, 21, 14, 28, 8, 3], [6, 45, 12, 20, 15, 17], [10, 12, 25, 22, 16, 19], [19, 16, 10, 18, 65, 48] ] // private var offsetX: CGFloat = 0 { // willSet { // if !self.automaticSwitch { // // decrease part // if self.currentScreenIndex > 0 { // if newValue < self.offsetX || newValue == 0 { // self.currentScreenIndex -= 1 // // Trigger redraw curve line here. // self.redrawChart() // } // } // // increase part // if self.currentScreenIndex < self.dataGroup.count - 1 { // // X of contentOffset is at most the whole width of one screen. // if newValue > self.offsetX || newValue == self.scrollView!.width { // self.currentScreenIndex += 1 // // Trigger redraw curve line here. // self.redrawChart() // } // } // } // print("current index: \(self.currentScreenIndex)") // print(">>>>>>>>offsetX at endDicelerating: \(self.offsetX)>>>>>>>\n") // } // } /// Used to indicate that whether the scrollView is scrolled automatically or via program. /// If the scrollView scrolls conform to program, this does not means that you should decrease/increse /// the currentScreenIndex, otherwise, you should adjust the currentScreenIndex. // private var automaticSwitch: Bool = false /// Current index of screen. private var currentScreenIndex: Int = 6 /// X of contentOffset at when scrollViewBeginDragging. private var beginOffsetX: CGFloat = 0 /// X of contentOffset at when scrollViewDidDecelerating. private var endOffsetX: CGFloat = 0 private var scrollView: UIScrollView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() // Disable automatically adjust scroll view insets when use navigationBar. self.automaticallyAdjustsScrollViewInsets = false self.attachScroll() // Set the default offsetX // self.directSetOffsetX(self.view.width) // self.scrollToSpecificIndex(1) self.beginOffsetX = self.view.width self.endOffsetX = self.view.width } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func attachScroll() { self.scrollView = UIScrollView(frame: CGRectMake(0, 100, self.view.width, 300)) self.scrollView?.delegate = self self.scrollView?.pagingEnabled = true self.view.addSubview(scrollView!) let pluckedData = self.pluckData() let chartView = ChartView( dataGroup: pluckedData, unitSize: CGSizeMake(self.scrollView!.width, self.scrollView!.height)) self.scrollView?.contentSize = chartView.frame.size self.scrollToSpecificIndex(1) self.scrollView?.addSubview(chartView) print("-count of pluckedData: \(pluckedData.count)") } private func pluckData() -> [[CGFloat]] { var tmp = [[CGFloat]]() if self.dataGroup.count > 0 { if self.currentScreenIndex == 0 { if self.dataGroup.count > 1 { tmp.append(self.dataGroup[0]) tmp.append(self.dataGroup[1]) } else { tmp.append(self.dataGroup[0]) } } else if self.currentScreenIndex == self.dataGroup.count - 1 { if self.dataGroup.count > 1 { tmp.append(self.dataGroup[self.currentScreenIndex - 1]) tmp.append(self.dataGroup[self.currentScreenIndex]) } } else { tmp.append(self.dataGroup[self.currentScreenIndex - 1]) tmp.append(self.dataGroup[self.currentScreenIndex]) tmp.append(self.dataGroup[self.currentScreenIndex + 1]) } } return tmp } private func scrollToSpecificIndex(index: Int) { print("-scroll to index: \(index)") // dispatch_async(dispatch_get_main_queue(), { // self.scrollView?.scrollRectToVisible(CGRectMake(CGFloat(index) * self.scrollView!.width, 0, self.scrollView!.width, self.scrollView!.height), animated: false) // }) self.scrollView?.contentOffset = CGPointMake(CGFloat(index) * self.scrollView!.width, 0) } private func getIndexOfScroll() -> Int { var currentScrollIndex = 0 if self.dataGroup.count > 0 { if self.currentScreenIndex == 0 { currentScrollIndex = 0 } else if self.currentScreenIndex == self.dataGroup.count - 1 { currentScrollIndex = 1 } else { currentScrollIndex = 1 } } return currentScrollIndex } private func redrawChart() { for view in self.scrollView!.subviews { view.removeFromSuperview() } let pluckedData = self.pluckData() let chartView = ChartView(dataGroup: pluckedData, unitSize: CGSizeMake(self.scrollView!.width, self.scrollView!.height)) chartView.layer.opacity = 0.0 self.scrollView?.contentSize = chartView.frame.size self.scrollView?.addSubview(chartView) self.scrollToSpecificIndex(self.getIndexOfScroll()) chartView.layer.opacity = 1.0 print("-count of pluckedData: \(pluckedData.count)") // if self.currentScreenIndex == self.dataGroup.count - 1 { // self.directSetOffsetX(self.scrollView!.contentSize.width - self.scrollView!.width) // } } // private func directSetOffsetX(value: CGFloat) { // self.automaticSwitch = true // self.offsetX = value // self.automaticSwitch = false // } } extension ChartViewController: UIScrollViewDelegate { func scrollViewWillBeginDragging(scrollView: UIScrollView) { print("viewWillBeginDragging contentOffset: \(scrollView.contentOffset)") self.beginOffsetX = scrollView.contentOffset.x } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { print("viewDidEndDecelerating contentOffset: \(scrollView.contentOffset)") self.endOffsetX = scrollView.contentOffset.x if self.endOffsetX > self.beginOffsetX { print("to left") if self.currentScreenIndex < self.dataGroup.count - 1 { self.currentScreenIndex += 1 self.redrawChart() } } if self.endOffsetX < self.beginOffsetX { print("to right") if self.currentScreenIndex > 0 { self.currentScreenIndex -= 1 self.redrawChart() } } print("current index: \(self.currentScreenIndex)") // // The last screen // if self.currentScreenIndex == self.dataGroup.count - 1 { // self.directSetOffsetX(self.scrollView!.width) // return // } // // // The first screen // if self.currentScreenIndex == 0 { // self.directSetOffsetX(0) // return // } // // if scrollView.contentOffset.x >= 0 && scrollView.contentOffset.x <= scrollView.contentSize.width - scrollView.width { // self.offsetX = scrollView.contentOffset.x // } } }
mit
30d721b5def571a7930bf6c03a81fdde
36.235023
172
0.569554
4.570136
false
false
false
false
tichise/MaterialDesignSymbol
Sources/MaterialDesignSymbol/MaterialDesignIcon1.swift
1
20238
// // MaterialDesignIcon1 // // Created by tichise on 2015/5/7 15/05/07. // Copyright (c) 2015 tichise. All rights reserved. // import UIKit /** * マテリアルデザインアイコンのコードを返すクラス */ extension MaterialDesignIcon { public static let threeDRotation24px = "\u{e600}" public static let threeDRotation48px = "\u{e601}" public static let accessibility24px = "\u{e602}" public static let accessibility48px = "\u{e603}" public static let accountBalance24px = "\u{e604}" public static let accountBalance48px = "\u{e605}" public static let accountBalanceWallet24px = "\u{e606}" public static let accountBalanceWallet48px = "\u{e607}" public static let accountBox18px = "\u{e608}" public static let accountBox24px = "\u{e609}" public static let accountBox48px = "\u{e60a}" public static let accountChild24px = "\u{e60b}" public static let accountChild48px = "\u{e60c}" public static let accountCircle18px = "\u{e60d}" public static let accountCircle24px = "\u{e60e}" public static let accountCircle48px = "\u{e60f}" public static let addShoppingCart24px = "\u{e610}" public static let addShoppingCart48px = "\u{e611}" public static let alarm24px = "\u{e612}" public static let alarm48px = "\u{e613}" public static let alarmAdd24px = "\u{e614}" public static let alarmAdd48px = "\u{e615}" public static let alarmOff24px = "\u{e616}" public static let alarmOff48px = "\u{e617}" public static let alarmOn24px = "\u{e618}" public static let alarmOn48px = "\u{e619}" public static let android24px = "\u{e61a}" public static let android48px = "\u{e61b}" public static let announcement24px = "\u{e61c}" public static let announcement48px = "\u{e61d}" public static let aspectRatio24px = "\u{e61e}" public static let aspectRatio48px = "\u{e61f}" public static let assessment24px = "\u{e620}" public static let assessment48px = "\u{e621}" public static let assignment24px = "\u{e622}" public static let assignment48px = "\u{e623}" public static let assignmentInd24px = "\u{e624}" public static let assignmentInd48px = "\u{e625}" public static let assignmentLate24px = "\u{e626}" public static let assignmentLate48px = "\u{e627}" public static let assignmentReturn24px = "\u{e628}" public static let assignmentReturn48px = "\u{e629}" public static let assignmentReturned24px = "\u{e62a}" public static let assignmentReturned48px = "\u{e62b}" public static let assignmentTurnedIn24px = "\u{e62c}" public static let assignmentTurnedIn48px = "\u{e62d}" public static let autorenew24px = "\u{e62e}" public static let autorenew48px = "\u{e62f}" public static let backup24px = "\u{e630}" public static let backup48px = "\u{e631}" public static let book24px = "\u{e632}" public static let book48px = "\u{e633}" public static let bookmark24px = "\u{e634}" public static let bookmark48px = "\u{e635}" public static let bookmarkOutline24px = "\u{e636}" public static let bookmarkOutline48px = "\u{e637}" public static let bugReport24px = "\u{e638}" public static let bugReport48px = "\u{e639}" public static let cached24px = "\u{e63a}" public static let cached48px = "\u{e63b}" public static let class24px = "\u{e63c}" public static let class48px = "\u{e63d}" public static let creditCard24px = "\u{e63e}" public static let creditCard48px = "\u{e63f}" public static let dashboard24px = "\u{e640}" public static let dashboard48px = "\u{e641}" public static let delete24px = "\u{e642}" public static let delete48px = "\u{e643}" public static let description24px = "\u{e644}" public static let description48px = "\u{e645}" public static let dns24px = "\u{e646}" public static let dns48px = "\u{e647}" public static let done24px = "\u{e648}" public static let done48px = "\u{e649}" public static let doneAll24px = "\u{e64a}" public static let doneAll48px = "\u{e64b}" public static let event18px = "\u{e64c}" public static let event24px = "\u{e64d}" public static let event48px = "\u{e64e}" public static let exitToApp24px = "\u{e64f}" public static let exitToApp48px = "\u{e650}" public static let explore24px = "\u{e651}" public static let explore48px = "\u{e652}" public static let extension24px = "\u{e653}" public static let extension48px = "\u{e654}" public static let faceUnlock24px = "\u{e655}" public static let faceUnlock48px = "\u{e656}" public static let favorite24px = "\u{e657}" public static let favorite48px = "\u{e658}" public static let favoriteOutline24px = "\u{e659}" public static let favoriteOutline48px = "\u{e65a}" public static let findInPage24px = "\u{e65b}" public static let findInPage48px = "\u{e65c}" public static let findReplace24px = "\u{e65d}" public static let findReplace48px = "\u{e65e}" public static let flipToBack24px = "\u{e65f}" public static let flipToBack48px = "\u{e660}" public static let flipToFront24px = "\u{e661}" public static let flipToFront48px = "\u{e662}" public static let getApp24px = "\u{e663}" public static let getApp48px = "\u{e664}" public static let grade24px = "\u{e665}" public static let grade48px = "\u{e666}" public static let groupWork24px = "\u{e667}" public static let groupWork48px = "\u{e668}" public static let help24px = "\u{e669}" public static let help48px = "\u{e66a}" public static let highlightRemove24px = "\u{e66b}" public static let highlightRemove48px = "\u{e66c}" public static let history24px = "\u{e66d}" public static let history48px = "\u{e66e}" public static let home24px = "\u{e66f}" public static let home48px = "\u{e670}" public static let https24px = "\u{e671}" public static let https48px = "\u{e672}" public static let info24px = "\u{e673}" public static let info48px = "\u{e674}" public static let infoOutline24px = "\u{e675}" public static let infoOutline48px = "\u{e676}" public static let input24px = "\u{e677}" public static let input48px = "\u{e678}" public static let invertColors24px = "\u{e679}" public static let invertColors48px = "\u{e67a}" public static let label24px = "\u{e67b}" public static let label48px = "\u{e67c}" public static let labelOutline24px = "\u{e67d}" public static let labelOutline48px = "\u{e67e}" public static let language24px = "\u{e67f}" public static let language48px = "\u{e680}" public static let launch24px = "\u{e681}" public static let launch48px = "\u{e682}" public static let list24px = "\u{e683}" public static let list48px = "\u{e684}" public static let lock24px = "\u{e685}" public static let lock48px = "\u{e686}" public static let lockOpen24px = "\u{e687}" public static let lockOpen48px = "\u{e688}" public static let lockOutline24px = "\u{e689}" public static let lockOutline48px = "\u{e68a}" public static let loyalty24px = "\u{e68b}" public static let loyalty48px = "\u{e68c}" public static let markunreadMailbox24px = "\u{e68d}" public static let markunreadMailbox48px = "\u{e68e}" public static let noteAdd24px = "\u{e68f}" public static let noteAdd48px = "\u{e690}" public static let openInBrowser24px = "\u{e691}" public static let openInBrowser48px = "\u{e692}" public static let openInNew24px = "\u{e693}" public static let openInNew48px = "\u{e694}" public static let openWith24px = "\u{e695}" public static let openWith48px = "\u{e696}" public static let pageview24px = "\u{e697}" public static let pageview48px = "\u{e698}" public static let payment24px = "\u{e699}" public static let payment48px = "\u{e69a}" public static let permCameraMic24px = "\u{e69b}" public static let permCameraMic48px = "\u{e69c}" public static let permContactCal24px = "\u{e69d}" public static let permContactCal48px = "\u{e69e}" public static let permDataSetting24px = "\u{e69f}" public static let permDataSetting48px = "\u{e6a0}" public static let permDeviceInfo24px = "\u{e6a1}" public static let permDeviceInfo48px = "\u{e6a2}" public static let permIdentity24px = "\u{e6a3}" public static let permIdentity48px = "\u{e6a4}" public static let permMedia24px = "\u{e6a5}" public static let permMedia48px = "\u{e6a6}" public static let permPhoneMsg24px = "\u{e6a7}" public static let permPhoneMsg48px = "\u{e6a8}" public static let permScanWifi24px = "\u{e6a9}" public static let permScanWifi48px = "\u{e6aa}" public static let pictureInPicture24px = "\u{e6ab}" public static let pictureInPicture48px = "\u{e6ac}" public static let polymer24px = "\u{e6ad}" public static let polymer48px = "\u{e6ae}" public static let print24px = "\u{e6af}" public static let print48px = "\u{e6b0}" public static let queryBuilder24px = "\u{e6b1}" public static let queryBuilder48px = "\u{e6b2}" public static let questionAnswer24px = "\u{e6b3}" public static let questionAnswer48px = "\u{e6b4}" public static let receipt24px = "\u{e6b5}" public static let receipt48px = "\u{e6b6}" public static let redeem24px = "\u{e6b7}" public static let redeem48px = "\u{e6b8}" public static let reorder24px = "\u{e6b9}" public static let reportProblem24px = "\u{e6ba}" public static let reportProblem48px = "\u{e6bb}" public static let restore24px = "\u{e6bc}" public static let restore48px = "\u{e6bd}" public static let room24px = "\u{e6be}" public static let room48px = "\u{e6bf}" public static let schedule24px = "\u{e6c0}" public static let schedule48px = "\u{e6c1}" public static let search24px = "\u{e6c2}" public static let search48px = "\u{e6c3}" public static let settings24px = "\u{e6c4}" public static let settings48px = "\u{e6c5}" public static let settingsApplications24px = "\u{e6c6}" public static let settingsApplications48px = "\u{e6c7}" public static let settingsBackupRestore24px = "\u{e6c8}" public static let settingsBackupRestore48px = "\u{e6c9}" public static let settingsBluetooth24px = "\u{e6ca}" public static let settingsBluetooth48px = "\u{e6cb}" public static let settingsCell24px = "\u{e6cc}" public static let settingsCell48px = "\u{e6cd}" public static let settingsDisplay24px = "\u{e6ce}" public static let settingsDisplay48px = "\u{e6cf}" public static let settingsEthernet24px = "\u{e6d0}" public static let settingsEthernet48px = "\u{e6d1}" public static let settingsInputAntenna24px = "\u{e6d2}" public static let settingsInputAntenna48px = "\u{e6d3}" public static let settingsInputComponent24px = "\u{e6d4}" public static let settingsInputComponent48px = "\u{e6d5}" public static let settingsInputComposite24px = "\u{e6d6}" public static let settingsInputComposite48px = "\u{e6d7}" public static let settingsInputHdmi24px = "\u{e6d8}" public static let settingsInputHdmi48px = "\u{e6d9}" public static let settingsInputSvideo24px = "\u{e6da}" public static let settingsInputSvideo48px = "\u{e6db}" public static let settingsOverscan24px = "\u{e6dc}" public static let settingsOverscan48px = "\u{e6dd}" public static let settingsPhone24px = "\u{e6de}" public static let settingsPhone48px = "\u{e6df}" public static let settingsPower24px = "\u{e6e0}" public static let settingsPower48px = "\u{e6e1}" public static let settingsRemote24px = "\u{e6e2}" public static let settingsRemote48px = "\u{e6e3}" public static let settingsVoice24px = "\u{e6e4}" public static let settingsVoice48px = "\u{e6e5}" public static let shop24px = "\u{e6e6}" public static let shop48px = "\u{e6e7}" public static let shopTwo24px = "\u{e6e8}" public static let shopTwo48px = "\u{e6e9}" public static let shoppingBasket24px = "\u{e6ea}" public static let shoppingBasket48px = "\u{e6eb}" public static let shoppingCart24px = "\u{e6ec}" public static let shoppingCart48px = "\u{e6ed}" public static let speakerNotes24px = "\u{e6ee}" public static let speakerNotes48px = "\u{e6ef}" public static let spellcheck24px = "\u{e6f0}" public static let spellcheck48px = "\u{e6f1}" public static let starRate24px = "\u{e6f2}" public static let starRate48px = "\u{e6f3}" public static let stars24px = "\u{e6f4}" public static let stars48px = "\u{e6f5}" public static let store24px = "\u{e6f6}" public static let store48px = "\u{e6f7}" public static let subject24px = "\u{e6f8}" public static let subject48px = "\u{e6f9}" public static let supervisorAccount24px = "\u{e6fa}" public static let swapHoriz24px = "\u{e6fb}" public static let swapHoriz48px = "\u{e6fc}" public static let swapVert24px = "\u{e6fd}" public static let swapVert48px = "\u{e6fe}" public static let swapVertCircle24px = "\u{e6ff}" public static let swapVertCircle48px = "\u{e700}" public static let systemUpdateTv24px = "\u{e701}" public static let systemUpdateTv48px = "\u{e702}" public static let tab24px = "\u{e703}" public static let tab48px = "\u{e704}" public static let tabUnselected24px = "\u{e705}" public static let tabUnselected48px = "\u{e706}" public static let theaters24px = "\u{e707}" public static let theaters48px = "\u{e708}" public static let thumbDown24px = "\u{e709}" public static let thumbDown48px = "\u{e70a}" public static let thumbUp24px = "\u{e70b}" public static let thumbUp48px = "\u{e70c}" public static let thumbsUpDown24px = "\u{e70d}" public static let thumbsUpDown48px = "\u{e70e}" public static let toc24px = "\u{e70f}" public static let toc48px = "\u{e710}" public static let today24px = "\u{e711}" public static let today48px = "\u{e712}" public static let trackChanges24px = "\u{e713}" public static let trackChanges48px = "\u{e714}" public static let translate24px = "\u{e715}" public static let translate48px = "\u{e716}" public static let trendingDown24px = "\u{e717}" public static let trendingDown48px = "\u{e718}" public static let trendingNeutral24px = "\u{e719}" public static let trendingNeutral48px = "\u{e71a}" public static let trendingUp24px = "\u{e71b}" public static let trendingUp48px = "\u{e71c}" public static let turnedIn24px = "\u{e71d}" public static let turnedIn48px = "\u{e71e}" public static let turnedInNot24px = "\u{e71f}" public static let turnedInNot48px = "\u{e720}" public static let verifiedUser24px = "\u{e721}" public static let verifiedUser48px = "\u{e722}" public static let viewAgenda24px = "\u{e723}" public static let viewAgenda48px = "\u{e724}" public static let viewArray24px = "\u{e725}" public static let viewArray48px = "\u{e726}" public static let viewCarousel24px = "\u{e727}" public static let viewCarousel48px = "\u{e728}" public static let viewColumn24px = "\u{e729}" public static let viewColumn48px = "\u{e72a}" public static let viewDay24px = "\u{e72b}" public static let viewDay48px = "\u{e72c}" public static let viewHeadline24px = "\u{e72d}" public static let viewHeadline48px = "\u{e72e}" public static let viewList24px = "\u{e72f}" public static let viewList48px = "\u{e730}" public static let viewModule24px = "\u{e731}" public static let viewModule48px = "\u{e732}" public static let viewQuilt24px = "\u{e733}" public static let viewQuilt48px = "\u{e734}" public static let viewStream24px = "\u{e735}" public static let viewStream48px = "\u{e736}" public static let viewWeek24px = "\u{e737}" public static let viewWeek48px = "\u{e738}" public static let visibility24px = "\u{e739}" public static let visibility48px = "\u{e73a}" public static let visibilityOff24px = "\u{e73b}" public static let visibilityOff48px = "\u{e73c}" public static let walletGiftcard24px = "\u{e73d}" public static let walletGiftcard48px = "\u{e73e}" public static let walletMembership24px = "\u{e73f}" public static let walletMembership48px = "\u{e740}" public static let walletTravel24px = "\u{e741}" public static let walletTravel48px = "\u{e742}" public static let work24px = "\u{e743}" public static let work48px = "\u{e744}" public static let error18px = "\u{e745}" public static let error24px = "\u{e746}" public static let error36px = "\u{e747}" public static let error48px = "\u{e748}" public static let warning18px = "\u{e749}" public static let warning24px = "\u{e74a}" public static let warning36px = "\u{e74b}" public static let warning48px = "\u{e74c}" public static let album24px = "\u{e74d}" public static let album48px = "\u{e74e}" public static let avTimer24px = "\u{e74f}" public static let avTimer48px = "\u{e750}" public static let closedCaption24px = "\u{e751}" public static let closedCaption48px = "\u{e752}" public static let equalizer24px = "\u{e753}" public static let equalizer48px = "\u{e754}" public static let explicit24px = "\u{e755}" public static let explicit48px = "\u{e756}" public static let fastForward24px = "\u{e757}" public static let fastForward48px = "\u{e758}" public static let fastRewind24px = "\u{e759}" public static let fastRewind48px = "\u{e75a}" public static let games24px = "\u{e75b}" public static let games48px = "\u{e75c}" public static let hearing24px = "\u{e75d}" public static let hearing48px = "\u{e75e}" public static let highQuality24px = "\u{e75f}" public static let highQuality48px = "\u{e760}" public static let loop24px = "\u{e761}" public static let loop48px = "\u{e762}" public static let mic24px = "\u{e763}" public static let mic48px = "\u{e764}" public static let micNone24px = "\u{e765}" public static let micNone48px = "\u{e766}" public static let micOff24px = "\u{e767}" public static let micOff48px = "\u{e768}" public static let movie24px = "\u{e769}" public static let movie48px = "\u{e76a}" public static let myLibraryAdd24px = "\u{e76b}" public static let myLibraryAdd48px = "\u{e76c}" public static let myLibraryBooks24px = "\u{e76d}" public static let myLibraryBooks48px = "\u{e76e}" public static let myLibraryMusic24px = "\u{e76f}" public static let myLibraryMusic48px = "\u{e770}" public static let newReleases24px = "\u{e771}" public static let newReleases48px = "\u{e772}" public static let notInterested24px = "\u{e773}" public static let notInterested48px = "\u{e774}" public static let pause24px = "\u{e775}" public static let pause48px = "\u{e776}" public static let pauseCircleFill24px = "\u{e777}" public static let pauseCircleFill48px = "\u{e778}" public static let pauseCircleOutline24px = "\u{e779}" public static let pauseCircleOutline48px = "\u{e77a}" public static let playArrow24px = "\u{e77b}" public static let playArrow48px = "\u{e77c}" public static let playCircleFill24px = "\u{e77d}" public static let playCircleFill48px = "\u{e77e}" public static let playCircleOutline24px = "\u{e77f}" public static let playCircleOutline48px = "\u{e780}" public static let playShoppingBag24px = "\u{e781}" public static let playShoppingBag48px = "\u{e782}" public static let playlistAdd24px = "\u{e783}" public static let playlistAdd48px = "\u{e784}" public static let queue24px = "\u{e785}" public static let queue48px = "\u{e786}" public static let queueMusic24px = "\u{e787}" public static let queueMusic48px = "\u{e788}" public static let radio24px = "\u{e789}" public static let radio48px = "\u{e78a}" public static let recentActors24px = "\u{e78b}" public static let recentActors48px = "\u{e78c}" public static let repeat24px = "\u{e78d}" public static let repeat48px = "\u{e78e}" }
mit
aee25535febfe44bc72766296b4b6dec
47.891041
61
0.680567
3.231754
false
false
false
false
southfox/jfwindguru
JFWindguru/Classes/Model/User.swift
1
7806
// // User.swift // Pods // // Created by javierfuchs on 7/11/17. // // import Foundation /* * User * * Discussion: * Represents a model information of the weather data inside the model id * At this moment public models are all "3" * The information contained is of type Forecast (only one object) * * { * "id_user": 0, * "username": "", * "id_country": 0, * "wind_units": "knots", * "temp_units": "c", * "wave_units": "m", * "pro": 0, * "no_ads": 0, * "view_hours_from": 3, * "view_hours_to": 22, * "temp_limit": 10, * "wind_rating_limits": [ 10.63, 15.57, 19.41 ], * "colors": { * "wind": [ * [ 0, 255, 255, 255 ], * [ 5, 255, 255, 255 ], * [ 8.9, 103, 247, 241 ], * [ 13.5, 0, 255, 0 ], * [ 18.8, 255, 240, 0 ], * [ 24.7, 255, 50, 44 ], * [ 31.7, 255, 10, 200 ], * [ 38, 255, 0, 255 ], * [ 45, 150, 50, 255 ], * [ 60, 60, 60, 255 ], * [ 70, 0, 0, 255 ] * ], * "temp": [ * [-25, 80, 255, 220 ], * [-15, 171, 190, 255 ], * [ 0, 255, 255, 255 ], * [ 10, 255, 255, 100 ], * [ 20, 255, 170, 0 ], * [ 30, 255, 50, 50 ], * [ 35, 255, 0, 110 ], * [ 40, 255, 0, 160 ], * [ 50, 255, 80, 220 ] * ], * "cloud": [ * [ 0, 255, 255, 255 ], * [ 100, 120, 120, 120 ] * ], * "precip": [ * [ 0, 255, 255, 255 ], * [ 9, 115, 115, 255 ], * [ 30, 115, 115, 255 ] * ], * "precip1": [ * [ 0, 255, 255, 255 ], * [ 3, 115, 115, 255 ], * [ 10, 115, 115, 255 ] * ], * "press": [ * [ 900, 80, 255, 220 ], * [ 1000, 255, 255, 255 ], * [ 1070, 115, 115, 255 ] * ], * "rh": [ * [ 0, 171, 190, 255 ], * [ 50, 255, 255, 255 ], * [ 100, 255, 255, 0 ] * ], * "htsgw": [ * [ 0, 255, 255, 255 ], * [ 0.3, 255, 255, 255 ], * [ 4, 120, 120, 255 ], * [ 10, 255, 80, 100 ], * [ 15, 255, 200, 100 ] * ], * "perpw": [ * [ 0, 255, 255, 255 ], * [ 10, 255, 255, 255], * [ 20, 252, 81, 81] * ] * } * } * */ public class User: Object, Mappable { typealias ListColor = [Color] var id_user : Int = 0 var username: String? var id_country : Int = 0 var wind_units: String? var temp_units: String? var wave_units: String? var pro : Int = 0 var no_ads : Int = 0 var view_hours_from : Int = 0 var view_hours_to : Int = 0 var temp_limit : Int = 0 var wind_rating_limits = [Float]() var colors_wind = ListColor() var colors_temp = ListColor() var colors_cloud = ListColor() var colors_precip = ListColor() var colors_precip1 = ListColor() var colors_press = ListColor() var colors_rh = ListColor() var colors_htsgw = ListColor() var colors_perpw = ListColor() required public convenience init(map: [String:Any]) { self.init() mapping(map: map) } public func mapping(map: [String:Any]) { var colors = Dictionary<String, [[Float]]>() id_user = map["id_user"] as? Int ?? 0 username = map["username"] as? String ?? nil id_country = map["id_country"] as? Int ?? 0 wind_units = map["wind_units"] as? String ?? nil temp_units = map["temp_units"] as? String ?? nil wave_units = map["wave_units"] as? String ?? nil pro = map["pro"] as? Int ?? 0 no_ads = map["no_ads"] as? Int ?? 0 view_hours_from = map["view_hours_from"] as? Int ?? 0 view_hours_to = map["view_hours_to"] as? Int ?? 0 temp_limit = map["temp_limit"] as? Int ?? 0 wind_rating_limits = map["wind_rating_limits"] as? [Float] ?? [] if let tmpcolors = map["colors"] as? Dictionary<String, [[Float]]> { colors = tmpcolors } for (k,v) in colors { for c in v { if let color = Color.init(a: c[0], r: c[1], g: c[2], b: c[3]) { switch k { case "wind": colors_wind.append(color) break case "temp": colors_temp.append(color) break case "cloud": colors_cloud.append(color) break case "precip": colors_precip.append(color) break case "precip1": colors_precip1.append(color) break case "press": colors_press.append(color) break case "rh": colors_rh.append(color) break case "htsgw": colors_htsgw.append(color) break case "perpw": colors_perpw.append(color) break default: break } } } } } public var description : String { var aux : String = "\(type(of:self)): " aux += "#\(id_user), " if let username = username { aux += "username: \(username), " } aux += "country # \(id_country), " if let wind_units = wind_units { aux += "wind_units \(wind_units), " } if let temp_units = temp_units { aux += "temp_units \(temp_units), " } if let wave_units = wave_units { aux += "wave_units \(wave_units), " } aux += "pro \(pro), " aux += "no_ads \(no_ads), " aux += "view_hours_from \(view_hours_from), " aux += "view_hours_to \(view_hours_to), " aux += "temp_limit \(temp_limit), " aux += "wind_rating_limits \(wind_rating_limits.printDescription())\n" aux += "colors_wind: " for c in colors_wind { aux += c.description + "; " } aux += "\n" aux += "colors_temp: " for c in colors_temp { aux += c.description + "; " } aux += "\n" aux += "colors_cloud: " for c in colors_cloud { aux += c.description + "; " } aux += "\n" aux += "colors_precip: " for c in colors_precip { aux += c.description + "; " } aux += "\n" aux += "colors_precip1: " for c in colors_precip1 { aux += c.description + "; " } aux += "\n" aux += "colors_press: " for c in colors_press { aux += c.description + "; " } aux += "\n" aux += "colors_rh: " for c in colors_rh { aux += c.description + "; " } aux += "\n" aux += "colors_htsgw: " for c in colors_htsgw{ aux += c.description + "; " } aux += "\n" aux += "colors_perpw: [" for c in colors_perpw{ aux += c.description + "; " } aux += "]\n" return aux } } extension User { public func name() -> String { if isAnonymous() { return "Anonymous" } return username ?? "" } public func isAnonymous() -> Bool { if let username = username, username != "" { return false } return true } public func getUsername() -> String? { return username } }
mit
80d64ad6debc95fe3ceb32084d0bd964
28.793893
79
0.414809
3.569273
false
false
false
false
jianghongbing/APIReferenceDemo
UIKit/UIBezierPath/UIBezierPath/DrawOtherViewController.swift
1
1111
// // DrawOtherViewController.swift // UIBezierPath // // Created by pantosoft on 2018/3/2. // Copyright © 2018年 jianghongbing. All rights reserved. // import UIKit class DrawOtherViewController: UIViewController { override func loadView() { view = DrawOtherView() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white //apply(_ transform: CGAffineTransform):将某个transform应用到当前Path } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let point = touch.location(in: view) let touchableView = view as! DrawOtherView let path = touchableView.path if path.contains(point) { //判断当前路径是否包含某个点 print("touched touch enable area") //isEmpty:判断path是否为空,bounds:path的bounds,currentPoint:paht的当前点 print("\(path.isEmpty),\(path.bounds), \(path.currentPoint) ") } } } }
mit
d5cc277950a0c10431cca90611bbc3c8
28
79
0.610153
4.519481
false
false
false
false
Nandiin/Savory
SavoryTests/SimpleStateProviderSpec.swift
1
1787
// // SimpleStateProviderSpec.swift // Savory // // Created by Nandiin Borjigin on 20/05/2017. // Copyright © 2017 Nandiin Borjigin. All rights reserved. // import Quick import Nimble import Savory class SimpleStateProviderSpec: QuickSpec { override func spec() { describe("count of provider") { context("initialized with empty array") { it("equals 0") { let provider = SimpleStateProvider([]) as SavoryStateProvider expect(provider.count) == 0 } } context("initialized with non-empty array") { it("equals the count of the array") { let provider = SimpleStateProvider([.expanded, .collapsed]) as SavoryStateProvider expect(provider.count) == 2 } } } describe("subscript") { var provider: SavoryStateProvider! beforeEach { provider = SimpleStateProvider([.expanded, .collapsed, .collapsed]) } describe("getter") { it("correctly returns the array elements") { expect(provider[0]) == SavoryPanelState.expanded expect(provider[1]) == SavoryPanelState.collapsed expect(provider[2]) == SavoryPanelState.collapsed } } it("is writable") { provider[0] = .collapsed expect(provider[0]) == SavoryPanelState.collapsed provider[1] = .expanded expect(provider[1]) == SavoryPanelState.expanded provider[2] = .expanded expect(provider[2]) == SavoryPanelState.expanded } } } }
mit
31a01fddae585ef2ec12f26b46425574
34.019608
102
0.528555
4.947368
false
false
false
false
apple/swift-system
Sources/System/PlatformString.swift
1
6646
/* This source file is part of the Swift System open source project Copyright (c) 2020 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension String { /// Creates a string by interpreting the null-terminated platform string as /// UTF-8 on Unix and UTF-16 on Windows. /// /// - Parameter platformString: The null-terminated platform string to be /// interpreted as `CInterop.PlatformUnicodeEncoding`. /// /// If the content of the platform string isn't well-formed Unicode, /// this initializer replaces invalid bytes with U+FFFD. /// This means that, depending on the semantics of the specific platform, /// conversion to a string and back might result in a value that's different /// from the original platform string. public init(platformString: UnsafePointer<CInterop.PlatformChar>) { self.init(_errorCorrectingPlatformString: platformString) } /// Creates a string by interpreting the null-terminated platform string as /// UTF-8 on Unix and UTF-16 on Windows. /// /// - Parameter platformString: The null-terminated platform string to be /// interpreted as `CInterop.PlatformUnicodeEncoding`. /// /// - Note It is a precondition that `platformString` must be null-terminated. /// The absence of a null byte will trigger a runtime error. /// /// If the content of the platform string isn't well-formed Unicode, /// this initializer replaces invalid bytes with U+FFFD. /// This means that, depending on the semantics of the specific platform, /// conversion to a string and back might result in a value that's different /// from the original platform string. @inlinable @_alwaysEmitIntoClient public init(platformString: [CInterop.PlatformChar]) { guard let _ = platformString.firstIndex(of: 0) else { fatalError( "input of String.init(platformString:) must be null-terminated" ) } self = platformString.withUnsafeBufferPointer { String(platformString: $0.baseAddress!) } } @inlinable @_alwaysEmitIntoClient @available(*, deprecated, message: "Use String.init(_ scalar: Unicode.Scalar)") public init(platformString: inout CInterop.PlatformChar) { guard platformString == 0 else { fatalError( "input of String.init(platformString:) must be null-terminated" ) } self = "" } @inlinable @_alwaysEmitIntoClient @available(*, deprecated, message: "Use a copy of the String argument") public init(platformString: String) { if let nullLoc = platformString.firstIndex(of: "\0") { self = String(platformString[..<nullLoc]) } else { self = platformString } } /// Creates a string by interpreting the null-terminated platform string as /// UTF-8 on Unix and UTF-16 on Windows. /// /// - Parameter platformString: The null-terminated platform string to be /// interpreted as `CInterop.PlatformUnicodeEncoding`. /// /// If the contents of the platform string isn't well-formed Unicode, /// this initializer returns `nil`. public init?( validatingPlatformString platformString: UnsafePointer<CInterop.PlatformChar> ) { self.init(_platformString: platformString) } /// Creates a string by interpreting the null-terminated platform string as /// UTF-8 on Unix and UTF-16 on Windows. /// /// - Parameter platformString: The null-terminated platform string to be /// interpreted as `CInterop.PlatformUnicodeEncoding`. /// /// - Note It is a precondition that `platformString` must be null-terminated. /// The absence of a null byte will trigger a runtime error. /// /// If the contents of the platform string isn't well-formed Unicode, /// this initializer returns `nil`. @inlinable @_alwaysEmitIntoClient public init?( validatingPlatformString platformString: [CInterop.PlatformChar] ) { guard let _ = platformString.firstIndex(of: 0) else { fatalError( "input of String.init(validatingPlatformString:) must be null-terminated" ) } guard let string = platformString.withUnsafeBufferPointer({ String(validatingPlatformString: $0.baseAddress!) }) else { return nil } self = string } @inlinable @_alwaysEmitIntoClient @available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)") public init?( validatingPlatformString platformString: inout CInterop.PlatformChar ) { guard platformString == 0 else { fatalError( "input of String.init(validatingPlatformString:) must be null-terminated" ) } self = "" } @inlinable @_alwaysEmitIntoClient @available(*, deprecated, message: "Use a copy of the String argument") public init?( validatingPlatformString platformString: String ) { if let nullLoc = platformString.firstIndex(of: "\0") { self = String(platformString[..<nullLoc]) } else { self = platformString } } /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated platform string. /// /// - Parameter body: A closure with a pointer parameter /// that points to a null-terminated platform string. /// If `body` has a return value, /// that value is also used as the return value for this method. /// - Returns: The return value, if any, of the `body` closure parameter. /// /// The pointer passed as an argument to `body` is valid /// only during the execution of this method. /// Don't try to store the pointer for later use. public func withPlatformString<Result>( _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result ) rethrows -> Result { try _withPlatformString(body) } } extension CInterop.PlatformChar { internal var _platformCodeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit { #if os(Windows) return self #else return CInterop.PlatformUnicodeEncoding.CodeUnit(bitPattern: self) #endif } } extension CInterop.PlatformUnicodeEncoding.CodeUnit { internal var _platformChar: CInterop.PlatformChar { #if os(Windows) return self #else return CInterop.PlatformChar(bitPattern: self) #endif } } internal protocol _PlatformStringable { func _withPlatformString<Result>( _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result ) rethrows -> Result init?(_platformString: UnsafePointer<CInterop.PlatformChar>) } extension String: _PlatformStringable {}
apache-2.0
a37fff39026b6391977f1a30b1046db5
33.435233
81
0.702829
4.375247
false
false
false
false
yosan/SwifTumblr
Pod/Classes/Blog.swift
1
1119
// // Blog.swift // SingItLater // // Created by Takahashi Yosuke on 2015/08/12. // Copyright (c) 2015年 Yousan. All rights reserved. // import Foundation import AEXML public struct Blog { public let name: String? public let timezone: String? public let title: String? public let description: String? public let posts: Posts? public init(xmlDoc: AEXMLDocument) { let blogElem = xmlDoc.root["tumblelog"] self.name = blogElem.attributes["name"] self.timezone = blogElem.attributes["timezone"] self.title = blogElem.attributes["title"] self.description = blogElem.string self.posts = Posts(postsXml: xmlDoc.root["posts"]) } } extension Blog: CustomDebugStringConvertible { public var debugDescription: String { let properties = ["name:\(String(describing: name))", "timezone:\(String(describing: timezone))", "title:\(String(describing: title))", "description:\(String(describing: description))", "posts:\(String(describing: posts))"] return properties.joined(separator: "\n") } }
mit
9af710e95b0e99e3015295075cf1d9c2
28.394737
231
0.653536
4.199248
false
false
false
false
mzaks/EntitasKit
Tests/GroupTests.swift
1
12647
// // GroupTests.swift // Entitas-Swift // // Created by Maxim Zaks on 17.06.17. // Copyright © 2017 Maxim Zaks. All rights reserved. // import Foundation import XCTest @testable import EntitasKit class GroupTests: XCTestCase { class Observer: GroupObserver { var addedData: [(entity: Entity, oldComponent: Component?, newComponent: Component?)] = [] func added(entity: Entity, oldComponent: Component?, newComponent: Component?, in group: Group) { addedData.append((entity: entity, oldComponent: oldComponent, newComponent:newComponent)) } var updatedData: [(entity: Entity, oldComponent: Component?, newComponent: Component?)] = [] func updated(entity: Entity, oldComponent: Component?, newComponent: Component?, in group: Group) { updatedData.append((entity: entity, oldComponent: oldComponent, newComponent:newComponent)) } var removedData: [(entity: Entity, oldComponent: Component?, newComponent: Component?)] = [] func removed(entity: Entity, oldComponent: Component?, newComponent: Component?, in group: Group) { removedData.append((entity: entity, oldComponent: oldComponent, newComponent:newComponent)) } } func testObservAllOfGroup() { let ctx = Context() let g = ctx.group(Matcher(all:[Position.cid, Size.cid])) let o = Observer() g.observer(add:o) let e = ctx.createEntity().set(Position(x: 1, y:2)).set(Size(value: 123)) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 0) XCTAssert(o.addedData[0].entity === e) XCTAssertNil(o.addedData[0].oldComponent) XCTAssertEqual((o.addedData[0].newComponent as? Size)?.value, 123) e.set(Position(x:3, y:1)) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 1) XCTAssertEqual(o.removedData.count, 0) XCTAssert(o.addedData[0].entity === e) XCTAssertEqual((o.updatedData[0].oldComponent as? Position)?.x, 1) XCTAssertEqual((o.updatedData[0].oldComponent as? Position)?.y, 2) XCTAssertEqual((o.updatedData[0].newComponent as? Position)?.x, 3) XCTAssertEqual((o.updatedData[0].newComponent as? Position)?.y, 1) e.remove(Size.cid) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 1) XCTAssertEqual(o.removedData.count, 1) XCTAssert(o.removedData[0].entity === e) XCTAssertNil(o.removedData[0].newComponent) XCTAssertEqual((o.removedData[0].oldComponent as? Size)?.value, 123) e.destroy() // no effect because is already out of the group XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 1) XCTAssertEqual(o.removedData.count, 1) } func testObservAnyOfGroup() { let ctx = Context() let g = ctx.group(Matcher(any:[Position.cid, Size.cid])) let o = Observer() g.observer(add:o) let e = ctx.createEntity().set(Position(x: 1, y:2)) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 0) XCTAssert(o.addedData[0].entity === e) XCTAssertNil(o.addedData[0].oldComponent) XCTAssertEqual((o.addedData[0].newComponent as? Position)?.x, 1) XCTAssertEqual((o.addedData[0].newComponent as? Position)?.y, 2) e.set(Size(value:34)) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 1) XCTAssertEqual(o.removedData.count, 0) XCTAssert(o.updatedData[0].entity === e) XCTAssertNil(o.updatedData[0].oldComponent) XCTAssertEqual((o.updatedData[0].newComponent as? Size)?.value, 34) e.remove(Size.cid) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 2) XCTAssertEqual(o.removedData.count, 0) XCTAssert(o.updatedData[1].entity === e) XCTAssertNil(o.updatedData[1].newComponent) XCTAssertEqual((o.updatedData[1].oldComponent as? Size)?.value, 34) e.destroy() XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 2) XCTAssertEqual(o.removedData.count, 1) XCTAssert(o.removedData[0].entity === e) XCTAssertNil(o.removedData[0].newComponent) XCTAssertEqual((o.removedData[0].oldComponent as? Position)?.x, 1) XCTAssertEqual((o.removedData[0].oldComponent as? Position)?.y, 2) } func testObservAllOfNoneOfGroup(){ let ctx = Context() let g = ctx.group(Matcher(all:[Position.cid, Size.cid], none: [Name.cid])) let o = Observer() g.observer(add:o) let e = ctx.createEntity().set(Position(x: 1, y:2)) XCTAssertEqual(o.addedData.count, 0) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 0) e.set(Size(value: 12)) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 0) XCTAssert(o.addedData[0].entity === e) XCTAssertNil(o.addedData[0].oldComponent) XCTAssertEqual((o.addedData[0].newComponent as? Size)?.value, 12) e.set(Name(value: "Max")) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 1) XCTAssert(o.removedData[0].entity === e) XCTAssertNil(o.removedData[0].oldComponent) XCTAssertEqual((o.removedData[0].newComponent as? Name)?.value, "Max") e.remove(Name.cid) XCTAssertEqual(o.addedData.count, 2) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 1) XCTAssert(o.addedData[1].entity === e) XCTAssertNil(o.addedData[1].newComponent) XCTAssertEqual((o.addedData[1].oldComponent as? Name)?.value, "Max") } func testRemoveObserving() { let ctx = Context() let g = ctx.group(Matcher(any:[Position.cid, Size.cid])) let o = Observer() g.observer(add:o) let e = ctx.createEntity().set(Position(x: 1, y:2)) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 0) g.observer(remove:o) e.set(Size(value: 123)) XCTAssertEqual(o.addedData.count, 1) XCTAssertEqual(o.updatedData.count, 0) XCTAssertEqual(o.removedData.count, 0) } func testWeakObserverGetRemoved() { let ctx = Context() let g = ctx.group(Matcher(any:[Position.cid, Size.cid])) weak var o0 : Observer? do { let o = Observer() g.observer(add:o) o0 = o } let o1 = Observer() g.observer(add:o1) ctx.createEntity().set(Position(x: 1, y:2)) XCTAssertNil(o0) XCTAssertEqual(o1.addedData.count, 1) XCTAssertEqual(o1.updatedData.count, 0) XCTAssertEqual(o1.removedData.count, 0) } func testMultipleGroups() { let ctx = Context() let g1 = ctx.group(Matcher(any:[Position.cid, Size.cid])) let g2 = ctx.group(Matcher(all:[Position.cid, Size.cid])) let o1 = Observer() let o2 = Observer() g1.observer(add:o1) g2.observer(add:o2) let e = ctx.createEntity().set(Position(x: 1, y:2)) XCTAssertEqual(o1.addedData.count, 1) XCTAssertEqual(o1.updatedData.count, 0) XCTAssertEqual(o1.removedData.count, 0) XCTAssertEqual(o2.addedData.count, 0) XCTAssertEqual(o2.updatedData.count, 0) XCTAssertEqual(o2.removedData.count, 0) e.set(Size(value: 43)) XCTAssertEqual(o1.addedData.count, 1) XCTAssertEqual(o1.updatedData.count, 1) XCTAssertEqual(o1.removedData.count, 0) XCTAssertEqual(o2.addedData.count, 1) XCTAssertEqual(o2.updatedData.count, 0) XCTAssertEqual(o2.removedData.count, 0) } func testSoretedListFromGroup() { let ctx = Context() let g = ctx.group(Position.matcher) var list = g.sorted() XCTAssertEqual(list, []) let e = ctx.createEntity().set(Position(x: 1, y:2)) let e1 = ctx.createEntity().set(Position(x: 2, y:2)) list = g.sorted() XCTAssertEqual(list, [e, e1]) let list2 = g.sorted() XCTAssert(list == list2) } func testSoretedListForObjectFromGroup() { let ctx = Context() let g = ctx.group(Position.matcher) var list = g.sorted() XCTAssertEqual(list, []) let e = ctx.createEntity().set(Position(x: 1, y:2)) let e1 = ctx.createEntity().set(Position(x: 2, y:2)) list = g.sorted(forObject: ObjectIdentifier(self)) { e1, e2 in return (e1.get(Position.self)?.x ?? 0) > (e2.get(Position.self)?.x ?? 0) } XCTAssertEqual(list, [e1, e]) let list2 = g.sorted(forObject: ObjectIdentifier(self)) { e1, e2 in return (e1.get(Position.self)?.x ?? 0) > (e2.get(Position.self)?.x ?? 0) } XCTAssert(list == list2) } func testGroupIsEmpty() { let ctx = Context() let g = ctx.group(Position.matcher) XCTAssertEqual(g.isEmpty, true) _ = ctx.createEntity().set(Position(x: 1, y:2)) XCTAssertEqual(g.isEmpty, false) } func testWithEach() { let ctx = Context() let g = ctx.group(Matcher(any: [Position.cid, Name.cid, Size.cid, Person.cid])) let e = ctx.createEntity().set(Position(x: 1, y:2)) e += Name(value: "Max") e += Size(value: 3) e += Person() var found = false g.withEach { (e, c: Position) in found = true } XCTAssert(found) found = false g.withEach { (e, c1: Position, c2: Person) in found = true } XCTAssert(found) found = false g.withEach { (e, c1: Position, c2: Person, c3: Size) in found = true } XCTAssert(found) found = false g.withEach { (e, c1: Position, c2: Person, c3: Size, c4: Name) in found = true } XCTAssert(found) e -= Person.cid found = false g.withEach { (e, c1: Position, c2: Person, c3: Size, c4: Name) in found = true } XCTAssert(found == false) } func testLoopOverGroupWhenOutOfOrderChangeOccurs(){ let ctx = Context() let g = ctx.all([Position.cid, Name.cid]) let e1 = ctx.createEntity() e1 += Position(x: 1, y: 2) e1 += Name(value: "1") let e2 = ctx.createEntity() e2 += Position(x: 2, y: 2) e2 += Name(value: "2") let e3 = ctx.createEntity() e3 += Position(x: 3, y: 2) e3 += Name(value: "3") for e in g { e3 -= Name.cid if e == e3 { XCTAssertFalse(e.has(Name.cid)) } else { XCTAssert(e.has(Name.cid)) } } } func testLoopWithComponentOverGroupWhenOutOfOrderChangeOccurs(){ let ctx = Context() let g = ctx.all([Position.cid, Name.cid]) let e1 = ctx.createEntity() e1 += Position(x: 1, y: 2) e1 += Name(value: "1") let e2 = ctx.createEntity() e2 += Position(x: 2, y: 2) e2 += Name(value: "2") let e3 = ctx.createEntity() e3 += Position(x: 3, y: 2) e3 += Name(value: "3") var count = 0 g.withEach(sorted: true) { (e, c: Name) in e3 -= Name.cid XCTAssertEqual(e.has(Name.cid), true) count += 1 } XCTAssertEqual(2, count) } }
mit
c96a31f401c724239f5d9b9410c1f494
32.191601
107
0.563894
3.895872
false
false
false
false
xeo-it/poggy
Pods/OAuthSwift/OAuthSwift/NSError+OAuthSwift.swift
1
2290
// // NSError+OAuthSwift.swift // OAuthSwift // // Created by Goessler, Florian on 04/04/16. // Copyright © 2016 Dongri Jin. All rights reserved. // import Foundation public extension NSError { /// Checks the headers contained in the userInfo whether this error was caused by an /// expired/invalid access token. /// /// Criteria for invalid token error: WWW-Authenticate header contains a field "error" with /// value "invalid_token". /// /// Also implements a special handling for the Facebook API, which indicates invalid tokens in a /// different manner. See https://developers.facebook.com/docs/graph-api/using-graph-api#errors public var isExpiredTokenError: Bool { if self.domain == NSURLErrorDomain && self.code == 401 { if let reponseHeaders = self.userInfo["Response-Headers"] as? [String:String], authenticateHeader = reponseHeaders["WWW-Authenticate"] ?? reponseHeaders["Www-Authenticate"] { let headerDictionary = authenticateHeader.headerDictionary if let error = headerDictionary["error"] where error == "invalid_token" || error == "\"invalid_token\"" { return true } } } // Detect access token expiration errors from facebook // Docu: https://developers.facebook.com/docs/graph-api/using-graph-api#errors if self.domain == NSURLErrorDomain && self.code == 400 { if let urlString = self.userInfo[NSURLErrorFailingURLErrorKey] as? String where urlString.containsString("graph.facebook.com") { if let body = self.userInfo["Response-Body"] as? String, let bodyData = body.dataUsingEncoding(OAuthSwiftDataEncoding), let json = try? NSJSONSerialization.JSONObjectWithData(bodyData, options: NSJSONReadingOptions()), let jsonDic = json as? [String: AnyObject] { let errorCode = jsonDic["error"]?["code"] as? Int let errorSubCode = jsonDic["error"]?["error_subcode"] as? Int if (errorCode == 102 && errorSubCode == nil) || errorSubCode == 463 || errorSubCode == 467 { return true } } } } return false } }
apache-2.0
2617d6cc325625826a6f4fa9b84d9895
39.875
118
0.624727
4.624242
false
false
false
false
ifabijanovic/RxBattleNet
RxBattleNet/WoW/Model/Realm.swift
1
1302
// // Realm.swift // RxBattleNet // // Created by Ivan Fabijanović on 06/08/16. // Copyright © 2016 Ivan Fabijanovic. All rights reserved. // import SwiftyJSON public extension WoW { public struct Realm: Model { // MARK: - Properties public let name: String public let slug: String public let locale: String public let timezone: String public let status: Bool public let queue: Bool public let population: String public let type: String public let battlegroup: String public let connectedRealms: [String] // MARK: - Init internal init(json: JSON) { self.name = json["name"].stringValue self.slug = json["slug"].stringValue self.locale = json["locale"].stringValue self.timezone = json["timezone"].stringValue self.status = json["status"].boolValue self.queue = json["queue"].boolValue self.population = json["population"].stringValue self.type = json["type"].stringValue self.battlegroup = json["battlegroup"].stringValue self.connectedRealms = json["connected_realms"].map { $1.stringValue } } } }
mit
4753c8bb56d2bc77e9639a7974172f4c
27.888889
82
0.577692
4.710145
false
false
false
false
sharkspeed/dororis
languages/swift/guide/3-strings-and-characters.swift
1
9142
// 3. Strings and Characters /* a series of characters Swift strings are represented by the String type NOTE Swift’s String type is bridged with Foundation’s NSString class. */ // 1. String Literals // textual characters surrounded by a pair of double quotes (""). var emptyString = "" // empty string literal var anotherEmptyString = String() // initializer syntax // both empty and are equivalent to each other if emptyString.isEmpty { print("Nothing will be seen") } // 2. String Mutability var variableString = "Horse" variableString += " and carriage" print(variableString) let constantString = "Can't change" // constantString += 'Add words' // Error // 3. Strings Are Value Types // 值类型 非引用类型 // 4. Working with Characters for character in "Dog!🐶".characters { print(character) } let exclamationMark: Character = "!" // String values can be constructed by passing an array of Character values as an argument to its initializer let buildByChar:[Character] = ["C", "A", "T"] let buildString = String(buildByChar) print(buildString) // 5. Concatenating Strings and Characters // String + String // String += String // String.append(Character) // type check operator (is) var a = "!" // var a: Character= "!" a += a // binary operator '+=' cannot be applied to two 'Character' operands print(a) // var a:String = "@" // print(a is Character) // print(a is String) var welcome = "Hello" welcome.append(exclamationMark) print(welcome) // 6. String Interpolation let multiplier = 3 let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" // cannot contain an unescaped backslash (\), a carriage return, or a line feed // 7. Unicode // Swift’s String and Character types are fully Unicode-compliant 完全兼容 Unicode // 7.1 Unicode Scalars // Swift’s native String type is built from Unicode scalar values // A Unicode scalar is a unique 21-bit number for a character or modifier, such as U+0061 for LATIN SMALL LETTER A ("a") // 并非全部的 21-bit Unicode 都分配了字符有些被保留作为未来用途 // Scalars that have been assigned to a character typically also have a name, such as LATIN SMALL LETTER A and FRONT-FACING BABY CHICK in the examples above. // 7.2 Special Characters in String Literals // The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote) // An arbitrary Unicode scalar, written as \u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point let wiseWords = "\"Imagination is more important than knowledge\"" let dollarSign = "\u{24}" // $, Unicode scalar U+0024 let blackHeart = "\u{2665}" // ♥, Unicode scalar U+2665 let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496 // 7.3 Extended Grapheme Clusters // Character 类型一般表示一个字型 let eAcute: Character = "\u{E9}" // é LATIN SMALL LETTER E WITH ACUTE, or U+00E9 let combinedEAcute: Character = "\u{65}\u{301}" // e followed by ́ (LATIN SMALL LETTER E, or U+0065), followed by the COMBINING ACUTE ACCENT scalar (U+0301) rendered by a Unicode-aware text-rendering system let precomposed: Character = "\u{D55C}" // 한 let decomposed: Character = "\u{1112}\u{1161}\u{11AB}" // ᄒ, ᅡ, ᆫ // 7.4 Counting Characters let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪" print("unusualMenagerie has \(unusualMenagerie.characters.count) characters") // print("unusualMenagerie has \(unusualMenagerie.count) characters") // String 类型没有直接的 count 方法 因为一个 Unicode 可能由多个 character 组成,只有当遍历字符串才知道长度 // The count of the characters returned by the characters property is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string. // 8. Accessing and Modifying a String // 通过 methods properties 或 subscript 语法 读取 修改 字符串 // 8.1 String Indices // different characters can require different amounts of memory to store, you must iterate over each Unicode scalar from the start or end of that String. For this reason, Swift strings cannot be indexed by integer values. print(unusualMenagerie[unusualMenagerie.startIndex]) // The endIndex property is the position after the last character in a String. As a result, the endIndex property isn’t a valid argument to a string’s subscript. // endIndex 属性是 String 最后一个字符后边的位置, 因此溢出了。。 // unusualMenagerie[unusualMenagerie.index(before: unusualMenagerie.endIndex)] // index(after: unusualMenagerie.startIndex) // index(unusualMenagerie.startIndex, offsetBy: 8) // 获取超出字符串长度范围位置的字符会导致 runtime error // indices for index in unusualMenagerie.characters.indices { print("\(unusualMenagerie[index])-", terminator: "") } print() // 8.2 Inserting and Removing // insert(_:at:) var myWelcome = "Come to USA" // myWelcome.insert("<-OK->", at: myWelcome[myWelcome.index(myWelcome.endIndex, offsetBy: 4)]) // myWelcome.insert("<", at: myWelcome[myWelcome.index(myWelcome.endIndex, offsetBy: 4)]) welcome.insert("!", at: welcome.endIndex) print(welcome) welcome.insert(contentsOf: " USA".characters, at: welcome.index(after: welcome.startIndex)) //decrement before startIndex print(welcome) // remove(at:) remove a single character // removeSubrange(_:) remove a specified range welcome.remove(at: welcome.index(before: welcome.endIndex)) print(welcome) welcome.removeSubrange(welcome.index(welcome.endIndex, offsetBy: -5)..<welcome.endIndex) print(welcome) // insert remove 都可以用在 any type that conforms to the RangeReplaceableCollection protocol. 例如 String Array Dictionary Set // 8.3 Comparing Strings // 8.3.1 String and Character Equality // "equal to" operator (==) and the "not equal to" operator (!=), let quotation = "We're a lot alike, you and I." let sameQuotation = "We're a lot alike, you and I." if quotation == sameQuotation { print("These two strings are considered equal") } // Two String values (or two Character values) are considered equal if their extended grapheme clusters are canonically equivalent // LATIN SMALL LETTER E WITH ACUTE (U+00E9) is canonically equivalent to LATIN SMALL LETTER E (U+0065) followed by COMBINING ACUTE ACCENT (U+0301) // "Voulez-vous un café?" using LATIN SMALL LETTER E WITH ACUTE let eAcuteQuestion = "Voulez-vous un caf\u{E9}?" // "Voulez-vous un café?" using LATIN SMALL LETTER E and COMBINING ACUTE ACCENT let combinedEAcuteQuestion = "Voulez-vous un caf\u{65}\u{301}?" if eAcuteQuestion == combinedEAcuteQuestion { print("These two strings are considered equal") } // Conversely, LATIN CAPITAL LETTER A (U+0041, or "A"), as used in English, is not equivalent to CYRILLIC CAPITAL LETTER A (U+0410, or "А"), as used in Russian let latinCapitalLetterA: Character = "\u{41}" let cyrillicCapitalLetterA: Character = "\u{0410}" if latinCapitalLetterA != cyrillicCapitalLetterA { print("These two characters are not equivalent.") } // 8.3.2 // hasPrefix(_:) and hasSuffix(_:) methods, both of which take a single argument of type String and return a Boolean value // 检查前缀和后缀 let rubyAndPython = [ "Python is bad fish", "Python is not so cool", "Ruby is too selfish", "Ruby sounds like hard to learn" ] var pythonCount = 0 for word in rubyAndPython { if word.hasPrefix("Python") { pythonCount += 1 } } print(pythonCount) var endWithFish = 0 for word in rubyAndPython { if word.hasSuffix("fish") { endWithFish += 1 } } print(endWithFish) // 8.4 Unicode Representations of Strings // You can iterate over the string with a for-in statement, to access its individual Character values as Unicode extended grapheme clusters // Alternatively, access a String value in one of three other Unicode-compliant representations: // A collection of UTF-8 code units (accessed with the string’s utf8 property) // A collection of UTF-16 code units (accessed with the string’s utf16 property) // A collection of 21-bit Unicode scalar values, equivalent to the string’s UTF-32 encoding form (accessed with the string’s unicodeScalars property) let dogString = "Dog‼🐶" for codeUnit in dogString.utf8 { print("\(codeUnit) ", terminator: "") } print("") // dogString.utf16 // dogString.unicodeScalars for scalar in dogString.unicodeScalars { print("\(scalar.value) ", terminator: "") } print("") // Prints "68 111 103 8252 128054 " for scalar in dogString.unicodeScalars { print("\(scalar) ") } /* Refs https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-ID88 */
bsd-2-clause
73376d0b921b60ebaf8a286b465fc95f
32.811538
350
0.730375
3.708861
false
false
false
false
zenghaojim33/BeautifulShop
BeautifulShop/BeautifulShop/Charts/Utils/ChartHighlight.swift
1
2532
// // ChartHighlight.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartHighlight: NSObject { /// the x-index of the highlighted value private var _xIndex = Int(0) /// the index of the dataset the highlighted value is in private var _dataSetIndex = Int(0) /// index which value of a stacked bar entry is highlighted /// :default: -1 private var _stackIndex = Int(-1) public override init() { super.init(); } public init(xIndex x: Int, dataSetIndex: Int) { super.init(); _xIndex = x; _dataSetIndex = dataSetIndex; } public init(xIndex x: Int, dataSetIndex: Int, stackIndex: Int) { super.init(); _xIndex = x; _dataSetIndex = dataSetIndex; _stackIndex = stackIndex; } public var dataSetIndex: Int { return _dataSetIndex; } public var xIndex: Int { return _xIndex; } public var stackIndex: Int { return _stackIndex; } // MARK: NSObject public override var description: String { return "Highlight, xIndex: \(_xIndex), dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex)"; } public override func isEqual(object: AnyObject?) -> Bool { if (object == nil) { return false; } if (!object!.isKindOfClass(self.dynamicType)) { return false; } if (object!.xIndex != _xIndex) { return false; } if (object!.dataSetIndex != _dataSetIndex) { return false; } if (object!.stackIndex != _stackIndex) { return false; } return true; } } func ==(lhs: ChartHighlight, rhs: ChartHighlight) -> Bool { if (lhs === rhs) { return true; } if (!lhs.isKindOfClass(rhs.dynamicType)) { return false; } if (lhs._xIndex != rhs._xIndex) { return false; } if (lhs._dataSetIndex != rhs._dataSetIndex) { return false; } if (lhs._stackIndex != rhs._stackIndex) { return false; } return true; }
apache-2.0
5da65dfb6ceaf5e8b9cc8b01a158879c
19.762295
131
0.53831
4.529517
false
false
false
false
enisinanaj/1-and-1.workouts
Pods/SQLite.swift/Sources/SQLite/Typed/Schema.swift
2
22733
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension SchemaType { // MARK: - DROP TABLE / VIEW / VIRTUAL TABLE public func drop(ifExists: Bool = false) -> String { return drop("TABLE", tableName(), ifExists) } } extension Table { // MARK: - CREATE TABLE public func create(temporary: Bool = false, ifNotExists: Bool = false, withoutRowid: Bool = false, block: (TableBuilder) -> Void) -> String { let builder = TableBuilder() block(builder) let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), "".wrap(builder.definitions) as Expression<Void>, withoutRowid ? Expression<Void>(literal: "WITHOUT ROWID") : nil ] return " ".join(clauses.flatMap { $0 }).asSQL() } public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - ALTER TABLE … ADD COLUMN public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V) -> String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V) -> String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil) -> String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil) -> String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } fileprivate func addColumn(_ expression: Expressible) -> String { return " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "ADD COLUMN"), expression ]).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: Table) -> String { return rename(to: to) } // MARK: - CREATE INDEX public func createIndex(_ columns: Expressible...) -> String { return createIndex(columns) } public func createIndex(_ columns: [Expressible], unique: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create("INDEX", indexName(columns), unique ? .unique : nil, ifNotExists), Expression<Void>(literal: "ON"), tableName(qualified: false), "".wrap(columns) as Expression<Void> ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - DROP INDEX public func dropIndex(_ columns: Expressible...) -> String { return dropIndex(columns) } public func dropIndex(_ columns: [Expressible], ifExists: Bool = false) -> String { return drop("INDEX", indexName(columns), ifExists) } fileprivate func indexName(_ columns: [Expressible]) -> Expressible { let string = (["index", clauses.from.name, "on"] + columns.map { $0.expression.template }).joined(separator: " ").lowercased() let index = string.characters.reduce("") { underscored, character in guard character != "\"" else { return underscored } guard "a"..."z" ~= character || "0"..."9" ~= character else { return underscored + "_" } return underscored + String(character) } return database(namespace: index) } } extension View { // MARK: - CREATE VIEW public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(View.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - DROP VIEW public func drop(ifExists: Bool = false) -> String { return drop("VIEW", tableName(), ifExists) } } extension VirtualTable { // MARK: - CREATE VIRTUAL TABLE public func create(_ using: Module, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(VirtualTable.identifier, tableName(), nil, ifNotExists), Expression<Void>(literal: "USING"), using ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: VirtualTable) -> String { return rename(to: to) } } public final class TableBuilder { fileprivate var definitions = [Expressible]() public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool>? = nil) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool?>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } fileprivate func column(_ name: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) { definitions.append(definition(name, datatype, primaryKey, null, unique, check, defaultValue, references, collate)) } // MARK: - public func primaryKey<T : Value>(_ column: Expression<T>) { primaryKey([column]) } public func primaryKey<T : Value, U : Value>(_ compositeA: Expression<T>, _ b: Expression<U>) { primaryKey([compositeA, b]) } public func primaryKey<T : Value, U : Value, V : Value>(_ compositeA: Expression<T>, _ b: Expression<U>, _ c: Expression<V>) { primaryKey([compositeA, b, c]) } fileprivate func primaryKey(_ composite: [Expressible]) { definitions.append("PRIMARY KEY".prefix(composite)) } public func unique(_ columns: Expressible...) { unique(columns) } public func unique(_ columns: [Expressible]) { definitions.append("UNIQUE".prefix(columns)) } public func check(_ condition: Expression<Bool>) { check(Expression<Bool?>(condition)) } public func check(_ condition: Expression<Bool?>) { definitions.append("CHECK".prefix(condition)) } public enum Dependency: String { case noAction = "NO ACTION" case restrict = "RESTRICT" case setNull = "SET NULL" case setDefault = "SET DEFAULT" case cascade = "CASCADE" } public func foreignKey<T : Value>(_ column: Expression<T>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T : Value>(_ column: Expression<T?>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T : Value, U : Value>(_ composite: (Expression<T>, Expression<U>), references table: QueryType, _ other: (Expression<T>, Expression<U>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1]) let references = (table, ", ".join([other.0, other.1])) foreignKey(composite, references, update, delete) } public func foreignKey<T : Value, U : Value, V : Value>(_ composite: (Expression<T>, Expression<U>, Expression<V>), references table: QueryType, _ other: (Expression<T>, Expression<U>, Expression<V>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1, composite.2]) let references = (table, ", ".join([other.0, other.1, other.2])) foreignKey(composite, references, update, delete) } fileprivate func foreignKey(_ column: Expressible, _ references: (QueryType, Expressible), _ update: Dependency?, _ delete: Dependency?) { let clauses: [Expressible?] = [ "FOREIGN KEY".prefix(column), reference(references), update.map { Expression<Void>(literal: "ON UPDATE \($0.rawValue)") }, delete.map { Expression<Void>(literal: "ON DELETE \($0.rawValue)") } ] definitions.append(" ".join(clauses.flatMap { $0 })) } } public enum PrimaryKey { case `default` case autoincrement } public struct Module { fileprivate let name: String fileprivate let arguments: [Expressible] public init(_ name: String, _ arguments: [Expressible]) { self.init(name: name.quote(), arguments: arguments) } init(name: String, arguments: [Expressible]) { self.name = name self.arguments = arguments } } extension Module : Expressible { public var expression: Expression<Void> { return name.wrap(arguments) } } // MARK: - Private private extension QueryType { func create(_ identifier: String, _ name: Expressible, _ modifier: Modifier?, _ ifNotExists: Bool) -> Expressible { let clauses: [Expressible?] = [ Expression<Void>(literal: "CREATE"), modifier.map { Expression<Void>(literal: $0.rawValue) }, Expression<Void>(literal: identifier), ifNotExists ? Expression<Void>(literal: "IF NOT EXISTS") : nil, name ] return " ".join(clauses.flatMap { $0 }) } func rename(to: Self) -> String { return " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "RENAME TO"), Expression<Void>(to.clauses.from.name) ]).asSQL() } func drop(_ identifier: String, _ name: Expressible, _ ifExists: Bool) -> String { let clauses: [Expressible?] = [ Expression<Void>(literal: "DROP \(identifier)"), ifExists ? Expression<Void>(literal: "IF EXISTS") : nil, name ] return " ".join(clauses.flatMap { $0 }).asSQL() } } private func definition(_ column: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) -> Expressible { let clauses: [Expressible?] = [ column, Expression<Void>(literal: datatype), primaryKey.map { Expression<Void>(literal: $0 == .autoincrement ? "PRIMARY KEY AUTOINCREMENT" : "PRIMARY KEY") }, null ? nil : Expression<Void>(literal: "NOT NULL"), unique ? Expression<Void>(literal: "UNIQUE") : nil, check.map { " ".join([Expression<Void>(literal: "CHECK"), $0]) }, defaultValue.map { "DEFAULT".prefix($0) }, references.map(reference), collate.map { " ".join([Expression<Void>(literal: "COLLATE"), $0]) } ] return " ".join(clauses.flatMap { $0 }) } private func reference(_ primary: (QueryType, Expressible)) -> Expressible { return " ".join([ Expression<Void>(literal: "REFERENCES"), primary.0.tableName(qualified: false), "".wrap(primary.1) as Expression<Void> ]) } private enum Modifier : String { case unique = "UNIQUE" case temporary = "TEMPORARY" }
mit
dfa53164e8479d7c69838108930bc2c3
42.703846
260
0.643624
4.183726
false
false
false
false
keyfun/synology_ds_get
DSGetLite/DSGetLite/TaskListViewController.swift
1
2724
// // TaskListViewController.swift // DSGetLite // // Created by Hui Key on 20/10/2016. // Copyright © 2016 Key Hui. All rights reserved. // import UIKit class TaskListViewController: UITableViewController { private var tasks = Array<Task>() private var timer: Timer? = nil private var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() textField = UITextField.init(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 40)) textField.text = "" textField.placeholder = "Input url" textField.textAlignment = .center self.navigationItem.titleView = textField let btnAdd = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(self.onTapAdd)) self.navigationItem.rightBarButtonItem = btnAdd // call update list refreshList() } @objc private func onTapAdd() { print("onTapAdd: \(String(describing: textField.text))") if let uri = textField.text, !uri.isEmpty { APIManager.sharedInstance.createTask(uri: uri) UIPasteboard.general.string = "" } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // auto refresh, start timer timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.refreshList), userInfo: nil, repeats: true) // auto paste clipboard to input field textField.text = UIPasteboard.general.string } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) timer?.invalidate() timer = nil } @objc func refreshList() { APIManager.sharedInstance.getDownloadList { (isSuccess: Bool, result: TaskListResponse?) in print("isSuccess = \(isSuccess)") if result != nil { print("response = \(result!.toString())") self.tasks = result!.tasks! DispatchQueue.main.async { self.tableView.reloadData() } } } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tasks.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) let task: Task = self.tasks[indexPath.row] cell.textLabel?.text = task.title cell.detailTextLabel?.text = task.status return cell } }
mit
69821a8107039537f8237907f0130ea2
29.943182
137
0.622842
4.879928
false
false
false
false
akupara/Vishnu
Vishnu/Vishnu/HMAC.swift
1
3067
// // HMAC.swift // Vishnu // // Created by Daniel Lu on 2/19/16. // Copyright © 2016 Daniel Lu. All rights reserved. // import Foundation import CommonCrypto public struct AVishnuHMAC { // MARK: - Types public enum Algorithm { case SHA1 case MD5 case SHA256 case SHA384 case SHA512 case SHA224 public var algorithm: CCHmacAlgorithm { switch self { case .MD5: return CCHmacAlgorithm(kCCHmacAlgMD5) case .SHA1: return CCHmacAlgorithm(kCCHmacAlgSHA1) case .SHA224: return CCHmacAlgorithm(kCCHmacAlgSHA224) case .SHA256: return CCHmacAlgorithm(kCCHmacAlgSHA256) case .SHA384: return CCHmacAlgorithm(kCCHmacAlgSHA384) case .SHA512: return CCHmacAlgorithm(kCCHmacAlgSHA512) } } public var digestLength: Int { switch self { case .MD5: return Int(CC_MD5_DIGEST_LENGTH) case .SHA1: return Int(CC_SHA1_DIGEST_LENGTH) case .SHA224: return Int(CC_SHA224_DIGEST_LENGTH) case .SHA256: return Int(CC_SHA256_DIGEST_LENGTH) case .SHA384: return Int(CC_SHA384_DIGEST_LENGTH) case .SHA512: return Int(CC_SHA512_DIGEST_LENGTH) } } } // MARK: - Signing public static func sign(data data: NSData, algorithm: Algorithm, key: NSData) -> NSData { let signature = UnsafeMutablePointer<CUnsignedChar>.alloc(algorithm.digestLength) CCHmac(algorithm.algorithm, key.bytes, key.length, data.bytes, data.length, signature) return NSData(bytes: signature, length: algorithm.digestLength) } public static func sign(message message: String, algorithm: Algorithm, key: String) -> String? { guard let signedData:NSData? = sign(message: message, algorithm: algorithm, key: key), let data = signedData else { return nil } var hash = "" data.enumerateByteRangesUsingBlock { bytes, range, _ in let pointer = UnsafeMutablePointer<CUnsignedChar>(bytes) for i in range.location..<(range.location + range.length) { hash += NSString(format: "%02x", pointer[i]) as String } } return hash } public static func sign(message message: String, algorithm: Algorithm, key: String) -> NSData? { guard let messageData = message.dataUsingEncoding(NSUTF8StringEncoding), keyData = key.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } let data = sign(data: messageData, algorithm: algorithm, key: keyData) return data } public static func base64Sign(message message: String, algorithm: Algorithm, key:String) -> String? { guard let signedData:NSData? = sign(message: message, algorithm: algorithm, key: key), let data = signedData else { return nil } return data.base64EncodedStringWithOptions([]) } }
mit
e50d066142c6d724d27d4046d284a0e9
35.082353
105
0.618069
4.542222
false
false
false
false
vgorloff/AUHost
Sources/Common/TitlebarViewController.swift
1
3293
// // TitlebarViewController.swift // Attenuator // // Created by Vlad Gorlov on 13.10.18. // Copyright © 2018 WaveLabs. All rights reserved. // import Foundation import AppKit import mcxUIReusable import mcxUI class TitlebarViewController: ViewController { enum Event: CaseIterable { case library, play, effect, reloadPlugIns } var eventHandler: ((Event) -> Void)? private lazy var actionsBar = ActionsBar().autolayoutView() private lazy var buttonLibrary = Button(image: ControlIcon.library.image).autolayoutView() private lazy var buttonPlay = Button(image: ControlIcon.play.image, alternateImage: ControlIcon.pause.image).autolayoutView() private lazy var buttonLoadAU = Button(image: ControlIcon.effect.image).autolayoutView() private lazy var buttonReload = Button(image: ControlIcon.reload.image).autolayoutView() private let isHostTitleBar: Bool init(isHostTitleBar: Bool) { self.isHostTitleBar = isHostTitleBar super.init() } public required init?(coder: NSCoder) { fatalError() } override func setupUI() { view.addSubviews(actionsBar) let spacing: CGFloat = 7 actionsBar.itemsSpacing = spacing actionsBar.edgeInsets = NSEdgeInsets(horizontal: spacing, vertical: 3) actionsBar.setLeftItems(buttonPlay, buttonLoadAU) isHostTitleBar ? actionsBar.setRightItems(buttonReload, buttonLibrary) : actionsBar.setRightItems(buttonLibrary) buttonPlay.setButtonType(.toggle) buttonReload.toolTip = "Reload PlugIns" buttonLibrary.toolTip = "Toggle Media Library" buttonPlay.toolTip = "Toggle Playback" buttonLoadAU.toolTip = isHostTitleBar ? "Show Effect Window" : "Load / Unload Effect" } override func setupDefaults() { buttonPlay.isEnabled = false } override func setupLayout() { anchor.pin.toBounds(actionsBar).activate() } override func setupHandlers() { buttonLibrary.setHandler { [weak self] in self?.eventHandler?(.library) } buttonPlay.setHandler { [weak self] in self?.eventHandler?(.play) } buttonLoadAU.setHandler { [weak self] in self?.eventHandler?(.effect) } buttonReload.setHandler { [weak self] in self?.eventHandler?(.reloadPlugIns) } } func handleEvent(_ event: MainViewUIModel.Event, _ state: MainViewUIModel.State) { switch event { case .playbackEngineStageChanged(let playbackState): buttonLoadAU.isEnabled = state.contains(.canOpenEffect) switch playbackState { case .playing: buttonPlay.isEnabled = true buttonPlay.state = .on case .stopped: buttonPlay.isEnabled = true buttonPlay.state = .off case .paused: buttonPlay.isEnabled = true buttonPlay.state = .off case .updatingGraph: buttonPlay.isEnabled = false buttonLoadAU.isEnabled = false } case .loadingEffects(let isBusy): buttonLoadAU.isEnabled = !isBusy && state.contains(.canOpenEffect) default: buttonLoadAU.isEnabled = state.contains(.canOpenEffect) } if !isHostTitleBar { buttonLoadAU.isEnabled = true } } }
mit
a909f460be8374ae93c957955c433eaf
29.766355
128
0.670413
4.314548
false
false
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 15 - Beginning CloudKit/BabiFud-Starter/BabiFud/NotesTableViewController.swift
3
2920
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import CloudKit class NotesCell : UITableViewCell { @IBOutlet var thumbImageView: UIImageView! { didSet { thumbImageView.clipsToBounds = true thumbImageView.layer.cornerRadius = 6 } } @IBOutlet var titleLabel: UILabel! @IBOutlet var notesLabel: UILabel! } class NotesTableViewController: UITableViewController { var notes : NSArray! = [] override func viewDidLoad() { super.viewDidLoad() Model.sharedInstance().fetchNotes { (notes : NSArray!, error : NSError!) in if error == nil { self.notes = notes; dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } } } // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return notes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("NotesCell", forIndexPath: indexPath) as NotesCell let record:CKRecord = notes[indexPath.row] as CKRecord cell.notesLabel.text = record.objectForKey("Note") as? String let establishmentRef = record.objectForKey("Establishment") as CKReference if let establishment = Model.sharedInstance().establishment(establishmentRef) { cell.titleLabel.text = establishment.name establishment.loadCoverPhoto() { photo in dispatch_async(dispatch_get_main_queue()) { cell.thumbImageView.image = photo } } } else { cell.thumbImageView.image = nil; cell.titleLabel.text = "???" } return cell } }
mit
2748e87e4288deff42e5f813e4cd4ca2
32.181818
116
0.715753
4.717286
false
false
false
false
humeng12/DouYuZB
DouYuZB/DouYuZB/Classes/Main/View/PageTitleView.swift
1
5488
// // PageTitleView.swift // DouYuZB // // Created by 胡猛 on 16/11/6. // Copyright © 2016年 HuMeng. All rights reserved. // import UIKit protocol PageTitleViewDelegate : class{ func pageTitleView(titleView : PageTitleView,selectedIndex index : Int) } private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85) private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0) private let scrollLineH : CGFloat = 2 class PageTitleView: UIView { //定义属性 fileprivate var currentIndex : Int = 0 fileprivate var titles:[String] weak var delegate : PageTitleViewDelegate? fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.isPagingEnabled = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //自定义构造函数 init(frame: CGRect,titles: [String]) { self.titles = titles; super.init(frame: frame) //设置ui界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { fileprivate func setupUI() { addSubview(scrollView) scrollView.frame = bounds setupTitleLabels() setupBottomMenuAndScrollLine() } fileprivate func setupTitleLabels() { let labelW : CGFloat = frame.width / (CGFloat)(titles.count) let labelH : CGFloat = frame.height - scrollLineH let labelY : CGFloat = 0 for (index,title) in titles.enumerated() { let label = UILabel() label.text = title; label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor.gray label.textAlignment = .center let labelX : CGFloat = labelW * (CGFloat)(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollView.addSubview(label) titleLabels.append(label) //添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(_ :))) label.addGestureRecognizer(tapGes) } } fileprivate func setupBottomMenuAndScrollLine() { //添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: 0, width:frame.height - lineH , height: lineH) addSubview(bottomLine) //添加scrollLine guard let firstLabel = titleLabels.first else {return} firstLabel.textColor = UIColor.orange scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - scrollLineH, width: firstLabel.frame.width, height: scrollLineH) } } extension PageTitleView { @objc fileprivate func titleLabelClick(_ tapGes:UITapGestureRecognizer) { //获取当前Label guard let currentLabel = tapGes.view as? UILabel else {return} if currentLabel.tag == currentIndex { return } //获取之前Label let oldLabel = titleLabels[currentIndex] //改变文字颜色 currentLabel.textColor = UIColor.orange oldLabel.textColor = UIColor.darkGray //保存最新UILabel的下标值 currentIndex = currentLabel.tag //滚动条位置变化 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.15, animations: { self.scrollLine.frame.origin.x = scrollLineX }); //通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int,targetIndex : Int) { let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX //颜色渐变 let colorDelta = (kSelectColor.0 - kNormalColor.0,kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g:kSelectColor.1 - colorDelta.1 * progress , b: kSelectColor.2 - colorDelta.2 * progress) targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g:kNormalColor.1 + colorDelta.1 * progress , b: kNormalColor.2 + colorDelta.2 * progress) currentIndex = targetIndex } }
mit
ffa4c3c15bbd8f2833304362b1f781d8
28.596685
174
0.608736
5.116523
false
false
false
false
lady12/firefox-ios
Client/Frontend/Browser/Browser.swift
9
13158
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Storage import Shared import XCGLogger private let log = Logger.browserLogger protocol BrowserHelper { static func name() -> String func scriptMessageHandlerName() -> String? func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } @objc protocol BrowserDelegate { func browser(browser: Browser, didAddSnackbar bar: SnackBar) func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) optional func browser(browser: Browser, didCreateWebView webView: WKWebView) optional func browser(browser: Browser, willDeleteWebView webView: WKWebView) } class Browser: NSObject { var webView: WKWebView? = nil var browserDelegate: BrowserDelegate? = nil var bars = [SnackBar]() var favicons = [Favicon]() var lastExecutedTime: Timestamp? var sessionData: SessionData? var lastRequest: NSURLRequest? = nil var restoring: Bool = false /// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs. var lastTitle: String? private(set) var screenshot: UIImage? var screenshotUUID: NSUUID? private var helperManager: HelperManager? = nil private var configuration: WKWebViewConfiguration? = nil init(configuration: WKWebViewConfiguration) { self.configuration = configuration } class func toTab(browser: Browser) -> RemoteTab? { if let displayURL = browser.displayURL { let history = Array(browser.historyList.filter(RemoteTab.shouldIncludeURL).reverse()) return RemoteTab(clientGUID: nil, URL: displayURL, title: browser.displayTitle, history: history, lastUsed: NSDate.now(), icon: nil) } else if let sessionData = browser.sessionData where !sessionData.urls.isEmpty { let history = Array(sessionData.urls.reverse()) return RemoteTab(clientGUID: nil, URL: history[0], title: browser.displayTitle, history: history, lastUsed: sessionData.lastUsedTime, icon: nil) } return nil } weak var navigationDelegate: WKNavigationDelegate? { didSet { if let webView = webView { webView.navigationDelegate = navigationDelegate } } } func createWebview() { if webView == nil { assert(configuration != nil, "Create webview can only be called once") configuration!.userContentController = WKUserContentController() configuration!.preferences = WKPreferences() configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false let webView = WKWebView(frame: CGRectZero, configuration: configuration!) configuration = nil webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.allowsBackForwardNavigationGestures = true webView.backgroundColor = UIColor.lightGrayColor() // Turning off masking allows the web content to flow outside of the scrollView's frame // which allows the content appear beneath the toolbars in the BrowserViewController webView.scrollView.layer.masksToBounds = false webView.navigationDelegate = navigationDelegate helperManager = HelperManager(webView: webView) restore(webView) self.webView = webView browserDelegate?.browser?(self, didCreateWebView: webView) // lastTitle is used only when showing zombie tabs after a session restore. // Since we now have a web view, lastTitle is no longer useful. lastTitle = nil } } func restore(webView: WKWebView) { // Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore // has already been triggered via custom URL, so we use the last request to trigger it again; otherwise, // we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL // to trigger the session restore via custom handlers if let sessionData = self.sessionData { restoring = true var updatedURLs = [String]() for url in sessionData.urls { let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString updatedURLs.append(updatedURL) } let currentPage = sessionData.currentPage self.sessionData = nil var jsonDict = [String: AnyObject]() jsonDict["history"] = updatedURLs jsonDict["currentPage"] = currentPage let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)") lastRequest = NSURLRequest(URL: restoreURL!) webView.loadRequest(lastRequest!) } else if let request = lastRequest { webView.loadRequest(request) } else { log.error("creating webview with no lastRequest and no session data: \(self.url)") } } deinit { if let webView = webView { browserDelegate?.browser?(self, willDeleteWebView: webView) } } var loading: Bool { return webView?.loading ?? false } var estimatedProgress: Double { return webView?.estimatedProgress ?? 0 } var backList: [WKBackForwardListItem]? { return webView?.backForwardList.backList } var forwardList: [WKBackForwardListItem]? { return webView?.backForwardList.forwardList } var historyList: [NSURL] { func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL } var tabs = self.backList?.map(listToUrl) ?? [NSURL]() tabs.append(self.url!) return tabs } var title: String? { return webView?.title } var displayTitle: String { if let title = webView?.title { if !title.isEmpty { return title } } return displayURL?.absoluteString ?? lastTitle ?? "" } var displayFavicon: Favicon? { var width = 0 var largest: Favicon? for icon in favicons { if icon.width > width { width = icon.width! largest = icon } } return largest } var url: NSURL? { return webView?.URL ?? lastRequest?.URL } var displayURL: NSURL? { if let url = url { if ReaderModeUtils.isReaderModeURL(url) { return ReaderModeUtils.decodeURL(url) } if ErrorPageHelper.isErrorPageURL(url) { let decodedURL = ErrorPageHelper.decodeURL(url) if !AboutUtils.isAboutURL(decodedURL) { return decodedURL } else { return nil } } if !AboutUtils.isAboutURL(url) { return url } } return nil } var canGoBack: Bool { return webView?.canGoBack ?? false } var canGoForward: Bool { return webView?.canGoForward ?? false } func goBack() { webView?.goBack() } func goForward() { webView?.goForward() } func goToBackForwardListItem(item: WKBackForwardListItem) { webView?.goToBackForwardListItem(item) } func loadRequest(request: NSURLRequest) -> WKNavigation? { if let webView = webView { lastRequest = request return webView.loadRequest(request) } return nil } func stop() { webView?.stopLoading() } func reload() { if let _ = webView?.reloadFromOrigin() { log.info("reloaded zombified tab from origin") return } if let webView = self.webView { log.info("restoring webView from scratch") restore(webView) } } func addHelper(helper: BrowserHelper, name: String) { helperManager!.addHelper(helper, name: name) } func getHelper(name name: String) -> BrowserHelper? { return helperManager?.getHelper(name: name) } func hideContent(animated: Bool = false) { webView?.userInteractionEnabled = false if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 0.0 }) } else { webView?.alpha = 0.0 } } func showContent(animated: Bool = false) { webView?.userInteractionEnabled = true if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 1.0 }) } else { webView?.alpha = 1.0 } } func addSnackbar(bar: SnackBar) { bars.append(bar) browserDelegate?.browser(self, didAddSnackbar: bar) } func removeSnackbar(bar: SnackBar) { if let index = bars.indexOf(bar) { bars.removeAtIndex(index) browserDelegate?.browser(self, didRemoveSnackbar: bar) } } func removeAllSnackbars() { // Enumerate backwards here because we'll remove items from the list as we go. for var i = bars.count-1; i >= 0; i-- { let bar = bars[i] removeSnackbar(bar) } } func expireSnackbars() { // Enumerate backwards here because we may remove items from the list as we go. for var i = bars.count-1; i >= 0; i-- { let bar = bars[i] if !bar.shouldPersist(self) { removeSnackbar(bar) } } } func setScreenshot(screenshot: UIImage?, revUUID: Bool = true) { self.screenshot = screenshot if revUUID { self.screenshotUUID = NSUUID() } } } private class HelperManager: NSObject, WKScriptMessageHandler { private var helpers = [String: BrowserHelper]() private weak var webView: WKWebView? init(webView: WKWebView) { self.webView = webView } @objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addHelper(helper: BrowserHelper, name: String) { if let _ = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right BrowserHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName) } } func getHelper(name name: String) -> BrowserHelper? { return helpers[name] } } extension WKWebView { func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) { if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String { evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in if let err = err { print("Error injecting \(err)") return } self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in }) if let err = err { print("Error running \(err)") return } callback(obj) }) }) } } } }
mpl-2.0
2f507c35d781264303b393c47e4b9d47
32.566327
167
0.600699
5.425979
false
false
false
false
ahoppen/swift
test/Parse/confusables.swift
9
2105
// RUN: %target-typecheck-verify-swift // expected-error @+4 {{type annotation missing in pattern}} // expected-error @+3 {{cannot find operator '⁚' in scope}} // expected-error @+2 {{operator with postfix spacing cannot start a subexpression}} // expected-error @+1 {{consecutive statements on a line must be separated by ';'}} let number⁚ Int // expected-note {{operator '⁚' (Two Dot Punctuation) looks similar to ':' (Colon); did you mean ':' (Colon)?}} {{11-14=:}} // expected-warning @+3 2 {{integer literal is unused}} // expected-error @+2 {{invalid character in source file}} // expected-error @+1 {{consecutive statements on a line must be separated by ';'}} 5 ‒ 5 // expected-note {{unicode character '‒' (Figure Dash) looks similar to '-' (Hyphen Minus); did you mean to use '-' (Hyphen Minus)?}} {{3-6=-}} // expected-error @+2 {{cannot find 'ꝸꝸꝸ' in scope}} // expected-error @+1 {{expected ',' separator}} if (true ꝸꝸꝸ false) {} // expected-note {{identifier 'ꝸꝸꝸ' contains possibly confused characters; did you mean to use '&&&'?}} {{10-19=&&&}} // expected-error @+3 {{invalid character in source file}} // expected-error @+2 {{expected ',' separator}} // expected-error @+1 {{type '(Int, Int)' cannot conform to 'BinaryInteger'}} if (5 ‒ 5) == 0 {} // expected-note {{unicode character '‒' (Figure Dash) looks similar to '-' (Hyphen Minus); did you mean to use '-' (Hyphen Minus)?}} {{7-10=-}} // expected-note @-1 {{operator function '=='}} // expected-note @-2 {{only concrete types such as structs, enums and classes can conform to protocols}} // FIXME(rdar://61028087): The above note should read "required by referencing operator function '==' on 'BinaryInteger' where 'Self' = '(Int, Int)'". // GREEK QUESTION MARK (which looks like a semicolon) print("A"); print("B") // expected-error@-1 2{{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{cannot find ';' in scope}} // expected-note@-3 {{identifier ';' (Greek Question Mark) looks similar to ';' (Semicolon); did you mean ';' (Semicolon)?}} {{11-13=;}}
apache-2.0
2d0e860322f33500a69b09b8815af257
65.774194
163
0.666184
3.556701
false
false
false
false
patrick-sheehan/cwic
Source/UIColor.swift
1
2515
// // UIColor.swift // SlideMenuControllerSwift // // Created by Yuji Hato on 11/5/15. // Copyright © 2015 Yuji Hato. All rights reserved. // import UIKit extension UIColor { public convenience init?(hexString: String) { let r, g, b, a: CGFloat if hexString.hasPrefix("#") { let start = hexString.index(hexString.startIndex, offsetBy: 1) let hexColor = String(hexString[start...]) if hexColor.count == 8 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 a = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } } } return nil } // convenience init(hex: String) { // self.init(hex: hex, alpha:1) // } // // convenience init(hex: String, alpha: CGFloat) { // var hexWithoutSymbol = hex // if hexWithoutSymbol.hasPrefix("#") { // hexWithoutSymbol = hex.substring(1) // } // // let scanner = Scanner(string: hexWithoutSymbol) // var hexInt:UInt32 = 0x0 // scanner.scanHexInt32(&hexInt) // // var r:UInt32!, g:UInt32!, b:UInt32! // switch (hexWithoutSymbol.length) { // case 3: // #RGB // r = ((hexInt >> 4) & 0xf0 | (hexInt >> 8) & 0x0f) // g = ((hexInt >> 0) & 0xf0 | (hexInt >> 4) & 0x0f) // b = ((hexInt << 4) & 0xf0 | hexInt & 0x0f) // break; // case 6: // #RRGGBB // r = (hexInt >> 16) & 0xff // g = (hexInt >> 8) & 0xff // b = hexInt & 0xff // break; // default: // // TODO:ERROR // break; // } // // self.init( // red: (CGFloat(r)/255), // green: (CGFloat(g)/255), // blue: (CGFloat(b)/255), // alpha:alpha) // } // // convenience init(red: Int, green: Int, blue: Int) { // assert(red >= 0 && red <= 255, "Invalid red component") // assert(green >= 0 && green <= 255, "Invalid green component") // assert(blue >= 0 && blue <= 255, "Invalid blue component") // // self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) // } // // convenience init(netHex:Int) { // self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) // } }
gpl-3.0
84d0e0756e93259d454c20a20cb6fd62
26.626374
114
0.536595
3.096059
false
false
false
false
evan-liu/CommandArguments
Doc.playground/Pages/Inheritance.xcplaygroundpage/Contents.swift
1
542
//: [Previous](@previous) import Foundation import CommandArguments enum Platform: String, ArgumentConvertible { case iOS, watchOS, macOS } class AppleArgs { var platform = OptionT<Platform>(usage: "Apple platform (iOS|watchOS|macOS)") } final class BuildArgs: AppleArgs, CommandArguments { let commandName = "build" var clear = Flag() } final class DeployArgs: AppleArgs, CommandArguments { let commandName = "deploy" var report = Flag() } print(BuildArgs().usage()) print(DeployArgs().usage()) //: [Next](@next)
mit
ef47407ed15807852e5809800ece6e44
21.583333
81
0.706642
3.956204
false
false
false
false
swernimo/iOS
UI Kit Fundamentals 1/MemeMe/MemeMe/MemeCollectionViewController.swift
1
1648
// // MemeCollectionViewController.swift // MemeMe // // Created by Sean Wernimont on 11/29/15. // Copyright © 2015 Just One Guy. All rights reserved. // import Foundation import UIKit class MemeCollectionViewController: UICollectionViewController{ var memeArray: [Meme] = []; override func viewWillAppear(animated: Bool) { loadMemesFromAppDelegate(); collectionView?.reloadData(); } func loadMemesFromAppDelegate() -> Void{ let object = UIApplication.sharedApplication().delegate let appDelegate = object as! AppDelegate memeArray = appDelegate.memesArray; } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionViewCell", forIndexPath: indexPath) as! CustomMemeCell; let meme = memeArray[indexPath.row]; cell.backgroundView = UIImageView(image: meme.memeImage); return cell; } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return memeArray.count; } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let detailController = self.storyboard!.instantiateViewControllerWithIdentifier("MemeDetailViewController") as! MemeDetailViewController detailController.meme = memeArray[indexPath.row]; self.navigationController!.pushViewController(detailController, animated: true) } }
mit
f4f14c1153071c4d6d71733c10a95259
37.302326
144
0.728597
5.67931
false
false
false
false
lucaslt89/simpsonizados
simpsonizados/Pods/Kanna/Source/libxml/libxmlParserOption.swift
5
6056
/**@file libxmlParserOption.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 libxml2 /* Libxml2HTMLParserOptions */ public struct Libxml2HTMLParserOptions : OptionSetType { public typealias RawValue = UInt private var value: UInt = 0 init(_ value: UInt) { self.value = value } private init(_ opt: htmlParserOption) { self.value = UInt(opt.rawValue) } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: Libxml2HTMLParserOptions { return self.init(0) } static func fromMask(raw: UInt) -> Libxml2HTMLParserOptions { return self.init(raw) } public var rawValue: UInt { return self.value } static var STRICT: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(0) } static var RECOVER: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_RECOVER) } static var NODEFDTD: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NODEFDTD) } static var NOERROR: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOERROR) } static var NOWARNING: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOWARNING) } static var PEDANTIC: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_PEDANTIC) } static var NOBLANKS: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOBLANKS) } static var NONET: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NONET) } static var NOIMPLIED: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOIMPLIED) } static var COMPACT: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_COMPACT) } static var IGNORE_ENC: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_IGNORE_ENC) } } /* Libxml2XMLParserOptions */ public struct Libxml2XMLParserOptions: OptionSetType { public typealias RawValue = UInt private var value: UInt = 0 init(_ value: UInt) { self.value = value } private init(_ opt: xmlParserOption) { self.value = UInt(opt.rawValue) } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: Libxml2XMLParserOptions { return self.init(0) } static func fromMask(raw: UInt) -> Libxml2XMLParserOptions { return self.init(raw) } public var rawValue: UInt { return self.value } static var STRICT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(0) } static var RECOVER: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_RECOVER) } static var NOENT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOENT) } static var DTDLOAD: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDLOAD) } static var DTDATTR: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDATTR) } static var DTDVALID: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDVALID) } static var NOERROR: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOERROR) } static var NOWARNING: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOWARNING) } static var PEDANTIC: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_PEDANTIC) } static var NOBLANKS: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOBLANKS) } static var SAX1: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_SAX1) } static var XINCLUDE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_XINCLUDE) } static var NONET: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NONET) } static var NODICT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NODICT) } static var NSCLEAN: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NSCLEAN) } static var NOCDATA: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOCDATA) } static var NOXINCNODE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOXINCNODE) } static var COMPACT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_COMPACT) } static var OLD10: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_OLD10) } static var NOBASEFIX: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOBASEFIX) } static var HUGE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_HUGE) } static var OLDSAX: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_OLDSAX) } static var IGNORE_ENC: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_IGNORE_ENC) } static var BIG_LINES: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_BIG_LINES) } }
mit
7da45f030e90536c373165d57c3e23cd
64.826087
110
0.774273
3.808805
false
false
false
false
JudoPay/JudoKitObjC
JudoKitObjCExampleAppUITests/JudoKitCheckCardTests.swift
1
3206
// // JudoKitCheckCardTests.swift // JudoKitSwiftExample // // Copyright (c) 2019 Alternative Payments 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 XCTest class JudoKitCheckCardTests: XCTestCase { private let existsPredicate = NSPredicate(format: "exists == 1") override func setUp() { super.setUp(); continueAfterFailure = false XCUIApplication().launch() } func test_OnCheckCardTap_DisplayCheckCardForm() { let app = XCUIApplication() app.tables.staticTexts["Check card"].tap() XCTAssertTrue(app.navigationBars["Check Card"].exists); } func test_OnCheckCardValidParameters_DisplayDetailsScreen() { let app = XCUIApplication() app.tables.staticTexts["Check card"].tap() app.secureTextFields["Card number"].typeText("4976000000003436") app.textFields["Expiry date"].typeText("1220") app.secureTextFields["CVV2"].typeText("452") app.buttons["Pay"].firstMatch.tap() let cardDetailsNavigation = app.navigationBars["Payment receipt"] let detailsExpectation = expectation(for: existsPredicate, evaluatedWith: cardDetailsNavigation, handler: nil) wait(for: [detailsExpectation], timeout: 20.0) } func test_OnCheckCardInvalidParameters_DisplayErrorAlert() { let app = XCUIApplication() app.tables.staticTexts["Check card"].tap() app.secureTextFields["Card number"].typeText("5500 0000 0000 0004") app.textFields["Expiry date"].typeText("1228") app.secureTextFields["CVC2"].typeText("999") app.buttons["Pay"].firstMatch.tap() let errorAlert = app.alerts.firstMatch.staticTexts["Error"]; let errorAlertExpectation = expectation(for: existsPredicate, evaluatedWith: errorAlert, handler: nil) wait(for: [errorAlertExpectation], timeout: 20.0) } }
mit
076f633b3f751aa6fe079e6a2fa3fcb3
39.075
82
0.649407
4.924731
false
true
false
false
AlexIzh/Griddle
Griddle/Classes/TableView/TablePresenter.swift
1
11506
// // TablePresenter.swift // CollectionPresenter // // Created by Alex on 18/02/16. // Copyright © 2016 Moqod. All rights reserved. // import Foundation import UIKit /* public protocol TablePresenterDelegate: PresenterDelegate { func presenter(_ presenter:Presenter, canMoveCellFromIndexPath fromIndexPath: IndexPath , toIndexPath: IndexPath) -> Bool func presenter(_ presenter:Presenter, didMoveCellFromIndexPath fromIndexPath: IndexPath , toIndexPath: IndexPath) } public extension TablePresenterDelegate { func presenter(_ presenter:Presenter, didMoveCellFromIndexPath fromIndexPath: IndexPath , toIndexPath: IndexPath) {} func presenter(_ presenter:Presenter, canMoveCellFromIndexPath fromIndexPath: IndexPath , toIndexPath: IndexPath) -> Bool { return true } }*/ open class TablePresenter<DataSourceModel: DataSource>: Presenter<DataSourceModel>, UITableViewDataSource, UITableViewDelegate { open let tableView: UITableView open var insertAnimation: UITableViewRowAnimation = .fade open var deleteAnimation: UITableViewRowAnimation = .fade open var updateAnimation: UITableViewRowAnimation = .none public init(_ tableView: UITableView, source: DataSourceModel, map: Map) { self.tableView = tableView super.init(source: source, map: map) self.tableView.delegate = self self.tableView.dataSource = self } open override func dataSourceDidRefresh(_: DataSourceModel) { tableView.reloadData() } open override func dataSourceDidBeginEditing(_: DataSourceModel) { tableView.beginUpdates() } open override func dataSourceDidEndEditing(_: DataSourceModel) { tableView.endUpdates() } open override func dataSource(_ dataSource: DataSourceModel, didMoveItemFrom from: IndexPath, to: IndexPath) { switch (from, to) { case (.item(let section, let index), .item(let toSection, let toIndex)): tableView.moveRow(at: Foundation.IndexPath(row: index, section: section), to: Foundation.IndexPath(row: toIndex, section: toSection)) case (.header(let section), .header(let toSection)): tableView.reloadSections(IndexSet([section, toSection]), with: updateAnimation) case (.footer(let section), .footer(let toSection)): tableView.reloadSections(IndexSet([section, toSection]), with: updateAnimation) default: assertionFailure("IndexPath'es are invalid. (from: \(from), to: \(to))") } } open override func dataSource(_ dataSource: DataSourceModel, didDeleteItemAt indexPath: IndexPath) { switch indexPath { case .item(let section, let index): tableView.deleteRows(at: [Foundation.IndexPath(row: index, section: section)], with: deleteAnimation) case .header(let section): tableView.reloadSections(IndexSet(integer: section), with: updateAnimation) case .footer(let section): tableView.reloadSections(IndexSet(integer: section), with: updateAnimation) } } open override func dataSource(_ dataSource: DataSourceModel, didInsertItemAt indexPath: IndexPath) { switch indexPath { case .item(let section, let index): tableView.insertRows(at: [Foundation.IndexPath(row: index, section: section)], with: insertAnimation) case .header(let section): tableView.reloadSections(IndexSet(integer: section), with: updateAnimation) case .footer(let section): tableView.reloadSections(IndexSet(integer: section), with: updateAnimation) } } open override func dataSource(_ dataSource: DataSourceModel, didUpdateItemAt indexPath: IndexPath) { switch indexPath { case .item(let section, let index): tableView.reloadRows(at: [Foundation.IndexPath(row: index, section: section)], with: updateAnimation) case .header(let section): tableView.reloadSections(IndexSet(integer: section), with: updateAnimation) case .footer(let section): tableView.reloadSections(IndexSet(integer: section), with: updateAnimation) } } open override func dataSource(_ dataSource: DataSourceModel, didMoveSectionFrom from: Int, to: Int) { tableView.reloadSections(IndexSet([from, to]), with: updateAnimation) } open override func dataSource(_ dataSource: DataSourceModel, didDeleteSectionAt index: Int) { tableView.reloadSections(IndexSet([index]), with: deleteAnimation) } open override func dataSource(_ dataSource: DataSourceModel, didInsertSectionAt index: Int) { tableView.reloadSections(IndexSet([index]), with: insertAnimation) } open override func dataSource(_ dataSource: DataSourceModel, didUpdateSectionAt index: Int) { tableView.reloadSections(IndexSet([index]), with: updateAnimation) } // MARK: - Register Reusable Views open override func registerReusableViews() { super.registerReusableViews() for cell in map.registrationItems { switch cell.viewType { case .nib(let nib): if cell.itemType != .row { tableView.register(nib, forHeaderFooterViewReuseIdentifier: cell.identifier) } else { tableView.register(nib, forCellReuseIdentifier: cell.identifier) } case .viewClass(let cellClass): if cell.itemType != .row { tableView.register(cellClass, forHeaderFooterViewReuseIdentifier: cell.identifier) } else { tableView.register(cellClass, forCellReuseIdentifier: cell.identifier) } } } } // } // MARK: - UITableViewDataSource, UITableViewDelegate // extension TablePresenter /*: UITableViewDataSource, UITableViewDelegate*/ { public func numberOfSections(in tableView: UITableView) -> Int { return dataSource.sectionsCount } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.itemsCount(for: section) } public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: Foundation.IndexPath) -> CGFloat { guard let row = dataSource.item(at: indexPath.section, index: indexPath.row) else { return 0 } let innerIndexPath = IndexPath(.table, indexPath) let info = map.viewInfo(for: row, indexPath: innerIndexPath) return info?.estimatedSize(row, tableView)?.height ?? tableView.estimatedRowHeight } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: Foundation.IndexPath) -> CGFloat { guard let row = dataSource.item(at: indexPath.section, index: indexPath.row) else { return 0 } let innerIndexPath = IndexPath(.table, indexPath) let info = map.viewInfo(for: row, indexPath: innerIndexPath) return info?.size(row, tableView)?.height ?? tableView.rowHeight } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: Foundation.IndexPath) -> UITableViewCell { guard let row = dataSource.item(at: indexPath.section, index: indexPath.row) else { fatalError("DataSource (\(dataSource)) doesn't contain item with indexPath (\(indexPath))") } let innerIndexPath = IndexPath(.table, indexPath) guard let info = map.viewInfo(for: row, indexPath: innerIndexPath) else { fatalError("Map did not return information about view with \(innerIndexPath) for model \(row)") } let cell = tableView.dequeueReusableCell(withIdentifier: info.identifier, for: indexPath) info.setModel(cell, row) delegate.didUpdateCell(cell, row, (indexPath.section, indexPath.row)) return cell } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let row = dataSource.header(at: section) else { return 0 } let info = map.viewInfo(for: row, indexPath: .header(section: section)) return info?.size(row, tableView)?.height ?? tableView.sectionHeaderHeight } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { guard let row = dataSource.footer(at: section) else { return 0 } let info = map.viewInfo(for: row, indexPath: .footer(section: section)) return info?.size(row, tableView)?.height ?? tableView.sectionFooterHeight } public func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat { guard let row = dataSource.footer(at: section) else { return 0 } let info = map.viewInfo(for: row, indexPath: .footer(section: section)) return info?.estimatedSize(row, tableView)?.height ?? tableView.estimatedSectionHeaderHeight } public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { guard let row = dataSource.header(at: section) else { return 0 } let info = map.viewInfo(for: row, indexPath: .header(section: section)) return info?.estimatedSize(row, tableView)?.height ?? tableView.estimatedSectionFooterHeight } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let row = dataSource.header(at: section), let info = map.viewInfo(for: row, indexPath: .header(section: section)) else { return nil } let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: info.identifier) if let view = view { info.setModel(view, row) delegate.didUpdateHeader(view, row, section) } return view } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let row = dataSource.footer(at: section), let info = map.viewInfo(for: row, indexPath: .footer(section: section)) else { return nil } let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: info.identifier) if let view = view { info.setModel(view, row) delegate.didUpdateFooter(view, row, section) } return view } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: Foundation.IndexPath) { guard let row = dataSource.item(at: indexPath.section, index: indexPath.row) else { return } if let cell = tableView.cellForRow(at: indexPath) { delegate.didSelectCell(cell, row, (indexPath.section, indexPath.row)) } } // public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: Foundation.IndexPath, to destinationIndexPath: Foundation.IndexPath) { // let source = IndexPath(.table, sourceIndexPath) // let destination = IndexPath(.table, destinationIndexPath) // (self.delegate as? TablePresenterDelegate)?.presenter(self, didMoveCellFromIndexPath: source, toIndexPath: destination) // } // // public func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: Foundation.IndexPath, toProposedIndexPath proposedDestinationIndexPath: Foundation.IndexPath) -> Foundation.IndexPath { // guard let canMove = (self.delegate as? TablePresenterDelegate)?.presenter(self, canMoveCellFromIndexPath: IndexPath(.table, sourceIndexPath), toIndexPath: IndexPath(.table, proposedDestinationIndexPath)) else { // return sourceIndexPath // } // guard canMove == true else { // return sourceIndexPath // } // return proposedDestinationIndexPath // } }
mit
77c8a3793764bb4f77061dca249d78d9
41.929104
225
0.704216
5.030608
false
false
false
false
thewisecity/declarehome-ios
CookedApp/ViewControllers/EditUserDetailsViewController.swift
1
12779
// // EditUserDetailsViewController.swift // CookedApp // // Created by Dexter Lohnes on 11/9/15. // Copyright © 2015 The Wise City. All rights reserved. // import UIKit class EditUserDetailsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var scrollView : UIScrollView! var contentContainer : UIView! var profilePicture : PFImageView! var loadingView : UIView! let imagePicker = UIImagePickerController() var hasPickedImage:Bool = false var profilePicUploadFile:PFFile? var uploadButton : UIButton! var doneButton : UIButton! var nameLabel : UILabel! var emailLabel : UILabel! var mobileLabel : UILabel! var link1Label : UILabel! var link2Label : UILabel! var link3Label : UILabel! var descriptionLabel : UILabel! var nameTextField : UITextField! var emailTextField : UITextField! var mobileTextField : UITextField! var link1TextField : UITextField! var link2TextField : UITextField! var link3TextField : UITextField! var descriptionTextView : UITextView! let leftMargin = 14 as CGFloat let rightMargin = 14 as CGFloat let topMargin = 20 as CGFloat var keyboardIsShowing = false override func viewDidLoad() { super.viewDidLoad() scrollView = UIScrollView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) view.addSubview(scrollView) view.backgroundColor = UIColor.whiteColor() scrollView.contentSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 680) contentContainer = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 680)) contentContainer.backgroundColor = UIColor.whiteColor() loadingView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 680)) loadingView.backgroundColor = UIColor.whiteColor() let spinner = UIActivityIndicatorView(frame: CGRectMake(UIScreen.mainScreen().bounds.width / 2 - 25, UIScreen.mainScreen().bounds.height / 2 - 25, 50, 50)) loadingView.addSubview(spinner) spinner.startAnimating() loadingView.backgroundColor = UIColor(white: 0.1, alpha: 0.1) loadingView.hidden = true scrollView.addSubview(contentContainer) profilePicture = PFImageView(frame: CGRectMake(leftMargin, topMargin, 120, 120)) profilePicture.image = UIImage(named: "DefaultBioPic") roundImageCorners(profilePicture) let textfieldWidth = contentContainer.frame.width - leftMargin - rightMargin uploadButton = UIButton(frame:CGRectMake(142, 98, 65, 30)) uploadButton.setTitle("Upload", forState: .Normal) uploadButton.setTitleColor(UIColor.blueColor(), forState: .Normal) uploadButton.addTarget(self, action: "uploadNewProfilePic", forControlEvents: .TouchDown) nameLabel = UILabel(frame:CGRectMake(14,146,100,21)) nameLabel.text = "Name" emailLabel = UILabel(frame:CGRectMake(14,200,100,21)) emailLabel.text = "Email" mobileLabel = UILabel(frame:CGRectMake(14,254,100,21)) mobileLabel.text = "Mobile Phone" link1Label = UILabel(frame:CGRectMake(14,308,100,21)) link1Label.text = "Link" link2Label = UILabel(frame:CGRectMake(14,362,100,21)) link2Label.text = "Link" link3Label = UILabel(frame:CGRectMake(14,416,100,21)) link3Label.text = "Link" descriptionLabel = UILabel(frame:CGRectMake(14,484,200,21)) descriptionLabel.text = "Short Description (200 chars max)" nameTextField = UITextField(frame: CGRectMake(14, 168, textfieldWidth, 30)) nameTextField.borderStyle = .RoundedRect emailTextField = UITextField(frame: CGRectMake(14, 222, textfieldWidth, 30)) emailTextField.borderStyle = .RoundedRect mobileTextField = UITextField(frame: CGRectMake(14, 276, textfieldWidth, 30)) mobileTextField.borderStyle = .RoundedRect link1TextField = UITextField(frame: CGRectMake(14, 330, textfieldWidth, 30)) link1TextField.borderStyle = .RoundedRect link2TextField = UITextField(frame: CGRectMake(14, 384, textfieldWidth, 30)) link2TextField.borderStyle = .RoundedRect link3TextField = UITextField(frame: CGRectMake(14, 438, textfieldWidth, 30)) link3TextField.borderStyle = .RoundedRect descriptionTextView = UITextView(frame: CGRectMake(14, 506, textfieldWidth, 60)) descriptionTextView.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.1) doneButton = UIButton(frame: CGRectMake(contentContainer.frame.width / 2 - 18, 586, 50, 27)) doneButton.setTitle("Done", forState: .Normal) doneButton.setTitleColor(UIColor.blueColor(), forState: .Normal) doneButton.addTarget(self, action: "submitNewUserInfo", forControlEvents: .TouchDown) styleLabel(nameLabel) styleLabel(emailLabel) styleLabel(mobileLabel) styleLabel(link1Label) styleLabel(link2Label) styleLabel(link3Label) styleLabel(descriptionLabel) contentContainer.addSubview(profilePicture) contentContainer.addSubview(uploadButton) contentContainer.addSubview(nameLabel) contentContainer.addSubview(emailLabel) contentContainer.addSubview(mobileLabel) contentContainer.addSubview(link1Label) contentContainer.addSubview(link2Label) contentContainer.addSubview(link3Label) contentContainer.addSubview(descriptionLabel) contentContainer.addSubview(nameTextField) contentContainer.addSubview(emailTextField) contentContainer.addSubview(mobileTextField) contentContainer.addSubview(link1TextField) contentContainer.addSubview(link2TextField) contentContainer.addSubview(link3TextField) contentContainer.addSubview(descriptionTextView) contentContainer.addSubview(doneButton) contentContainer.addSubview(loadingView) let user = PFUser.currentUser() profilePicture.file = user?.objectForKey("profilePic") as? PFFile profilePicture.loadInBackground() nameTextField.text = user?.objectForKey("displayName") as? String emailTextField.text = user?.email mobileTextField.text = user?.objectForKey("phoneNumber") as? String link1TextField.text = user?.objectForKey("linkOne") as? String link2TextField.text = user?.objectForKey("linkTwo") as? String link3TextField.text = user?.objectForKey("linkThree") as? String descriptionTextView.text = user?.objectForKey("userDescription") as? String } private func styleLabel(label: UILabel) { label.font = UIFont.systemFontOfSize(11) label.textColor = UIColor.grayColor() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) } func uploadNewProfilePic() { imagePicker.allowsEditing = false imagePicker.sourceType = .SavedPhotosAlbum imagePicker.delegate = self presentViewController(imagePicker, animated: true, completion: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { if keyboardIsShowing == false { print("Keyboard will show") let keyboardFrame = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() var frame = self.view.frame frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.32) UIView.setAnimationCurve(UIViewAnimationCurve.EaseOut) self.view.frame = frame scrollView.frame = CGRectMake(0, 0, scrollView.frame.width, scrollView.frame.height - keyboardFrame!.height) UIView.commitAnimations() keyboardIsShowing = true } } func keyboardWillHide(notification: NSNotification) { if keyboardIsShowing == true { print("Keyboard will hide") var frame = self.view.frame frame = CGRect(x: 0, y: 0, width: frame.size.width, height: UIScreen.mainScreen().bounds.size.height) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.32) UIView.setAnimationCurve(UIViewAnimationCurve.EaseOut) self.view.frame = frame self.scrollView.frame = frame UIView.commitAnimations() keyboardIsShowing = false } } func submitNewUserInfo() { if (validateDisplayName(nameTextField.text) && validateEmail(emailTextField.text) && validatePhoneNumber(mobileTextField.text)) { loadingView.hidden = false let user = PFUser.currentUser() user?.setObject((nameTextField.text)!, forKey: "displayName") user?.email = emailTextField.text user?.setObject(link1TextField.text!, forKey: "linkOne") user?.setObject(mobileTextField.text!, forKey: "phoneNumber") user?.setObject(link2TextField.text!, forKey: "linkTwo") user?.setObject(link3TextField.text!, forKey: "linkThree") user?.setObject(descriptionTextView.text, forKey: "userDescription") if (hasPickedImage) { user?.setObject(profilePicUploadFile!, forKey: "profilePic") } user?.saveInBackgroundWithBlock({ ( success:Bool, error: NSError?) -> Void in if(success) { print("Saved user") //TODO: Launch alert with success self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } else { //TODO: Launch alert with failure message print("Error saving user") } }) } else { // TODO: Launch thing saying info was invalid } } /* // 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. } */ // MARK: - UIImagePickerControllerDelegate Methods func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { profilePicture.image = image; // profilePicture.setBackgroundImage(image, forState: UIControlState.Normal) hasPickedImage = true let data = UIImageJPEGRepresentation(image, 0.5) profilePicUploadFile = PFFile(name: "profilePic", data: data!) dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } }
gpl-3.0
22a487e9d8cdbbd9f1433b5556ca29ce
36.472141
163
0.643684
5.371164
false
false
false
false
dtartaglia/Apex
Apex/Store.swift
1
2184
// // Store.swift // Apex // // Created by Daniel Tartaglia on 01/16/15. // Copyright © 2017 Daniel Tartaglia. MIT License. // public protocol Action { } public protocol Publisher { associatedtype State typealias Observer = (State) -> Void func observe(observer: @escaping Observer) -> Unobserver } public final class Store<S>: Dispatcher, Publisher { public typealias State = S public init(initial: (State, [Command]), update: @escaping (State, Action) -> (State, [Command]), subscriptions: @escaping (State) -> Set<AnySubscription>) { self.state = initial.0 self.update = update self.subscriptions = subscriptions for command in initial.1 { command.execute(dispatcher: self) } } public func dispatch(action: Action) -> Void { queue.async { let result = self.update(self.state, action) self.state = result.0 DispatchQueue.main.async { for subscriber in self.observers.values { subscriber(self.state) } let subscribers = self.subscriptions(self.state) for each in self.inFlight.subtracting(subscribers) { each.cancel() self.inFlight.remove(each) } for each in subscribers.subtracting(self.inFlight) { self.inFlight.insert(each) each.launch(dispatcher: self) } for command in result.1 { command.execute(dispatcher: self) } } } } public func observe(observer: @escaping Observer) -> Unobserver { let id = UUID() observers[id] = { state in observer(state) } let dispose = { [weak self] () -> Void in self?.observers.removeValue(forKey: id) } observer(state) return Unobserver(method: dispose) } private let queue = DispatchQueue(label: "Apex") private let update: (State, Action) -> (State, [Command]) private let subscriptions: (State) -> Set<AnySubscription> private var state: State private var inFlight: Set<AnySubscription> = [] private var observers: [UUID: Observer] = [:] } public final class Unobserver { private var method: (() -> Void)? fileprivate init(method: @escaping () -> Void) { self.method = method } deinit { unobserve() } public func unobserve() { if let method = method { method() } method = nil } }
mit
4a684803849fa28f4a133df9b85e0daf
21.978947
158
0.677508
3.389752
false
false
false
false
jinSasaki/GroupSortData
GroupSortData/EnJaGroupIndex.swift
1
3131
// // EnJaGroupIndex.swift // GroupSortData // // Created by Jin Sasaki on 2017/01/29. // Copyright © 2017年 sasakky. All rights reserved. // import Foundation public enum EnJaGroupIndex: Int, GroupIndex { case a = 0, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z case aa, ka, sa, ta, na, ha, ma, ya, ra, wa case other public var name: String { switch self { case .a: return "A" case .b: return "B" case .c: return "C" case .d: return "D" case .e: return "E" case .f: return "F" case .g: return "G" case .h: return "H" case .i: return "I" case .j: return "J" case .k: return "K" case .l: return "L" case .m: return "M" case .n: return "N" case .o: return "O" case .p: return "P" case .q: return "Q" case .r: return "R" case .s: return "S" case .t: return "T" case .u: return "U" case .v: return "V" case .w: return "W" case .x: return "X" case .y: return "Y" case .z: return "Z" case .aa: return "あ" case .ka: return "か" case .sa: return "さ" case .ta: return "た" case .na: return "な" case .ha: return "は" case .ma: return "ま" case .ya: return "や" case .ra: return "ら" case .wa: return "わ" case .other: return "#" } } public var index: Int { return self.rawValue } public init?(index: Int) { self.init(rawValue: index) } public init(value: String) { if value.isEmpty { self = .other return } var string = String(value[value.startIndex]).uppercased() guard let c = string.unicodeScalars.first?.value else { self = .other return } if string >= "\u{0041}" && string <= "\u{005A}", let index = EnJaGroupIndex(index: Int(c) - 0x0041) { // A-Z self = index } else if string >= "\u{3041}" && string <= "\u{304A}" { self = .aa } else if string >= "\u{304B}" && string <= "\u{3054}" { self = .ka } else if string >= "\u{3055}" && string <= "\u{305E}" { self = .sa } else if string >= "\u{305F}" && string <= "\u{3069}" { self = .ta } else if string >= "\u{306A}" && string <= "\u{306E}" { self = .na } else if string >= "\u{306F}" && string <= "\u{307D}" { self = .ha } else if string >= "\u{307E}" && string <= "\u{3082}" { self = .ma } else if string >= "\u{3083}" && string <= "\u{3088}" { self = .ya } else if string >= "\u{3089}" && string <= "\u{308D}" { self = .ra } else if string >= "\u{308F}" && string <= "\u{3093}" { self = .wa } else { self = .other } } public static var count: Int { return EnJaGroupIndex.other.rawValue + 1 } }
mit
29bc86bcf80201bf5076cdce46fe381d
27.777778
109
0.453668
3.288889
false
false
false
false
kevinmlong/realm-cocoa
examples/ios/swift/Simple/AppDelegate.swift
9
2606
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import RealmSwift class Dog: Object { dynamic var name = "" dynamic var age = 0 } class Person: Object { dynamic var name = "" let dogs = List<Dog>() } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = UIViewController() window?.makeKeyAndVisible() NSFileManager.defaultManager().removeItemAtPath(Realm.defaultPath, error: nil) // Create a standalone object var mydog = Dog() // Set & read properties mydog.name = "Rex" mydog.age = 9 println("Name of dog: \(mydog.name)") // Realms are used to group data together let realm = Realm() // Create realm pointing to default file // Save your object realm.beginWrite() realm.add(mydog) realm.commitWrite() // Query var results = realm.objects(Dog).filter(NSPredicate(format:"name contains 'x'")) // Queries are chainable! var results2 = results.filter("age > 8") println("Number of dogs: \(results.count)") // Link objects var person = Person() person.name = "Tim" person.dogs.append(mydog) realm.write { realm.add(person) } // Multi-threading dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let otherRealm = Realm() var otherResults = otherRealm.objects(Dog).filter(NSPredicate(format:"name contains 'Rex'")) println("Number of dogs \(otherResults.count)") } return true } }
apache-2.0
269af439f01ff7179510b2b78ccb6c03
29.658824
128
0.607444
4.790441
false
false
false
false
pooi/SubwayAlerter
SubwayAlerter/AdditionFunction.swift
1
40972
// // AdditionFunction.swift // SubwayAlerter // // Created by 유태우 on 2016. 5. 5.. // Copyright © 2016년 유태우. All rights reserved. // import Foundation import UIKit import SystemConfiguration // 사용자 설정을 저장할 함수 class FavoriteVO { let config = NSUserDefaults.standardUserDefaults() } //네트워크 연결 확인 public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } } // 주요 색 저장 let settingColor = [ UIColor(red: 233/255, green: 97/255, blue: 97/255, alpha: 1.0), UIColor(red: 208/255, green: 84/255, blue: 84/255, alpha: 1.0), UIColor(red: 194/255, green: 75/255, blue: 75/255, alpha: 1.0), UIColor(red: 175/255, green: 64/255, blue: 64/255, alpha: 1.0), UIColor(red: 157/255, green: 55/255, blue: 55/255, alpha: 1.0), UIColor(red: 139/255, green: 46/255, blue: 46/255, alpha: 1.0) ] // 프로그램에서 필요한 주요 구조체 struct SubwayInfo { var navigate : Array<String> var navigateId : Array<String> let copyNavigate : Array<String> let copyNavigateId : Array<String> var navigateTm : Array<Int> var subwayId : String var time : Int let copyTime : Int var updn : String var startTime : Int var startSchedule : Array<Schedule> var startScheduleIndex : Int var expressYN : Bool var fastExit : String } // 최단 경로 정보를 저장하는 구조체 struct Root{ var statnFid : String = "" var statnTid : String = "" var shtTravelTm : Int = 0 var shtTransferCnt : Int = 0 var minTravelTm : Int = 0 var minTransferCnt : Int = 0 var shtStatnId : String = "" var shtStatnNm : String = "" var minStatnId : String = "" var minStatnNm : String = "" } struct Transfer { var name : String //환승역명 var Id : String //환승역 ID } // 지하철 역정보를 저장하는 구조체 struct SubwayList { var line : String //열차 호선 var stationNm : String //지하철 역명 var chosung : String //지하철 역명 초성 } // 시간표를 저장하는 구조체 struct Schedule { var arriveTime : Int //도착 시간 단위 : 초 var leftTime : Int //출발 시간 var directionNm : String //열차 방향 예 : 구파발행 var trainNo : String //열차 번호 var expressYN : String //급행여부 Yes or No } // 열차 도착 시간을 저장하는 구조체 struct trainTime{ var station : String var arriveTime : Int } // 가까운역을 저장하는 구조체 struct nealStation{ var statnNm : String = "" var subwayId : String = "" var subwayNm : String = "" var ord : Int = 0 } // 초성을 가져오기 위해 확장 함수 추가 extension String { var hangul: String { get { let hangle = [ // 초성, 중성, 종성 순 ["ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"], ["ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅘ","ㅙ","ㅚ","ㅛ","ㅜ","ㅝ","ㅞ","ㅟ","ㅠ","ㅡ","ㅢ","ㅣ"], ["","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ","ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"] ] return characters.reduce("") { result, char in if case let code = Int(String(char).unicodeScalars.reduce(0){$0.0 + $0.1.value}) - 44032 where code > -1 && code < 11172 { let cho = code / 21 / 28//, jung = code % (21 * 28) / 28, jong = code % 28; return result + hangle[0][cho]// + hangle[1][jung] + hangle[2][jong] } return result + String(char) } } } } // 해상도 최적화를 위해 extension UILabel { func setFontSize (sizeFont: CGFloat) { self.font = UIFont(name: self.font.fontName, size: sizeFont)! self.sizeToFit() } } // 해상도 최적화를 위해 extension UIButton { func setFontSize (size : CGFloat){ self.titleLabel?.font = UIFont(name: self.titleLabel!.font.fontName, size: size) } } // 해상도 최적화를 위해 func settingFontSize(mode : Int) -> CGFloat{ if(UIScreen.mainScreen().bounds.size.width == 320.0 && UIScreen.mainScreen().bounds.size.height == 480.0){ //3.5인치 switch mode{ case 0: return 14.0 //메인 버튼, 라벨 case 1: return 12.0 //부가 버튼 case 3: return 20 //마지막 페이지 맨위 레이블 constraint case 4: return 24.0 //마지막 페이지 맨위 레이블 case 5: return 64.0 //마지막 페이지 시간초 레이블 case 6: return 42 //하단바 높이 case 7: return 40 //첫페이지 타이틀 case 8: return 80 //셀 높이 case 9: return 42 //셀 높이2 case 10: return 38 //footer 높이 case 11: return -15 //메인페이지 기차 이미지 constraint case 12: return 73.5 * 4 //메인페이지 높이 constraint case 13: return 16 //메인페이지 역 이름 case 14: return 11 //메인페이지 서브 역 이름 default: return 1 } }else if(UIScreen.mainScreen().bounds.size.width == 320.0){ //4인치 switch mode{ case 0: return 15.0 //메인 버튼, 라벨 case 1: return 13.0 //부가 버튼 case 3: return 35 //마지막 페이지 맨위 레이블 constraint case 4: return 24 //마지막 페이지 맨위 레이블 case 5: return 64 //마지막 페이지 시간초 레이블 case 6: return 45 //하단바 높이 case 7: return 43 //첫페이지 타이틀 case 8: return 90 //셀 높이 case 9: return 43 //셀 높이2 case 10: return 39 //footer 높이 case 11: return -20 //메인페이지 기차 이미지 constraint case 12: return 73.5 * 5 //메인페이지 높이 constraint case 13: return 16 //메인페이지 역 이름 case 14: return 11 //메인페이지 서브 역 이름 default: return 1 } }else if(UIScreen.mainScreen().bounds.size.width == 375.0){ //4.7인치 switch mode{ case 0: return 16.0 //메인 버튼, 라벨 case 1: return 14.0 //부가 버튼 case 3: return 45 //마지막 페이지 맨위 레이블 constraint case 4: return 28 //마지막 페이지 맨위 레이블 case 5: return 72.0 //마지막 페이지 시간초 레이블 case 6: return 50 //하단바 높이 case 7: return 46 //첫페이지 타이틀 case 8: return 100 //셀 높이 case 9: return 44 //셀 높이2 case 10: return 40 //footer 높이 case 11: return -25 //메인페이지 기차 이미지 constraint case 12: return 86.5 * 5 //메인페이지 높이 constraint case 13: return 18 //메인페이지 역 이름 case 14: return 13 //메인페이지 서브 역 이름 default: return 1 } }else{ //5.5인치 switch mode{ case 0: return 17.0 //메인 버튼, 라벨 case 1: return 15.0 //부가 버튼 case 3: return 50 //마지막 페이지 맨위 레이블 constraint case 4: return 30 //마지막 페이지 맨위 레이블 case 5: return 76.0 //마지막 페이지 시간초 레이블 case 6: return 50 //하단바 높이 case 7: return 49 //첫페이지 타이틀 case 8: return 110 //셀 높이1 case 9: return 45 //셀 높이2 case 10: return 41 //footer 높이 case 11: return -30 //메인페이지 기차 이미지 constraint case 12: return 95 * 5 //메인페이지 높이 constraint case 13: return 18 //메인페이지 역 이름 case 14: return 13 //메인페이지 서브 역 이름 default: return 1 } } } // 정해진 범위의 문자를 반환하는 함수 func convertStartToFinishString(let Start start : Int, let Finish finish : Int, let string str : String) -> String{ var count : Int = 1 var extraText : String = "" for ce in str.characters{ if(count >= start && count <= finish){ //count++ extraText = extraText + String(ce) if(count == finish){break;} count+=1 }else{count+=1} } if(extraText == "1061"){extraText = "1063"} return extraText } //문자를 시간초로 변경 ex)15:30:30 -> 55830 func convertStringToSecond(set : String, Mode mode2 : Int) -> Int { var mode = mode2 var time : Int = 0 var count : Int = 0 var hour : String = "0" var min : String = "0" var sec : String = "0" for ce in set.characters{ if(ce == "-"){ mode = 0 } } switch mode{ case 1: for se in set.characters{ if(se == ":"){ count+=1 }else if(count<2){ hour = hour + String(se) count+=1 }else if(count<6){ min = min + String(se) count+=1 }else if(count<10){ sec = sec + String(se) count+=1 } } break; case 2: for se in set.characters{ if(Int(String(se)) != nil){ if(count == 0){ hour = hour + String(se) }else if(count == 1){ min = min + String(se) }else if(count == 2){ sec = sec + String(se) } }else if(se == "시"){ count+=1 }else if(se == "분"){ count+=1 }else if(se == "초"){ count+=1 } } break; case 3: hour = "0" for se in set.characters{ if(Int(String(se)) != nil){ if(count == 0){ min = min + String(se) }else if(count == 1){ sec = sec + String(se) } }else if(se == "분"){ count+=1 }else if(se == "초"){ count+=1 } } break; case 4: hour="" min="" for se in set.characters{ if(se == ":"){ count+=1 }else if(count<2){ hour = hour + String(se) count+=1 }else if(count<5){ min = min + String(se) count+=1 }else if(count>=5){ break; } } break; default: break; } if(hour == "0" && min == "0" && sec == "0"){ time = 0 }else if(hour == "" && min == "" && sec == ""){ time = 0 }else{ time = Int(hour)!*3600 + Int(min)!*60 + Int(sec)! } return time } // "군자, 어린이대공원"을 군자 어린이대공원 2개로 나눔 func removeComma(Name name : String) -> (String, String){ var start : String = "" var finish : String = "" var count : Int = 0 for ce in name.characters{ if(ce == ","){ count += 1 }else{ if(count == 0){ start = start + String(ce) }else{ finish = finish + String(ce) } } } return (start, finish) } // "ㅁ역 -> ㅁ역"을 만들기 위한 함수 func convertTitle(Title name : String) -> String{ var start : String = "" var finish : String = "" var count : Int = 0 for ce in name.characters{ if(ce == ","){ count += 1 }else{ if(count == 0){ start = start + String(ce) }else{ finish = finish + String(ce) } } } return start + "역 -> " + finish + "역" } // 만약"군자역"을 인자로 받을 경우 '역'을 지우는 함수 func removeString(Name name : String) -> String { var stationYN : Bool = false var count : Int = 0 var count2 : Int = 0 var tempS : String = "" for _ in name.characters{ count += 1 } for ce in name.characters{ count2+=1 if(count2 == count){ if(ce == "역"){ stationYN = true } } } if(stationYN == true){ count2 = 0 if(stationYN == true){ for ce in name.characters{ count2+=1 if(count2<count){ tempS = tempS + String(ce) } } } return tempS }else{ return name } } //시간초를 문자로 변경 ex)55830 -> 15시 30분 30초 func convertSecondToString(let set : Int, let Mode mode : Int) -> String{ var timeText : String = "" var hour : Int = 0 var min : Int = 0 var sec : Int = 0 hour = set/3600 min = (set - (hour*3600))/60 sec = set - hour*3600 - min*60 switch mode{ case 1: if(sec == 0){ timeText = String(hour) + "시 " + String(min) + "분 " + "00초" }else { timeText = String(hour) + "시 " + String(min) + "분 " + String(sec) + "초" } break; case 2: if(sec >= 30){ if(min + 1 == 60){hour = hour + 1; min = -1} timeText = String(hour) + "시 " + String(min+1) + "분" } else{ timeText = String(hour) + "시 " + String(min) + "분" } break; case 3: if(hour == 0){ timeText = String(min) + "분" }else{ timeText = String(hour) + "시간 " + String(min) + "분" } break; case 4: min = hour * 60 + min timeText = String(min) + "분 " + String(sec) + "초" break; case 5: min = set/60 timeText = String(min) break; default: break; } return timeText } // 현재시간을 시간초로 반환하는 함수 func returnCurrentTime() -> Int { var temp : Int = 0 let now = NSDate() let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "ko_KR") // 로케일 설정 dateFormatter.dateFormat = "HH" if(Int(dateFormatter.stringFromDate(now)) == 0){ temp = 24 }else if(Int(dateFormatter.stringFromDate(now)) == 1){ temp = 25 } dateFormatter.dateFormat = "HH:mm:ss" // 날짜 형식 설정 let mainCurrentTime = convertStringToSecond(dateFormatter.stringFromDate(now), Mode: 1) + (temp * 3600) return mainCurrentTime } // 평일 : 1, 토요일 : 2, 공휴일/일요일 : 3 반환 func weekTag() -> String { // 2016년 공휴일 수동 선언 let holiday : Array<String> = [ "01-01", "03-01", "05-05", "05-14", "06-06", "08-15", "10-03", "10-09", "12-25", "02-08",//2016 설날, 추석 "02-09", "02-10", "09-14", "09-15", "09-16" ] //(평일:1, 토요일:2, 휴일/일요일:3) let now = NSDate() let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "ko_KR") // 로케일 설정 dateFormatter.dateFormat = "MM-dd" let checkHoliday : String = dateFormatter.stringFromDate(now) var check : Bool = false for ce in holiday{ if(checkHoliday == ce){ check = true } } if(check == true){ return "3" }else{ dateFormatter.dateFormat = "EEE" // 날짜 형식 설정 let currentTime : String = dateFormatter.stringFromDate(now) if(currentTime == "일"){ return "3" }else if(currentTime == "토"){ return "2" }else{ return "1" } } } // apiData를 가져올때 네트워크가 유실되는지 확인하며 가져옴 func checkNetworkApiData(ApiURI apiURI : NSURL) -> NSData?{ //let apidata : NSData? = NSData(contentsOfURL: apiURI)! var data : NSData? while(true){ do{ if(Reachability.isConnectedToNetwork() == true){ data = try NSData(contentsOfURL: apiURI, options: []) break; }else{ data = nil } }catch{ data = nil } } return data } // 전체 경로의 모든 시간정보를 info구조체에 저장하는 함수 func setAllTimeToInfo(Info info2 : Array<SubwayInfo>, Index mainIndex : Int) -> Array<SubwayInfo>{ var info = info2 info[mainIndex] = setInfoToTrainNo(Info: info[mainIndex]) var fTime : Int = info[mainIndex].navigateTm[info[mainIndex].navigateTm.count-1] let fvo = FavoriteVO() var addTime : Int = fvo.config.objectForKey("addTransTime") as! Int switch addTime{ case 0: addTime = 30 break; case 1: addTime = 60 break; case 2: addTime = 120 break; case 3: addTime = 180 break; default: break; } for i in mainIndex+1..<info.count{ fTime = fTime + addTime var indexTemp : Int = 0 for ce in info[i].startSchedule{ if(ce.arriveTime >= fTime){ break; }else{indexTemp += 1} } if(indexTemp == info[i].startSchedule.count){ info[i].navigateTm.removeAll() info[i].expressYN = false //indexTemp-- }else{ info[i].startTime = info[i].startSchedule[indexTemp].arriveTime info[i].startScheduleIndex = indexTemp info[i] = setInfoToTrainNo(Info: info[i]) //info[i].navigateTm[0] = info[i].startTime fTime = info[i].navigateTm[info[i].navigateTm.count-1] } if(fTime == 0){ break; } } return info } // 최단 경로를 mode에 맞춰 반환함(0 : 추천, 1 : 최소시간, 2 : 최소환승) func returnRootApi(StartNm start2 : String, FinishNm finish2 : String, Mode mode2 : Int) -> (Root, Int){ var start = start2 var finish = finish2 var mode = mode2 var rootlist : Array<Root> = [] var mainRow : Root? ////checkNetworkAvailable() let baseUrl = "http://swopenapi.seoul.go.kr/api/subway/\(KEY)/json/shortestRoute/0/100/" let text : String = start + "/" + finish //추후 수정 요망** let escapedText = text.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let reuqestUrl : String = baseUrl + escapedText! let apiURI = NSURL(string: reuqestUrl) let apiURL : NSURL = apiURI! let apidata : NSData? = checkNetworkApiData(ApiURI: apiURL)//NSData(contentsOfURL: apiURL) do{ //checkNetworkAvailable() let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as! NSDictionary let sub = apiDictionary["shortestRouteList"] as! NSArray //row["statnFid"] as! String for row in sub{ rootlist.append( Root( statnFid: row["statnFid"] as! String, statnTid: row["statnTid"] as! String, shtTravelTm: Int(row["shtTravelTm"] as! String)! * 60, shtTransferCnt: Int(row["shtTransferCnt"] as! String)!, minTravelTm: Int(row["minTravelTm"] as! String)! * 60, minTransferCnt: Int(row["minTransferCnt"] as! String)!, shtStatnId: row["shtStatnId"] as! String, shtStatnNm: row["shtStatnNm"] as! String, minStatnId: row["minStatnId"] as! String, minStatnNm: row["minStatnNm"] as! String ) ) } var shtTime : Array<Int> = []//최소시간 var minTime : Array<Int> = []//최소경로 for i in 0..<rootlist.count{ shtTime.append(rootlist[i].shtTravelTm + rootlist[i].shtTransferCnt * 60) minTime.append(rootlist[i].minTravelTm + rootlist[i].minTransferCnt * 60) } switch mode{ case 0: var sht : Int = shtTime[0] var min : Int = minTime[0] var indexSht : Int = 0 var indexMin : Int = 0 for cert in shtTime{ if(cert < sht){ sht = cert indexSht = shtTime.indexOf(sht)! } } for cert in minTime{ if(cert < min){ min = cert indexMin = minTime.indexOf(min)! } } if(sht <= min){ mode = 1 mainRow = rootlist[indexSht] }else{ mode = 2 mainRow = rootlist[indexMin] } break; case 1://최소시간 기준 var sht : Int = shtTime[0] var indexSht : Int = 0 for cert in shtTime{ if(cert < sht){ sht = cert indexSht = shtTime.indexOf(sht)! } } mode = 1 mainRow = rootlist[indexSht] break; case 2://최소환승 기준 var min : Int = minTime[0] var indexMin : Int = 0 for cert in minTime{ if(cert < min){ min = cert indexMin = minTime.indexOf(min)! } } mode = 2 mainRow = rootlist[indexMin] break; default: break; } }catch{ } if(mainRow == nil){ let rowTemp = Root() return (rowTemp, mode) }else{ return (mainRow!, mode) } } //상행인지 하행인지 체크하기 위한 함수 func checkUpOrDown(StartSTNm startSTNm : String, StartSTId startSTId : String, NextSTNm nextSTNm : String) -> String{ var UpDn : String = "" ////checkNetworkAvailable() let baseUrl = "http://swopenapi.seoul.go.kr/api/subway/\(KEY)/json/stationInfo/0/10/\(startSTNm)" let escapedText = baseUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let apiURI = NSURL(string: escapedText!) let apidata : NSData? = checkNetworkApiData(ApiURI: apiURI!)//NSData(contentsOfURL: apiURI!) do{ //checkNetworkAvailable() let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as! NSDictionary let sub = apiDictionary["stationList"] as! NSArray for row in sub{ if(row["statnId"] as! String == startSTId || convertStartToFinishString(Start: 1, Finish: 4, string: row["statnId"] as! String) == startSTId){ if(row["statnFnm"] as! String == nextSTNm){ if(row["subwayNm"] as! String == "2호선" || row["subwayNm"] as! String == "9호선"){ UpDn = "0" }else{ UpDn = "1" } }else{ if(row["subwayNm"] as! String == "2호선" || row["subwayNm"] as! String == "9호선"){ UpDn = "1" }else{ UpDn = "0" } } } } }catch{ } return UpDn } // info구조체의 전체적인 정보를 저장하는 함수(시간표, 급행여부 등) func parsingRoot(minStatNm statNm : Array<String>, minStatId statId : Array<String>) -> Array<SubwayInfo>{ var info : Array<SubwayInfo> = [] var timeArray : Array<Int> = [] var startschedule : Array<Array<Schedule>> = [] //var finishschedule : Array<Array<Schedule>> = [] var subwayIdArray : Array<String> = [] var updnArray : Array<String> = [] var mainNmArray : Array<Array<String>> = [] var mainIdArray : Array<Array<String>> = [] var tempArray : Array<String> = [] //var express : Array<Bool> = [] var subwayIdTemp : String = convertStartToFinishString(Start: 1, Finish: 4, string: statNm[0]) for ce in statId{ let temp = convertStartToFinishString(Start: 1, Finish: 4, string: ce) if(temp != subwayIdTemp){ subwayIdTemp = temp tempArray.append(ce) mainIdArray.append(tempArray) tempArray.removeAll() tempArray.append(ce) }else{ tempArray.append(ce) } } mainIdArray.append(tempArray) tempArray.removeAll() mainIdArray.removeAtIndex(0) for ce in mainIdArray{ for te in ce{ tempArray.append(statNm[statId.indexOf(te)!]) } mainNmArray.append(tempArray) tempArray.removeAll() } let count = mainIdArray.count let que = dispatch_queue_create("parsingRoot", DISPATCH_QUEUE_CONCURRENT) var queueFinish = false for _ in 0..<count{ subwayIdArray.append("0") updnArray.append("0") let temp : Array<Schedule> = [] startschedule.append(temp) timeArray.append(0) } for te in 0..<count{ dispatch_async(que){ let ce = te var subwayIdTemp = convertStartToFinishString(Start: 1, Finish: 4, string: mainIdArray[ce][0]) if(subwayIdTemp == "1061"){subwayIdTemp = "1063"} subwayIdArray[ce] = subwayIdTemp var updn = checkUpOrDown(StartSTNm: mainNmArray[ce][0], StartSTId: subwayIdTemp, NextSTNm: mainNmArray[ce][1]) if(subwayIdTemp == "1002"){ if(mainNmArray[ce].indexOf("용답") != nil || mainNmArray[ce].indexOf("신답") != nil || mainNmArray[ce].indexOf("용두") != nil){ if(updn == "1"){updn = "0"} else{updn = "1"} } } updnArray[ce] = updn //updnArray.append(updn) let checkExpress : Bool = setExpress(SubwayId: subwayIdTemp, Navigate: mainNmArray[ce]) //express.append(checkExpress) //시작역 var scheduleTemp = setTranferTimeBySubwayId2(StationNm: mainNmArray[ce][0], SubwayId: subwayIdTemp, UpDnLine: updn, ExpressCheck: checkExpress) startschedule[ce] = scheduleTemp let timeTemp = returnRootApi(StartNm: mainNmArray[ce][0], FinishNm: mainNmArray[ce][mainNmArray[ce].count - 1], Mode: 0).0.shtTravelTm timeArray[ce] = timeTemp } } dispatch_barrier_async(que){ for ce in 0..<count{ info.append(SubwayInfo(navigate: mainNmArray[ce], navigateId: mainIdArray[ce], copyNavigate: mainNmArray[ce], copyNavigateId: mainIdArray[ce], navigateTm: [], subwayId: subwayIdArray[ce], time: timeArray[ce], copyTime: timeArray[ce], updn: updnArray[ce], startTime: 0, startSchedule: startschedule[ce], startScheduleIndex: 0,/* finishSchedule: finishschedule[ce],*/ expressYN: false, fastExit : "")) } //여기서 환승출구 추가 for i in 0..<info.count{ if(i+1 == info.count){ info[i].fastExit = "" }else{ let firstNm : String = info[i].navigate[info[i].navigate.count-2] let secondNm : String = info[i+1].navigate[1] let subwayId : String = info[i+1].subwayId let firstFastExit = returnFastExit(SubwayId: info[i].subwayId) let index : Int? = firstFastExit.indexOf({ var check : Bool = false if($0.toLine == ""){ check = ($0.FirstNm == firstNm && $0.SecondNm == secondNm) }else{ check = $0.FirstNm == firstNm && $0.SecondNm == secondNm && $0.toLine == subwayId } return check }) if(index != nil){ if(firstFastExit[index!].Exit == "20"){ info[i].fastExit = "모든문" }else{ info[i].fastExit = firstFastExit[index!].Exit } }else{ info[i].fastExit = "" } } } queueFinish = true } while(queueFinish == false){ } return info } // 시간표를 불러온 뒤 저장하는 함수 func setTranferTimeBySubwayId2(StationNm stationNm : String, SubwayId subwayId : String, UpDnLine updnLine2 : String, ExpressCheck express : Bool) -> Array<Schedule> { var updnLine = updnLine2 //if(subwayId == "1061"){subwayId = "1063"} //var checkData : Bool = false //print(subwayId) //var totalCount : Int = 1 //var realCount : Int = 0 var tranSchdule : Array<Schedule> = [] let StationList = returnLineList(SubwayId: subwayId) let StationId = StationList[StationList.indexOf({$0.name == stationNm})!].code if(updnLine == "0"){updnLine = "2"} ////checkNetworkAvailable() let baseUrl = "http://openapi.seoul.go.kr:8088/\(KEY)/json/SearchSTNTimeTableByFRCodeService/1/1000/\(StationId)/\(weekTag())/\(updnLine)/" let escapedText = baseUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let apiURI = NSURL(string: escapedText!) let apidata : NSData? = checkNetworkApiData(ApiURI: apiURI!)//NSData(contentsOfURL: apiURI!) do{ //checkNetworkAvailable() let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as! NSDictionary if(apiDictionary["SearchSTNTimeTableByFRCodeService"] as? NSDictionary != nil){ let sub = apiDictionary["SearchSTNTimeTableByFRCodeService"] as! NSDictionary let sub2 = sub["row"] as! NSArray for row in sub2{ if(express == true){ if(row["ARRIVETIME"] as! String == "00:00:00"){ tranSchdule.append(Schedule.init( arriveTime: convertStringToSecond(row["LEFTTIME"] as! String, Mode: 1)-60,//-30, leftTime: convertStringToSecond(row["LEFTTIME"] as! String, Mode: 1), directionNm: row["SUBWAYENAME"] as! String, trainNo:row["TRAIN_NO"] as! String, expressYN: row["EXPRESS_YN"] as! String )) }else if(row["LEFTTIME"] as! String == "99:99:99"){ }else{ tranSchdule.append(Schedule.init( arriveTime: convertStringToSecond(row["ARRIVETIME"] as! String, Mode: 1),//-30, leftTime: convertStringToSecond(row["LEFTTIME"] as! String, Mode: 1), directionNm: row["SUBWAYENAME"] as! String, trainNo:row["TRAIN_NO"] as! String, expressYN: row["EXPRESS_YN"] as! String )) } }else{ if(row["ARRIVETIME"] as! String == "00:00:00"){ if(row["EXPRESS_YN"] as! String == ""){ tranSchdule.append(Schedule.init( arriveTime: convertStringToSecond(row["LEFTTIME"] as! String, Mode: 1)-60,//-30, leftTime: convertStringToSecond(row["LEFTTIME"] as! String, Mode: 1), directionNm: row["SUBWAYENAME"] as! String, trainNo:row["TRAIN_NO"] as! String, expressYN: row["EXPRESS_YN"] as! String )) } }else if(row["LEFTTIME"] as! String == "99:99:99"){ }else{ if(row["EXPRESS_YN"] as! String == ""){ tranSchdule.append(Schedule.init( arriveTime: convertStringToSecond(row["ARRIVETIME"] as! String, Mode: 1),//-30, leftTime: convertStringToSecond(row["LEFTTIME"] as! String, Mode: 1), directionNm: row["SUBWAYENAME"] as! String, trainNo:row["TRAIN_NO"] as! String, expressYN: row["EXPRESS_YN"] as! String )) } } } } }else{ } }catch{ } tranSchdule = tranSchdule.sort({$0.arriveTime < $1.arriveTime}) //print(tranSchdule) return tranSchdule } // 열차번호를 통해 각역별 도착시간을 설정하는 함수 func setInfoToTrainNo(Info info2 : SubwayInfo) -> SubwayInfo{ var info = info2 let index : Int = info.startSchedule.indexOf({$0.arriveTime == info.startTime})! info.navigateTm.removeAll() info.expressYN = false let trainNo = info.startSchedule[index].trainNo if(info.startSchedule[index].expressYN == "Y"){ info.expressYN = true info = setNavigateToExpress(Info: info, SubwayId: info.subwayId) }else{ info.navigate = info.copyNavigate info.navigateId = info.copyNavigateId info.navigateTm.removeAll() info.time = info.copyTime } var trainTemp : Array<trainTime> = returnTrainSchedule(TrainNo: trainNo, UpDn: info.updn) var list : Array<Int> = [] for _ in 0..<info.navigate.count{ list.append(0) } if(trainTemp.indexOf({$0.arriveTime == "00:00:00"}) != nil){ trainTemp.removeAtIndex(trainTemp.indexOf({$0.arriveTime == "00:00:00"})!) } for row in trainTemp{ if(info.navigate.indexOf(row.station) != nil){ let index : Int = info.navigate.indexOf(row.station)! list[index] = row.arriveTime } } list[0] = info.startTime var count : Int = -1 for i in 1..<list.count{ //count++ if(list[i-1] > list[i]){ count = i break; } } if(count >= 0){ trainTemp.removeAll() let index : Int = count let previousTime : Int = list[index-1] let schedule = setTranferTimeBySubwayId2(StationNm: info.navigate[index], SubwayId: info.subwayId, UpDnLine: info.updn, ExpressCheck: info.expressYN) for i in 0..<schedule.count{ if(schedule[i].arriveTime > previousTime){ trainTemp = returnTrainSchedule(TrainNo: schedule[i].trainNo, UpDn: info.updn) break; } } for i in index..<list.endIndex{ let index2 : Int? = trainTemp.indexOf({$0.station == info.navigate[i]}) if(index2 != nil){ list[i] = trainTemp[index2!].arriveTime } } } info.navigateTm = list if(info.expressYN == true){ info.time = info.navigateTm[info.navigateTm.count-1] - info.startTime } return info } // 열차 번호를 통해 그 열차의 운행정보를 반환함 func returnTrainSchedule(TrainNo trainNo : String, UpDn updn2 : String) -> Array<trainTime>{ var updn = updn2 var trainTemp : Array<trainTime> = [] if(updn == "0"){updn = "2"} //checkNetworkAvailable() let baseUrl = "http://openapi.seoul.go.kr:8088/\(KEY)/json/SearchViaSTNArrivalTimeByTrainService/1/1000/\(trainNo)/\(weekTag())/\(updn)/" let escapedText = baseUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let apiURI = NSURL(string: escapedText!) let apidata : NSData? = checkNetworkApiData(ApiURI: apiURI!)//NSData(contentsOfURL: apiURI!) do{ //checkNetworkAvailable() let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as! NSDictionary let sub = apiDictionary["SearchViaSTNArrivalTimeByTrainService"] as! NSDictionary let sub2 = sub["row"] as! NSArray for row in sub2{ trainTemp.append(trainTime(station: row["STATION_NM"] as! String, arriveTime: convertStringToSecond(row["ARRIVETIME"] as! String, Mode: 1) )) } trainTemp = trainTemp.sort({$0.arriveTime < $1.arriveTime}) }catch{ } return trainTemp } // 해상도 최적화를 위한 함수 extension UIView { func setWidth(width:CGFloat) { var frame:CGRect = self.frame frame.size.width = width self.frame = frame } func setHeight(height:CGFloat) { var frame:CGRect = self.frame frame.size.height = height self.frame = frame } }
bsd-3-clause
bd6d17dab7b676dbc76d4955d1f2094b
26.408481
411
0.480752
3.752588
false
false
false
false
cnharris10/CHRadarGraph
Example/Tests/CHSectorDataCollectionSpec.swift
1
1258
import Quick import Nimble import CHRadarGraph class CHSectorDataCollectionSpec: QuickSpec { override func spec() { describe("CHSectorDataCollection") { var height1: CGFloat! var label1: String! var height2: CGFloat! var label2: String! var sectorData: [CHSectorData]! var sdc: CHSectorDataCollection<CHSectorData>! beforeEach { height1 = 1.0 label1 = "label1" height2 = 2.0 label2 = "label2" sectorData = [ CHSectorData(height1, label1), CHSectorData(height2, label2) ] sdc = CHSectorDataCollection(sectorData) } context("#init") { it("will initialize with text") { let items = sdc.data expect(items[0].height) == height1 expect(items[0].label) == label1 expect(items[1].height) == height2 expect(items[1].label) == label2 expect(items.endIndex) == sdc.count } } } } }
mit
d326c388a1d3a1964b3aab19a58a12df
27.590909
58
0.45787
4.67658
false
false
false
false
lemberg/connfa-ios
Connfa/Classes/Events/Program List/ProgramListViewController.swift
1
3380
// // ProgramListViewController.swift // Connfa // // Created by Volodymyr Hyrka on 10/26/17. // Copyright (c) 2017 Lemberg Solution. All rights reserved. // import UIKit import SwiftDate class ProgramListViewController: EventListViewController { //MARK: - Public properties var filter: ProgramListFilter = ProgramListFilter() override var emptyView: UIView { return super.emptyEventsView.forEmptyScreen(.events) } //MARK: - Private properties @IBOutlet private weak var filterInfo: UILabel! @IBOutlet private weak var filterInfoHeight: NSLayoutConstraint! private let filterInfoDefaultHeight: CGFloat = 67.0 private let userStorage = StorageDataSaver<ProgramListFilter>() //MARK: - Public functions override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = NavigationTitleLabel(withText: Constants.Title.program) } override func setUI() { navigationItem.rightBarButtonItem?.isEnabled = true super.setUI() } override func setEmptyUI() { navigationItem.rightBarButtonItem?.isEnabled = false super.setEmptyUI() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let destination = segue.destination as? ProgramListFilterViewController { destination.filter = self.filter destination.delegate = self } } //MARK: - Actions @IBAction func onFilter() { performSegue(withIdentifier: SegueIdentifier.presentProgramListFilter.rawValue, sender: nil) } @IBAction func onResetFilter() { handleFilterReset() } override func receiveEvents() { super.receiveEvents() let newFilter = createFilter(from: super.events) if let savedFilter = userStorage.savedObject { savedFilter.merge(with: newFilter) userStorage.save(savedFilter) filter = savedFilter } else { filter = newFilter } filterChanged() } //MARK: - private private func createFilter(from events: [EventModel]) -> ProgramListFilter { let types = Array(Set(events.compactMap { $0.type })).filter{ !$0.isEmpty } let experienceLevels = Set(events.compactMap({ $0.experienceLevel })).sorted() let levels = Array(experienceLevels.compactMap { ExperienceLevel(rawValue: $0)?.description }).filter{ !$0.isEmpty } let tracks = Array(Set(events.compactMap { $0.track })).filter{ !$0.isEmpty } return ProgramListFilter(types: types, levels: levels, tracks: tracks) } private func filterChanged() { self.fullList = transformer.transform(filter.apply(for: super.events)) let info = filter.isEmpty ? "" : filter.filterInfo let height: CGFloat = filter.isEmpty ? 0.0 : filterInfoDefaultHeight reload(filterSummary: info, filterHeight: height) } private func reload(filterSummary: String?, filterHeight: CGFloat) { filterInfoHeight.constant = filterHeight additionalHeight = filterHeight filterInfo.text = filterSummary reload() } private func handleFilterReset() { userStorage.clean() filter.reset() filterChanged() } } extension ProgramListViewController: ProgramListFilterDelegate { func filter(_ controller: ProgramListFilterViewController, didChange filter: ProgramListFilter) { self.filter = filter userStorage.save(filter) self.filterChanged() } }
apache-2.0
41712b42675f1cc3ebcc7f860453256b
29.45045
120
0.713905
4.424084
false
false
false
false
apple/swift-nio
IntegrationTests/tests_04_performance/test_01_resources/test_decode_1000_ws_frames.swift
1
1412
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOEmbedded import NIOWebSocket class UnboxingChannelHandler: ChannelInboundHandler { typealias InboundIn = WebSocketFrame typealias InboundOut = WebSocketFrame func channelRead(context: ChannelHandlerContext, data: NIOAny) { let data = self.unwrapInboundIn(data) context.fireChannelRead(self.wrapInboundOut(data)) } } func run(identifier: String) { let channel = EmbeddedChannel() try! channel.pipeline.addHandler(ByteToMessageHandler(WebSocketFrameDecoder())).wait() try! channel.pipeline.addHandler(UnboxingChannelHandler()).wait() let data = ByteBuffer(bytes: [0x81, 0x00]) // empty websocket measure(identifier: identifier) { for _ in 0..<1000 { try! channel.writeInbound(data) let _: WebSocketFrame? = try! channel.readInbound() } return 1000 } _ = try! channel.finish() }
apache-2.0
4414150726672ffa950a3fc401bd74be
31.090909
90
0.624646
4.919861
false
false
false
false
kylef/CLIKit
Sources/Commander/ArgumentParser.swift
2
7189
private enum Arg : CustomStringConvertible, Equatable { /// A positional argument case argument(String) /// A boolean like option, `--version`, `--help`, `--no-clean`. case option(String) /// A flag case flag([Character]) var description:String { switch self { case .argument(let value): return value case .option(let key): return "--\(key)" case .flag(let flags): return "-\(String(flags))" } } var type:String { switch self { case .argument: return "argument" case .option: return "option" case .flag: return "flag" } } } private func == (lhs: Arg, rhs: Arg) -> Bool { return lhs.description == rhs.description } public struct ArgumentParserError : Error, Equatable, CustomStringConvertible { public let description: String public init(_ description: String) { self.description = description } } public func ==(lhs: ArgumentParserError, rhs: ArgumentParserError) -> Bool { return lhs.description == rhs.description } public final class ArgumentParser : ArgumentConvertible, CustomStringConvertible { fileprivate var arguments:[Arg] public typealias Option = String public typealias Flag = Character /// Initialises the ArgumentParser with an array of arguments public init(arguments: [String]) { let splitArguments = arguments.split(maxSplits: 1, omittingEmptySubsequences: false) { $0 == "--" } let unfixedArguments: [String] let fixedArguments: [String] if splitArguments.count == 2, let prefix = splitArguments.first, let suffix = splitArguments.last { unfixedArguments = Array(prefix) fixedArguments = Array(suffix) } else { unfixedArguments = arguments fixedArguments = [] } self.arguments = unfixedArguments.map { argument in if argument.first == "-" { let flags = argument[argument.index(after: argument.startIndex)..<argument.endIndex] if flags.first == "-" { let option = flags[flags.index(after: flags.startIndex)..<flags.endIndex] return .option(String(option)) } return .flag(Array(String(flags))) } return .argument(argument) } self.arguments.append(contentsOf: fixedArguments.map { .argument($0) }) } public init(parser: ArgumentParser) throws { arguments = parser.arguments } public var description:String { return arguments.map { $0.description }.joined(separator: " ") } public var isEmpty: Bool { return arguments.first { $0 != .argument("") } == nil } public var remainder:[String] { return arguments.map { $0.description } } /// Returns the first positional argument in the remaining arguments. /// This will remove the argument from the remaining arguments. public func shift() -> String? { for (index, argument) in arguments.enumerated() { switch argument { case .argument(let value): arguments.remove(at: index) return value default: continue } } return nil } /// Returns the value for an option (--name Kyle, --name=Kyle) public func shiftValue(for name: Option) throws -> String? { return try shiftValues(for: name)?.first } /// Returns the value for an option (--name Kyle, --name=Kyle) public func shiftValues(for name: Option, count: Int = 1) throws -> [String]? { var index = 0 var hasOption = false for argument in arguments { switch argument { case .option(let option): if option == name { hasOption = true break } fallthrough default: index += 1 } if hasOption { break } } if hasOption { arguments.remove(at: index) // Pop option return try (0..<count).map { i in if arguments.count > index { let argument = arguments.remove(at: index) switch argument { case .argument(let value): return value default: throw ArgumentParserError("Unexpected \(argument.type) `\(argument)` as a value for `--\(name)`") } } throw ArgumentError.missingValue(argument: "--\(name)") } } return nil } /// Returns whether an option was specified in the arguments public func hasOption(_ name: Option) -> Bool { var index = 0 for argument in arguments { switch argument { case .option(let option): if option == name { arguments.remove(at: index) return true } default: break } index += 1 } return false } /// Returns whether a flag was specified in the arguments public func hasFlag(_ flag: Flag) -> Bool { var index = 0 for argument in arguments { switch argument { case .flag(let option): var options = option if options.contains(flag) { options.removeAll(where: { $0 == flag }) arguments.remove(at: index) if !options.isEmpty { arguments.insert(.flag(options), at: index) } return true } default: break } index += 1 } return false } /// Returns the value for a flag (-n Kyle) public func shiftValue(for flag: Flag) throws -> String? { return try shiftValues(for: flag)?.first } /// Returns the value for a flag (-n Kyle) public func shiftValues(for flag: Flag, count: Int = 1) throws -> [String]? { var index = 0 var hasFlag = false for argument in arguments { switch argument { case .flag(let flags): if flags.contains(flag) { hasFlag = true break } fallthrough default: index += 1 } if hasFlag { break } } if hasFlag { arguments.remove(at: index) return try (0..<count).map { i in if arguments.count > index { let argument = arguments.remove(at: index) switch argument { case .argument(let value): return value default: throw ArgumentParserError("Unexpected \(argument.type) `\(argument)` as a value for `-\(flag)`") } } throw ArgumentError.missingValue(argument: "-\(flag)") } } return nil } /// Returns the value for an option (--name Kyle, --name=Kyle) or flag (-n Kyle) public func shiftValue(for name: Option, or flag: Flag?) throws -> String? { if let value = try shiftValue(for: name) { return value } else if let flag = flag, let value = try shiftValue(for: flag) { return value } return nil } /// Returns the values for an option (--name Kyle, --name=Kyle) or flag (-n Kyle) public func shiftValues(for name: Option, or flag: Flag?, count: Int = 1) throws -> [String]? { if let value = try shiftValues(for: name, count: count) { return value } else if let flag = flag, let value = try shiftValues(for: flag, count: count) { return value } return nil } /// Clears all arguments public func clear() { arguments = [] } }
bsd-3-clause
01ec1f041a76c8918b391fc69160923e
23.961806
109
0.597441
4.346433
false
false
false
false
apollostack/apollo-android
composite/samples/multiplatform/kmp-ios-app/kmp-ios-app/RepositoryManager.swift
1
1722
// // RepositoryManager.swift // kmp-ios-app // // Created by Ellen Shapiro on 4/26/20. // import Foundation import kmp_lib_sample import SwiftUI class RepositoryManager: ObservableObject { private let repository = ApolloiOSRepositoryKt.create() @Published var repos: [RepositoryFragmentImpl] = [] @Published var repoDetails: [String: RepositoryDetail] = [:] @Published var commits: [String: [GithubRepositoryCommitsQueryDataViewerRepositoryRefTargetCommitTarget.HistoryEdgesNode]] = [:] func fetch() { self.repository.fetchRepositories { [weak self] repos in self?.repos = repos as [RepositoryFragmentImpl] } } func fetchDetails(for repo: RepositoryFragment) { self.repository.fetchRepositoryDetail(repositoryName: repo.name) { [weak self] detail in if let detail = detail { self?.repoDetails[repo.name] = detail } } } func fetchCommits(for repo: RepositoryFragment) { // NOTE: This comes in as `[Any]` due to some some issues with representing // optional types in a generic array in Objective-C from K/N. The actual // type coming back here is `GithubRepositoryCommitsQuery.Edge`, and the // `Node` it contains is where actual information about the commit lives. self.repository.fetchCommits(repositoryName: repo.name) { [weak self] commits in let filteredCommits = commits .compactMap { $0 as? GithubRepositoryCommitsQueryDataViewerRepositoryRefTargetCommitTarget.HistoryEdges } .compactMap { $0.node } self?.commits[repo.name] = filteredCommits } } }
mit
bccb0b4052e70082a27dcdc510da7c7d
36.434783
132
0.660279
4.579787
false
false
false
false
allenlinli/Wildlife-League
Wildlife League/Set.swift
1
1919
// // Set.swift // Wildlife League // // Created by allenlin on 7/8/14. // Copyright (c) 2014 Raccoonism. All rights reserved. // import Foundation class Set<T : Hashable> : SequenceType, Printable { var dictionary : Dictionary<T,Bool> func addElement(obj:T){ dictionary[obj] = true } func removeElement(obj:T){ dictionary[obj] = nil } func allElements () -> [T] { return Array(dictionary.keys) } func count () -> Int { return self.allElements().count } init(){ dictionary = Dictionary<T,Bool>() } func generate () -> IndexingGenerator<Array<T>> { return allElements().generate() } func containsObject (obj:T) -> Bool{ return dictionary[obj] == true } func union (set :Set) { for key in set.dictionary.keys { self.dictionary[key] = true } } func intersect (set :Set) { for key in self.dictionary.keys{ if (set.dictionary[key]==nil){ self.dictionary[key] = nil } else{ self.dictionary[key] = true } } } func isIntersected (set :Set) -> Bool { var selfCopy = self.copy() selfCopy.intersect(set) return selfCopy.dictionary.count>0 } subscript (index :Int) -> T? { get{ return allElements()[index] } } var description :String { get{ var desc = String() for key in dictionary.keys { desc += "\(key), \n" } return desc } } func copy() -> Set<T>{ var set = Set<T>() set.dictionary = Dictionary() for key in self.dictionary.keys { set.dictionary[key] = true } return set } }
apache-2.0
94f611a14c7b67351715f583457000ec
20.098901
55
0.491923
4.217582
false
false
false
false
North-American-Signs/DKImagePickerController
Sources/Extensions/DKImageExtensionPhotoCropper.swift
1
2207
// // DKImageExtensionPhotoCropper.swift // DKImagePickerController // // Created by ZhangAo on 28/9/2018. // Copyright © 2017 ZhangAo. All rights reserved. // import UIKit import Foundation #if canImport(CropViewController) import CropViewController #endif open class DKImageExtensionPhotoCropper: DKImageBaseExtension { open weak var imageEditor: UIViewController? open var metadata: [AnyHashable : Any]? open var didFinishEditing: ((UIImage, [AnyHashable : Any]?) -> Void)? override class func extensionType() -> DKImageExtensionType { return .photoEditor } override open func perform(with extraInfo: [AnyHashable: Any]) { guard let sourceImage = extraInfo["image"] as? UIImage , let didFinishEditing = extraInfo["didFinishEditing"] as? ((UIImage, [AnyHashable : Any]?) -> Void) else { return } self.metadata = extraInfo["metadata"] as? [AnyHashable : Any] self.didFinishEditing = didFinishEditing let imageCropper = CropViewController(image: sourceImage) imageCropper.onDidCropToRect = { [weak self] image, _, _ in guard let strongSelf = self else { return } if let didFinishEditing = strongSelf.didFinishEditing { if sourceImage != image { strongSelf.metadata?[kCGImagePropertyOrientation] = NSNumber(integerLiteral: 1) } didFinishEditing(image, strongSelf.metadata) strongSelf.didFinishEditing = nil strongSelf.metadata = nil } } imageCropper.modalPresentationStyle = .fullScreen self.imageEditor = imageCropper let imagePickerController = self.context.imagePickerController let presentedViewController = imagePickerController?.presentedViewController ?? imagePickerController presentedViewController?.present(imageCropper, animated: true, completion: nil) } override open func finish() { self.imageEditor?.presentingViewController?.dismiss(animated: true, completion: nil) } }
mit
7f717d5768667ce361d60743808f8fed
35.163934
128
0.643246
5.598985
false
false
false
false
beyerss/CalendarKit
CalendarKit/ViewController/Calendar.swift
1
12872
// // Calendar.swift // CalendarKit // // Created by Steven Beyers on 5/23/15. // Copyright (c) 2015 Beyers Apps, LLC. All rights reserved. // import UIKit public class Calendar: UIViewController { @IBOutlet private weak var calendarCollectionView: UICollectionView! // The months that are currently available private var monthsShowing = Array<Month>() // The month currently showing private var currentMonth = Month(monthDate: NSDate()) // The position of the current month in the scroll view private var currentMonthPosition: Int = 0 // The date that has been selected public var selectedDate: NSDate? // The delegate to notify of events public var delegate: CalendarDelegate? // The configuration for the calendar private(set) public var configuration = CalendarConfiguration.FullScreenConfiguration() { didSet { if let myView = view { myView.backgroundColor = configuration.backgroundColor } if let collection = calendarCollectionView { collection.backgroundColor = configuration.backgroundColor } } } /// The constraint that limits the height of the calendar. This is used when a dynamic calendar height is desired. public var calendarHeightConstraint: NSLayoutConstraint? public init(configuration: CalendarConfiguration? = nil) { super.init(nibName: "Calendar", bundle: NSBundle(identifier: "com.beyersapps.CalendarKit")) // set the configuration to the one specified if let config = configuration { self.configuration = config } } public required init(coder aDecoder: NSCoder) { super.init(nibName: "Calendar", bundle: NSBundle(identifier: "com.beyersapps.CalendarKit")) } override public func viewDidLoad() { super.viewDidLoad() // set the month format currentMonth.useMonthFormat(configuration.monthFormat) // set the background color view.backgroundColor = configuration.backgroundColor calendarCollectionView.backgroundColor = configuration.backgroundColor // register cell let bundle = NSBundle(identifier: "com.beyersapps.CalendarKit") calendarCollectionView.registerNib(UINib(nibName: "CalendarMonth", bundle: bundle), forCellWithReuseIdentifier: "monthCell") // Set up data to start at the date 2 months ago rebuildMonths(currentMonthOnly: true) // tell the delegate what month I'm on delegate?.calendar(self, didScrollToDate: currentMonth.date, withNumberOfWeeks: currentMonth.weeksInMonth()) } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // fix the calendar height updateCalendarHeight() // reload the data whenever the view appears self.calendarCollectionView.reloadData() } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // rebuild the month array when the view appears rebuildMonths() // reload data and make sure we are at the center month so that we can scroll both ways calendarCollectionView.reloadData() calendarCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: currentMonthPosition), atScrollPosition: .Left, animated: false) } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { // coordinator.animateAlongsideTransition({ (context: UIViewControllerTransitionCoordinatorContext) in // // do nothing // }) { [weak self](context: UIViewControllerTransitionCoordinatorContext) in // self?.calendarCollectionView.collectionViewLayout.invalidateLayout() // self?.view.setNeedsDisplay() // self?.calendarCollectionView.reloadData() // } coordinator.animateAlongsideTransition({ [weak self](context) -> Void in self?.calendarCollectionView.collectionViewLayout.invalidateLayout() }, completion: { [weak self](context) -> Void in guard let weakSelf = self else { return } weakSelf.calendarCollectionView.reloadData() weakSelf.calendarCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: weakSelf.currentMonthPosition), atScrollPosition: .Left, animated: false) }) } /** Updates the height of the calendar if the height is supposed to be dynamic */ private func updateCalendarHeight() { if (configuration.dynamicHeight) { let weeks = CGFloat(currentMonth.weeksInMonth()) let totalCellHeight = weeks * configuration.dateCellConfiguration.heightForDynamicHeightRows let totalSpacerheight = (weeks - 1) * configuration.spaceBetweenDates let monthHeaderHeight = configuration.monthHeaderConfiguration.height let weekdayHeaderHeight = configuration.weekdayHeaderConfiguration.height let padding: CGFloat = 1 let desiredHeight = totalCellHeight + totalSpacerheight + monthHeaderHeight + weekdayHeaderHeight + padding if let constraint = calendarHeightConstraint where constraint.constant != desiredHeight { if (constraint.constant > desiredHeight) { calendarCollectionView.collectionViewLayout.invalidateLayout() } constraint.constant = desiredHeight UIView.animateWithDuration(0.5, animations: {[weak self]() in // call layout if needed on superview so it animates and related constraints self?.view.superview?.layoutIfNeeded() // animate calendar constraints self?.view.layoutIfNeeded() }, completion: { (finished) in }) } } } /** Rebuilds the month array with the current month being in the center and two months on the left plus another two months on the right so that we can scroll both directions. */ private func rebuildMonths(currentMonthOnly currentOnly: Bool = false) { monthsShowing = Array<Month>() if (currentOnly) { // If we only want the current month than we can only show one month at a time let tempMonth = currentMonth currentMonth = tempMonth monthsShowing.append(currentMonth) } else { // If we want to scroll between months then put two months on both sides of the current month // reset the currentMonthPostion before rebuilding array currentMonthPosition = 0 if let twoMonthsBack = getFirstDayOfMonthOffsetFromCurrentMonth(-2) where isAfterMinDate(twoMonthsBack) { monthsShowing.append(Month(monthDate: twoMonthsBack)) currentMonthPosition += 1 } if let oneMonthsBack = getFirstDayOfMonthOffsetFromCurrentMonth(-1) where isAfterMinDate(oneMonthsBack) { monthsShowing.append(Month(monthDate: oneMonthsBack)) currentMonthPosition += 1 } monthsShowing.append(currentMonth) if let oneMonthForward = getFirstDayOfMonthOffsetFromCurrentMonth(1) where isBeforeMaxDate(oneMonthForward) { monthsShowing.append(Month(monthDate: oneMonthForward)) } if let twoMonthForward = getFirstDayOfMonthOffsetFromCurrentMonth(2) where isBeforeMaxDate(twoMonthForward) { monthsShowing.append(Month(monthDate: twoMonthForward)) } } } private func getFirstDayOfMonthOffsetFromCurrentMonth(offset: Int) -> NSDate? { let calendar = NSCalendar.currentCalendar() let date = calendar.dateByAddingUnit(.Month, value: offset, toDate: currentMonth.date, options: [])! return date } private func isAfterMinDate(date: NSDate) -> Bool { if let minDate = configuration.logicConfiguration?.minDate { return (NSCalendar.currentCalendar().compareDate(minDate, toDate: date, toUnitGranularity: NSCalendarUnit.Month) != .OrderedDescending) } return true } private func isBeforeMaxDate(date: NSDate) -> Bool { if let maxDate = configuration.logicConfiguration?.maxDate { return (NSCalendar.currentCalendar().compareDate(date, toDate: maxDate, toUnitGranularity: NSCalendarUnit.Month) != .OrderedDescending) } return true } } extension Calendar: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate { public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { // Keep track of the month being displayed let month = monthsShowing[indexPath.section] if (month != currentMonth) { currentMonth = month } } /** Handle scrolling ending */ public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // if we are not on the center section let offset = scrollView.contentOffset.x if (scrollView.contentOffset.x != self.view.frame.width * CGFloat(currentMonthPosition)) { // reset the position of the collection view to re-center // resetPosition() if (offset == 0) { currentMonth = monthsShowing[0] } else if (offset == view.frame.width) { currentMonth = monthsShowing[1] } else if (offset == view.frame.width * 2) { currentMonth = monthsShowing[2] } else if (offset == view.frame.width * 3) { currentMonth = monthsShowing[3] } else { currentMonth = monthsShowing[4] } // fix the calendar height updateCalendarHeight() // notify the delegate that we changed months delegate?.calendar(self, didScrollToDate: currentMonth.date, withNumberOfWeeks: currentMonth.weeksInMonth()) // rebuild the months so that the new month is in the middle rebuildMonths() // reload data and move to the center of the scroll view calendarCollectionView.reloadData() calendarCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: currentMonthPosition), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false) } else { // If we are still in the center of the scroll view then we didn't change months if (currentMonth != monthsShowing[currentMonthPosition]) { currentMonth = monthsShowing[currentMonthPosition] } } } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return calendarCollectionView.frame.size } public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // Nothing happens here b/c we can only select individual cells collectionView.deselectItemAtIndexPath(indexPath, animated: false) } } extension Calendar: UICollectionViewDataSource { public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // We are showing one CalendarMonth cell for each section return 1 } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { // Show one section for each month return monthsShowing.count } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Get the month cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier("monthCell", forIndexPath: indexPath) if let month = cell as? CalendarMonth { // let the monthCell know that I own it month.containingCalendar = self month.monthToDisplay = monthsShowing[indexPath.section] month.backgroundColor = configuration.backgroundColor } return cell } }
mit
cf5c582a6034f6b8a0d3b1791893707f
42.782313
188
0.652579
5.850909
false
true
false
false
kwizzad/kwizzad-ios
Source/Localization.swift
1
2437
// // Localization.swift // KwizzadSDK // // Created by Sebastian Felix on 18/05/2017. // Copyright © 2017 Kwizzad. All rights reserved. // import UIKit var localizedBundle: Bundle? = nil; let defaultLocale = "en"; /// Returns the language code with the country code removed (for example `"en"` if given `"en-GB"`. /// returns: the language code with the country code removed (for example `"en"` if given `"en-GB"`. func languageWithoutCountry(_ language: String) -> String { return language.count >= 2 ? language.substring(with: language.startIndex..<language.index(language.startIndex, offsetBy: 2)) : language; } func languageCodesToTry(_ preferredLanguages: [String]) -> [String] { let languages = preferredLanguages.flatMap({ [$0, languageWithoutCountry($0)] }) + [defaultLocale]; var uniqueLanguages = Set<String>(); return languages.filter({ uniqueLanguages.insert($0).inserted }); // filtering keeps input array order } func localizedBundle(_ languageCode: String) -> Bundle? { let mainBundle = Bundle(for: KwizzadSDK.self) if let path = mainBundle.path(forResource: languageCode, ofType: "lproj") { if let bundle = Bundle(path: path) { localizedBundle = bundle; return bundle; } } return nil; } /// Tries to find a localized bundle using the user's preferred languages. /// Falls back to languages without countries if a bundle for the given language exists. /// If none of the user's preferred languages exist as localization, it falls back to 'en'. /// When using this, there MUST be a localization for "en", otherwise this crashes. func findLocalizedBundle() -> Bundle? { if localizedBundle != nil { return localizedBundle!; } for languageCode in languageCodesToTry(Locale.preferredLanguages) { if let bundle = localizedBundle(languageCode) { return bundle; } } return nil; } /// returns: Translation of the given string format. When you use this, builds can automatically /// collect new strings from the code in the build process using the `genstrings` tool. func LocalizedString(_ format: String, comment: String) -> String { guard let bundle = findLocalizedBundle() else { print("Warning: No localized strings found for '\(defaultLocale)' locale!"); return format; } return NSLocalizedString(format, tableName: "Kwizzad", bundle: bundle, comment: comment) }
mit
40d0bb257e7e2d12cb554a583a02b5ca
39.6
141
0.697044
4.288732
false
false
false
false
tiggleric/CVCalendar
Pod/Classes/CVCalendarDayViewControlCoordinator.swift
6
2061
// // CVCalendarDayViewControlCoordinator.swift // CVCalendar // // Created by E. Mozharovsky on 12/27/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit private let instance = CVCalendarDayViewControlCoordinator() class CVCalendarDayViewControlCoordinator: NSObject { var inOrderNumber = 0 class var sharedControlCoordinator: CVCalendarDayViewControlCoordinator { return instance } var selectedDayView: CVCalendarDayView? = nil var animator: CVCalendarViewAnimatorDelegate? lazy var appearance: CVCalendarViewAppearance = { return CVCalendarViewAppearance.sharedCalendarViewAppearance }() private override init() { super.init() } func performDayViewSelection(dayView: CVCalendarDayView) { if let selectedDayView = self.selectedDayView { if selectedDayView != dayView { if self.inOrderNumber < 2 { self.presentDeselectionOnDayView(self.selectedDayView!) self.selectedDayView = dayView self.presentSelectionOnDayView(self.selectedDayView!) } } } else { self.selectedDayView = dayView if self.animator == nil { self.animator = self.selectedDayView!.weekView!.monthView!.calendarView!.animator } self.presentSelectionOnDayView(self.selectedDayView!) } } private func presentSelectionOnDayView(dayView: CVCalendarDayView) { self.animator?.animateSelection(dayView, withControlCoordinator: CVCalendarDayViewControlCoordinator.sharedControlCoordinator) } private func presentDeselectionOnDayView(dayView: CVCalendarDayView) { self.animator?.animateDeselection(dayView, withControlCoordinator: CVCalendarDayViewControlCoordinator.sharedControlCoordinator) } func animationStarted() { self.inOrderNumber++ } func animationEnded() { self.inOrderNumber-- } }
mit
31b55a615aa0be7540905a96e0ba0b83
30.707692
136
0.670548
5.631148
false
false
false
false
pirishd/InstantMock
Sources/InstantMock/Arguments/Captor/ArgumentClosureCaptor/ArgumentClosureCaptor+NoArg.swift
1
1269
// // ArgumentClosureCaptor+NoArg.swift // InstantMock iOS // // Created by Patrick on 22/07/2017. // Copyright © 2017 pirishd. All rights reserved. // /** Extension that performs the actual capture for no arg */ extension ArgumentClosureCaptor { /** Capture a closure of expected type */ public func capture<Ret>() -> T where T == () -> Ret { let factory = ArgumentFactoryImpl<T>() return self.capture(argFactory: factory, argStorage: ArgumentStorageImpl.instance) as () -> Ret } /** Capture a closure of expected type that can throw */ public func capture<Ret>() -> T where T == () throws -> Ret { let factory = ArgumentFactoryImpl<T>() return self.capture(argFactory: factory, argStorage: ArgumentStorageImpl.instance) as () throws -> Ret } /** Capture an argument of expected type (for dependency injection) */ func capture<Ret, F>(argFactory: F, argStorage: ArgumentStorage) -> () -> Ret where F: ArgumentFactory, F.Value == T { // store instance let typeDescription = "\(T.self)" let arg = argFactory.argumentCapture(typeDescription) self.arg = arg argStorage.store(arg) return DefaultClosureHandler.it() as () -> Ret } }
mit
5fbe2418774206ad570e27a76e0870c4
29.190476
110
0.643533
4.212625
false
false
false
false
aronse/RdxSwift
Example/Tests/Tests.swift
1
1256
import UIKit import XCTest import RdxSwift struct TestState: RdxStateType { var val: String = "" } enum TestAction: RdxActionType { case callback(() -> Void) case changeValue(String) } func reducer(oldState: TestState, action: TestAction) -> TestState { var state: TestState = oldState switch action { case .callback(let fn): fn() case .changeValue(let value): state.val = value } return state } class Tests: XCTestCase { let store = RdxStore<TestState, TestAction>( state: TestState(), reducer: reducer, middlewares: [], asyncReducer: nil ) override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func isActionExecutedOnBackgroundThread() { store.dispatch(action: .callback({ XCTAssert(!Thread.isMainThread) })) } func isStateCorrectlyUpdatedAfterDispatch() { let oldVal = store.state.val store.dispatchAsync(action: TestAction.changeValue("foo")) XCTAssert(store.state.val != oldVal) } }
mit
99e2ff45c169ab3dbdfafbd93355fb29
21.035088
107
0.680732
4.064725
false
true
false
false
TheAppCookbook/MiseEnPlace
Tests/FormViewControllerTests.swift
1
1111
// // FormViewControllerTests.swift // MiseEnPlace // // Created by PATRICK PERINI on 9/12/15. // Copyright © 2015 pcperini. All rights reserved. // import XCTest class FormViewControllerTests: XCTestCase { // MARK: Setup override func setUp() { super.setUp() self.continueAfterFailure = false XCUIApplication().launch() } // MARK: Tests func testForm() { let tablesQuery = XCUIApplication().tables tablesQuery.cells["FormTests"].tap() let usernameField = tablesQuery.textFields["FormUsernameInput"] let passwordField = tablesQuery.secureTextFields["FormPasswordInput"] let doneButton = tablesQuery.buttons["FormDoneButton"] usernameField.tap() usernameField.typeText("test_username") XCTAssertFalse(doneButton.enabled) passwordField.tap() passwordField.typeText("012345678") XCTAssertFalse(doneButton.enabled) passwordField.typeText("9") XCTAssertTrue(doneButton.enabled) doneButton.tap() } }
mit
6ef3aeac4561b8d4b567de5246c9ae3a
26.073171
77
0.636937
5.162791
false
true
false
false
dfortuna/theCraic3
theCraic3/Main/Event/EventAttendeesTVCell.swift
1
4456
// // EventAttendeesTVCell.swift // Project01 // // Created by Denis Fortuna on 25/5/17. // Copyright © 2017 Denis. All rights reserved. // import UIKit class EventAttendeesTVCell: UITableViewCell { var friendsPictureURL = [String] () var maleAttendees: Int? var femaleAttendees: Int? { didSet{ updateUI() } } var viewsToDelete = [UIView]() @IBOutlet weak var maleAttendeesPercentageLabel: UILabel! @IBOutlet weak var femaleAttendeesPercentageLabel: UILabel! @IBOutlet weak var AttendeesContainerScrollView: UIScrollView! { didSet{ } } func updateUI() { guard let male = maleAttendees else { return } guard let female = femaleAttendees else { return } var malePercentage = (male * 100) / (male + female) maleAttendeesPercentageLabel.text = "\(malePercentage)%" var femalePercentage = (female * 100) / (male + female) femaleAttendeesPercentageLabel.text = "\(femalePercentage)%" //---Freinds attending: for friendPic in viewsToDelete { friendPic.removeFromSuperview() } AttendeesContainerScrollView.layer.borderWidth = 0.3 AttendeesContainerScrollView.layer.borderColor = UIColor.lightGray.cgColor let containerWidth = AttendeesContainerScrollView.frame.width let containerHeight = AttendeesContainerScrollView.frame.height var widthTaken: CGFloat = 0 var heightTaken: CGFloat = 0 let marginX: CGFloat = 16 let marginY: CGFloat = /*12 */ 16 let origin: CGFloat = 0 var partialWidthTaken: CGFloat = 0 for friendPicURL in friendsPictureURL { if (widthTaken + 34) < containerWidth { partialWidthTaken = addFriendPic(friendPicURL: friendPicURL, widthTaken: widthTaken, heightTaken: heightTaken, marginX: marginX, containerHeight: containerHeight, origin: origin) widthTaken += partialWidthTaken } else { heightTaken += 50 + 10 widthTaken = 0 partialWidthTaken = addFriendPic(friendPicURL: friendPicURL, widthTaken: widthTaken, heightTaken: heightTaken, marginX: marginX, containerHeight: containerHeight, origin: origin) widthTaken += partialWidthTaken } AttendeesContainerScrollView.contentSize = CGSize(width: widthTaken, height: heightTaken) } } func addFriendPic(friendPicURL: String, widthTaken: CGFloat, heightTaken: CGFloat, marginX: CGFloat, containerHeight: CGFloat, origin: CGFloat) -> CGFloat { let friendPic: UIImageView = { let friendP = UIImageView() var positionX = origin + widthTaken var positionY = origin + heightTaken friendP.frame = CGRect(origin: CGPoint(x: positionX, y: positionY), size: CGSize(width: 50, height: 50)) friendP.backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1) friendP.layer.cornerRadius = friendP.bounds.size.width/2 friendP.layer.masksToBounds = true friendP.layer.borderWidth = 0.3 if let profImage = URL(string: friendPicURL) { DispatchQueue.global().async { guard let imagedata = try? Data(contentsOf: profImage) else { return } DispatchQueue.main.async { friendP.image = UIImage(data: imagedata) } } } return friendP }() AttendeesContainerScrollView.addSubview(friendPic) viewsToDelete.append(friendPic) return (/*containerHeight*/ 50 - marginX) } }
apache-2.0
4c26688269dca23f0515e30eaded47aa
38.776786
120
0.535802
5.380435
false
false
false
false
izotx/iTenWired-Swift
Conference App/MasterViewController.swift
1
11548
// Copyright (c) 2016, Izotx // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Izotx nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // MasterViewController.swift // Conference App // Created by Felipe Neves {[email protected]} on 5/18/16. import UIKit import CoreData class MasterViewController : UIViewController{ var menuItems:[MenuItem] = [] let reach = Reach() let network = NetworkConnection() let appData = AppData() @IBOutlet weak var logo: UIImageView! @IBOutlet weak var collectionView: UICollectionView! var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil override func viewWillAppear(animated: Bool) { self.collectionView.reloadData() if NetworkConnection.isConnected(){ self.appData.saveData() } self.navigationController?.navigationBarHidden = true } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: NSSelectorFromString("updateData"), name: NotificationObserver.APPBecameActive.rawValue, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: NSSelectorFromString("updateData"), name: NotificationObserver.RemoteNotificationReceived.rawValue, object: nil) loadMenuItems() self.UIConfig() //CollectionView Deleagte self.collectionView.delegate = self self.collectionView.dataSource = self // SplitView Delegate splitViewController?.delegate = self } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBarHidden = false } func updateData(){ self.collectionView.reloadData() } internal func UIConfig(){ self.collectionView.backgroundColor = ItenWiredStyle.background.color.mainColor self.view.backgroundColor = ItenWiredStyle.background.color.mainColor self.logo.image = UIImage(named: "logo-16.png") self.navigationController?.navigationBarHidden = true } /** Loads the menu items into the MenuItems array */ internal func loadMenuItems(){ let agenda = MenuItem(storyboardId: "AgendaMain", viewControllerId: "AgendaInitial", name: "Agenda", imageUrl: "AgendaFilled-50.png") self.menuItems.append(agenda) let atendees = MenuItem(storyboardId: "Attendees", viewControllerId: "Attendee", name: "Who is here", imageUrl: "WhoFilled-50.png") self.menuItems.append(atendees) let myIten = MenuItem(storyboardId: "ItineraryStoryboard", viewControllerId: "Itinerary", name: "My Iten", imageUrl: "MyItenFilled-50.png") self.menuItems.append(myIten) let notifications = MenuItem(storyboardId: "Notification", viewControllerId: "NotificationViewControllerNav", name: "Announcements", imageUrl: "AnnouncementsFilled-50.png") self.menuItems.append(notifications) let nearBy = MenuItem(storyboardId: "NearBy", viewControllerId: "NearByViewControllerInitial", name: "Near Me", imageUrl: "NearByFilled-50.png") self.menuItems.append(nearBy) let map = MenuItem(storyboardId: "MapView", viewControllerId: "MapNavStoryboard", name: "Map", imageUrl: "MapMFilled-50.png") self.menuItems.append(map) let socialMedia = MenuItem(storyboardId: "SocialMedia", viewControllerId: "SocialMediaNav", name: "Social Media", imageUrl: "SocialMediaFilled-50.png") self.menuItems.append(socialMedia) let broadcast = MenuItem(storyboardId: "LiveBroadcast", viewControllerId: "LiveBroadcast", name: "Live Broadcast", imageUrl: "LiveBroadcastFilled-50.png") self.menuItems.append(broadcast) let about = MenuItem(storyboardId: "AboutView", viewControllerId: "AboutViewNav", name: "About", imageUrl: "AboutFilled-50.png") self.menuItems.append(about) } } //MARK: - UICollectionViewDataSource extension MasterViewController : UICollectionViewDataSource{ func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { guard let cell = self.collectionView.cellForItemAtIndexPath(indexPath) as? MenuCellCollectionViewCell else { return } cell.backgroundColor = ItenWiredStyle.background.color.invertedColor cell.nameLabel.textColor = ItenWiredStyle.text.color.invertedColor cell.icon.backgroundColor = ItenWiredStyle.background.color.invertedColor cell.icon.setImage(menuItems[indexPath.row].invertedColorIcon, forState: .Normal) } func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) { guard let cell = self.collectionView.cellForItemAtIndexPath(indexPath) as? MenuCellCollectionViewCell else { return } cell.backgroundColor = ItenWiredStyle.background.color.mainColor cell.nameLabel.textColor = ItenWiredStyle.text.color.mainColor cell.icon.backgroundColor = ItenWiredStyle.background.color.mainColor cell.icon.setImage(menuItems[indexPath.row].image, forState: .Normal) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.menuItems.count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if let svc = self.splitViewController where svc.collapsed == false { return CGSize(width: ((collectionView.frame.size.width - 10)) , height: 60) } return CGSize(width: ((collectionView.frame.size.width - 10) / 2) - 6 , height: 150) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let svc = self.splitViewController where svc.collapsed == false { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCellLong", forIndexPath: indexPath) as? MenuCellCollectionViewCell cell?.build(self.menuItems[indexPath.row]) cell?.layer.shadowColor = UIColor.blackColor().CGColor cell?.layer.shadowOffset = CGSizeMake(0,1.5) if menuItems[indexPath.row].name == "Announcements"{ let notificationController = NotificationController() cell?.icon.badgeString = "" if notificationController.getNumberOfUnReadNotifications() > 0 { cell?.icon.badgeString = "\(notificationController.getNumberOfUnReadNotifications())" } }else { cell?.icon.badgeString = "" } return cell! } let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as? MenuCellCollectionViewCell cell?.build(self.menuItems[indexPath.row]) cell?.layer.shadowColor = UIColor.blackColor().CGColor cell?.layer.shadowOffset = CGSizeMake(0,1.5) if menuItems[indexPath.row].name == "Announcements"{ let notificationController = NotificationController() cell?.icon.badgeString = "" if notificationController.getNumberOfUnReadNotifications() > 0 { cell?.icon.badgeString = "\(notificationController.getNumberOfUnReadNotifications())" } }else { cell?.icon.badgeString = "" } return cell! } } //MARK: - UICollectionViewDelegate extension MasterViewController: UICollectionViewDelegate{ func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){ let index = indexPath.row let menuItem = menuItems[index] if menuItem.name == "Announcements"{ self.collectionView.reloadData() } if NetworkConnection.isConnected() == false { if menuItem.name == "Social Media"{ // create the alert let alert = UIAlertController(title: "No Internet Connection", message: "Make sure your connected to the internet before accessing \(menuItem.name)", preferredStyle: UIAlertControllerStyle.Alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) // show the alert self.presentViewController(alert, animated: true, completion: nil) return } } let storyboard = UIStoryboard.init(name: menuItem.storyboardId, bundle: nil) let destinationViewController = storyboard.instantiateViewControllerWithIdentifier(menuItem.viewControllerId) splitViewController?.showDetailViewController(destinationViewController, sender: nil) } } //Mark: - UISplitViewControllerDelegate extension MasterViewController: UISplitViewControllerDelegate{ func targetDisplayModeForActionInSplitViewController(svc: UISplitViewController) -> UISplitViewControllerDisplayMode{ return .PrimaryHidden } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { return true } }
bsd-2-clause
22b35b4ce48053e97973dbfda24da049
43.419231
224
0.681157
5.434353
false
false
false
false
coderMONSTER/ioscelebrity
YStar/YStar/Scenes/Controller/BenifityVC.swift
1
12480
// // BenifityVC.swift // YStar // // Created by mu on 2017/7/4. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit import Charts private let KBenifityCellID = "BenifityCell" class BenifityVC: BaseTableViewController,DateSelectorViewDelegate { // tableHeaderView @IBOutlet weak var contentView: UIView! @IBOutlet weak var beginTimeButton: UIButton! @IBOutlet weak var endTimeButton: UIButton! @IBOutlet weak var beginPlaceholderImageView: UIImageView! @IBOutlet weak var endPlaceholderImageView: UIImageView! // 折线图 @IBOutlet weak var lineView: KLineView! // 收益信息 var earningData : [EarningInfoModel]? // 点击时间标识 var beginOrEnd : Bool = true override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // MARK: - 初始化 override func viewDidLoad() { super.viewDidLoad() if isLogin() {} setupUI() NotificationCenter.default.addObserver(self, selector: #selector(LoginSuccess(_ :)), name: NSNotification.Name(rawValue:AppConst.NoticeKey.LoginSuccess.rawValue), object: nil) } func setupUI() { self.beginPlaceholderImageView.image = UIImage.imageWith(AppConst.iconFontName.downArrow.rawValue, fontSize: beginPlaceholderImageView.frame.size, fontColor: UIColor.init(rgbHex: 0xDFDFDF)) self.endPlaceholderImageView.image = UIImage.imageWith(AppConst.iconFontName.downArrow.rawValue, fontSize: beginPlaceholderImageView.frame.size, fontColor: UIColor.init(rgbHex: 0xDFDFDF)) self.beginTimeButton.addTarget(self, action: #selector(timeButtonClick(_ :)), for: .touchUpInside) self.endTimeButton.addTarget(self, action: #selector(timeButtonClick(_ :)), for: .touchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "Exit", style: .done, target: self, action: #selector(ExitleftButtonClick)) self.tableView.tableHeaderView = contentView self.tableView.separatorStyle = .none } // MARK: - 移除通知 deinit { NotificationCenter.default.removeObserver(self) } // MARK: - 登录成功的通知方法 func LoginSuccess(_ note : NSNotification) { setupInitResponse() self.tableView.reloadData() } // MARK: - 默认一周交易数据 func setupInitResponse() { let cureentDate = NSDate() // 一天前 let oneDayTimeInterval : TimeInterval = 24 * 60 * 60 * 1 let beforeDay = cureentDate.addingTimeInterval(-oneDayTimeInterval) // 七天前 let weekDayTimeInterval : TimeInterval = 24 * 60 * 60 * 6 let beforeWeekDay = beforeDay.addingTimeInterval(-weekDayTimeInterval) // print("=====现在的日期是\(cureentDate) 一天前的日期====\(beforeDay) ===一周前的日期===\(beforeWeekDay)") let beginDateStr = beforeWeekDay.string_from(formatter: "yyyy-MM-dd") let endDateStr = beforeDay.string_from(formatter: "yyyy-MM-dd") self.beginTimeButton.setTitle(beginDateStr, for: .normal) self.endTimeButton.setTitle(endDateStr, for: .normal) // 转换成没有分割线的日期 let beginDateString = beforeWeekDay.string_from(formatter: "yyyyMMdd") let endDateString = beforeDay.string_from(formatter: "yyyyMMdd") // print("----\(endDateString) ----\(beginDateString)") // 转换成Int var beginDateInt : Int64 = 0 if beginDateStr.length() != 0 { beginDateInt = Int64(beginDateString)! } var endDateInt : Int64 = 0 if endDateString.length() != 0 { endDateInt = Int64(endDateString)! } let model = EarningRequestModel() model.stardate = beginDateInt model.enddate = endDateInt // model.stardate = 20170601 // model.enddate = 20170631 requestInitResponse(stardate: model.stardate, enddate: model.enddate) } // MARK: - 点击时间选择 func timeButtonClick(_ sender : UIButton) { if sender == beginTimeButton { let datePickerView = DateSelectorView(delegate: self) beginOrEnd = true datePickerView.showPicker() } else { let datePickerView = DateSelectorView(delegate: self) beginOrEnd = false datePickerView.showPicker() } } // MARK: - DateSelectorViewDelegate func chooseDate(datePickerView: DateSelectorView, date: Date) { let weekTimeInterval : TimeInterval = 24 * 60 * 60 * 6 let dateString = date.string_from(formatter: "yyyy-MM-dd") if beginOrEnd == true { // 获取7天后的日期 let afterWeekDate = date.addingTimeInterval(weekTimeInterval) let afterWeekStr = afterWeekDate.string_from(formatter: "yyyy-MM-dd") self.beginTimeButton.setTitle(dateString, for: .normal) self.endTimeButton.setTitle(afterWeekStr, for: .normal) let beginDateString = date.string_from(formatter: "yyyyMMdd") let endDateString = afterWeekDate.string_from(formatter: "yyyyMMdd") let model = EarningRequestModel() model.stardate = Int64(beginDateString)! model.enddate = Int64(endDateString)! requestInitResponse(stardate: model.stardate, enddate: model.enddate) } else { // 获取7天前的日期 let beforeWeekDate = date.addingTimeInterval(-weekTimeInterval) let beforeWeekStr = beforeWeekDate.string_from(formatter: "yyyy-MM-dd") self.endTimeButton.setTitle(dateString, for: .normal) self.beginTimeButton.setTitle(beforeWeekStr, for: .normal) let beginDateString = beforeWeekDate.string_from(formatter: "yyyyMMdd") let endDateString = date.string_from(formatter: "yyyyMMdd") let model = EarningRequestModel() model.stardate = Int64(beginDateString)! model.enddate = Int64(endDateString)! requestInitResponse(stardate: model.stardate, enddate: model.enddate) } } // MARK: - 请求收益列表信息 func requestInitResponse(stardate: Int64 , enddate : Int64) { let requestModel = EarningRequestModel() requestModel.stardate = stardate requestModel.enddate = enddate AppAPIHelper.commen().requestEarningInfo(model: requestModel, complete: { (response) -> ()? in if self.earningData != nil { self.earningData?.removeAll() } if let objects = response as? [EarningInfoModel] { self.earningData = objects self.lineView.refreshLineChartData(models: objects) } self.tableView.reloadData() return nil }) { (error) -> ()? in self.tableView.reloadData() self.didRequestError(error) return nil } } // MARK: - tableViewDataSource And tableViewDelegate override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return earningData?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let benifityCell = tableView.dequeueReusableCell(withIdentifier: KBenifityCellID, for: indexPath) as! BenifityCell if earningData != nil { benifityCell.setBenifity(model: earningData![indexPath.row]) } benifityCell.containerView.backgroundColor = indexPath.row % 2 == 0 ? UIColor.clear : UIColor.white return benifityCell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let benifityDetailVC = UIStoryboard.init(name: "Benifity", bundle: nil).instantiateViewController(withIdentifier: "BenifityDetailVC") as! BenifityDetailVC benifityDetailVC.earningModel = self.earningData?[indexPath.row] self.navigationController?.pushViewController(benifityDetailVC, animated: true) } // MARK: - 点击了退出账号 func ExitleftButtonClick() { logout() } func logout() { let alertController = UIAlertController(title: "提示", message: "你确定要退出吗?", preferredStyle:.alert) // 设置2个UIAlertAction let cancelAction = UIAlertAction(title: "取消", style:.cancel, handler: nil) let completeAction = UIAlertAction(title: "确定", style:.default) { (UIAlertAction) in // 退出 AppDataHelper.instance().clearUserInfo() self.checkLogin() } // 添加 alertController.addAction(cancelAction) alertController.addAction(completeAction) self.present(alertController, animated: true, completion: nil) } // MARK: - 点击了提现 @IBAction func rightItemAction(_ sender: UIBarButtonItem) { if isLogin() { let model = BankCardListRequestModel() AppAPIHelper.commen().bankCardList(model: model, complete: {[weak self] (response) -> ()? in if let objects = response as? BankListModel { if objects.cardNo.length() != 0 { // 已绑定 let withdrawalVC = UIStoryboard.init(name:"Benifity",bundle: nil).instantiateViewController(withIdentifier: "WithdrawalVC") as! WithdrawalVC self?.navigationController?.pushViewController(withdrawalVC, animated: true) } else { // 未绑定 let alertVC = AlertViewController() alertVC.showAlertVc(imageName: "tangkuang_kaitongzhifu", titleLabelText: "绑定银行卡", subTitleText: "提现操作需先绑定银行卡才能进行操作", completeButtonTitle: "我 知 道 了", action: {[weak alertVC] (completeButton) in alertVC?.dismissAlertVc() let bindBankCardVC = UIStoryboard.init(name: "Benifity", bundle: nil).instantiateViewController(withIdentifier: "BindBankCardVC") self?.navigationController?.pushViewController(bindBankCardVC, animated: true) }) } } return nil }, error: { (error) -> ()? in // 未绑定 if error.code == -801 { let alertVC = AlertViewController() alertVC.showAlertVc(imageName: "tangkuang_kaitongzhifu", titleLabelText: "绑定银行卡", subTitleText: "提现操作需先绑定银行卡才能进行操作", completeButtonTitle: "我 知 道 了", action: {[weak alertVC] (completeButton) in alertVC?.dismissAlertVc() let bindBankCardVC = UIStoryboard.init(name: "Benifity", bundle: nil).instantiateViewController(withIdentifier: "BindBankCardVC") self.navigationController?.pushViewController(bindBankCardVC, animated: true) }) } else { self.didRequestError(error) } return nil }) } } }
mit
c574453ed7adeebdb53de1b8b8650624
37.85209
197
0.586195
4.972428
false
true
false
false
wowiwj/Yeep
Yeep/Yeep/ViewControllers/Show/ShowViewController.swift
1
6333
// // ShowViewController.swift // Yeep // // Created by wangju on 16/7/18. // Copyright © 2016年 wangju. All rights reserved. // import UIKit class ShowViewController: UIViewController { @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var pageControl: UIPageControl! @IBOutlet private weak var registerButton: UIButton! @IBOutlet private weak var loginButton: EdgeBorderButton! private var steps = [UIViewController]() private var isFirstAppear = true override func viewDidLoad() { super.viewDidLoad() MakeUI() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) if isFirstAppear { scrollView.alpha = 0 pageControl.alpha = 0 registerButton.alpha = 0 loginButton.alpha = 0 } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if isFirstAppear { UIView.animateWithDuration(1, delay: 0.5, options: .CurveEaseInOut, animations: { [weak self] in self?.scrollView.alpha = 1 self?.pageControl.alpha = 1 self?.registerButton.alpha = 1 self?.loginButton.alpha = 1 }, completion: { _ in }) } isFirstAppear = false } private func MakeUI() { let stepA = stepGenius() let stepB = stepMatch() let stepC = stepMeet() steps = [stepA,stepB,stepC] pageControl.numberOfPages = steps.count pageControl.pageIndicatorTintColor = UIColor.yeepBorderColor() pageControl.currentPageIndicatorTintColor = UIColor.yeepTintColor() registerButton.setTitle(NSLocalizedString("Sign Up", comment: ""), forState: .Normal) loginButton.setTitle(NSLocalizedString("Login", comment: ""), forState: .Normal) registerButton.backgroundColor = UIColor.yeepTintColor() loginButton.setTitleColor(UIColor.yeepInputTextColor(), forState: .Normal) let viewsDictionary: [String: AnyObject] = [ "view": view, "stepA": stepA.view, "stepB": stepB.view, "stepC": stepC.view, ] let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[stepA(==view)]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(vConstraints) let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[stepA(==view)][stepB(==view)][stepC(==view)]|", options: [.AlignAllBottom, .AlignAllTop], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(hConstraints) } private func stepGenius() -> ShowStepGeniusViewController { let step = storyboard!.instantiateViewControllerWithIdentifier("ShowStepGeniusViewController") as! ShowStepGeniusViewController step.view.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(step.view) addChildViewController(step) /** - (void)didMoveToParentViewController:(UIViewController *)parent 当从一个视图控制容器中添加或者移除viewController后,该方法被调用。 parent:父视图控制器,如果没有父视图控制器,将为nil 当我们向我们的视图控制器容器(就是父视图控制器,它调用addChildViewController方法加入子视图控制器,它就成为了视图控制器的容器)中添加(或者删除)子视图控制器后,必须调用该方法,告诉iOS,已经完成添加(或删除)子控制器的操作。 removeFromParentViewController 方法会自动调用了该方法,所以,删除子控制器后,不需要在显示的调用该方法了。 */ step.didMoveToParentViewController(self) return step } private func stepMatch() -> ShowStepMatchViewController { let step = storyboard!.instantiateViewControllerWithIdentifier("ShowStepMatchViewController") as! ShowStepMatchViewController step.view.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(step.view) addChildViewController(step) step.didMoveToParentViewController(self) return step } private func stepMeet() -> ShowStepMeetViewController { let step = storyboard!.instantiateViewControllerWithIdentifier("ShowStepMeetViewController") as! ShowStepMeetViewController step.view.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(step.view) addChildViewController(step) step.didMoveToParentViewController(self) return step } } // MARK: - 登录注册按钮的点击 extension ShowViewController { @IBAction func register(sender: UIButton) { let storyboard = UIStoryboard(name: "Intro", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("RegisterPickNameViewController") navigationController?.pushViewController(vc, animated: true) } @IBAction func login(sender: UIButton) { let storyboard = UIStoryboard(name: "Intro", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("LoginByMobileViewController") navigationController?.pushViewController(vc, animated: true) } } // MARK: - UIScrollViewDelegate extension ShowViewController:UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let pageWidth = CGRectGetWidth(scrollView.bounds) let pageFraction = scrollView.contentOffset.x / pageWidth // round 四舍五入取值函数 let page = Int(round(pageFraction)) pageControl.currentPage = page } }
mit
fb4681a89b219528287b1d6a4af07696
31.404372
206
0.645868
5.420475
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/TruncateOptimizationTests.swift
1
28739
import XCTest import GRDB class TruncateOptimizationTests: GRDBTestCase { // https://www.sqlite.org/c3ref/update_hook.html // // > In the current implementation, the update hook is not invoked [...] // > when rows are deleted using the truncate optimization. // // https://www.sqlite.org/lang_delete.html#truncateopt // // > When the WHERE is omitted from a DELETE statement and the table // > being deleted has no triggers, SQLite uses an optimization to erase // > the entire table content without having to visit each row of the // > table individually. // // We will thus test that the truncate optimization does not prevent // transaction observers from observing individual deletions. // // But that's not enough: preventing the truncate optimization requires GRDB // to fiddle with sqlite3_set_authorizer. When badly done, this can prevent // DROP TABLE statements from dropping tables. SQLite3 authorizers are // invoked during both compilation and execution of SQL statements. We will // thus test that DROP TABLE statements perform as expected when compilation // and execution are grouped, and when they are performed separately. class DeletionObserver : TransactionObserver { private var notify: ([String: Int]) -> Void private var deletionEvents: [String: Int] = [:] // Notifies table names with the number of deleted rows init(_ notify: @escaping ([String: Int]) -> Void) { self.notify = notify } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { if case .delete = event.kind { deletionEvents[event.tableName, default: 0] += 1 } } func databaseDidCommit(_ db: Database) { if !deletionEvents.isEmpty { notify(deletionEvents) } deletionEvents = [:] } func databaseDidRollback(_ db: Database) { deletionEvents = [:] } } class UniversalObserver : TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { } func databaseDidCommit(_ db: Database) { } func databaseDidRollback(_ db: Database) { } } func testExecuteDelete() throws { let dbQueue = try makeDatabaseQueue() var deletionEvents: [[String: Int]] = [] let observer = DeletionObserver { deletionEvents.append($0) } dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") deletionEvents = [] try db.execute(sql: "DELETE FROM t") XCTAssertEqual(deletionEvents.count, 1) XCTAssertEqual(deletionEvents[0], ["t": 2]) try db.execute(sql: "INSERT INTO t VALUES (NULL)") deletionEvents = [] try db.execute(sql: "DELETE FROM t") XCTAssertEqual(deletionEvents.count, 1) XCTAssertEqual(deletionEvents[0], ["t": 1]) } } func testExecuteDeleteCaseSensitivity() throws { let dbQueue = try makeDatabaseQueue() class DeletionObserver : TransactionObserver { var deletionCount = 0 func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { if case .delete(tableName: "pLaYeR") = eventKind { return true } else { return false } } func databaseDidChange(with event: DatabaseEvent) { if case .delete = event.kind { deletionCount += 1 } } func databaseDidCommit(_ db: Database) { } func databaseDidRollback(_ db: Database) { } } let observer = DeletionObserver() dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in observer.deletionCount = 0 try db.execute(sql: "CREATE TABLE pLaYeR(a)") try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)") try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)") try db.execute(sql: "DELETE FROM pLaYeR") XCTAssertEqual(observer.deletionCount, 2) observer.deletionCount = 0 try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)") try db.execute(sql: "DELETE FROM PLAYER") XCTAssertEqual(observer.deletionCount, 1) observer.deletionCount = 0 try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)") try db.execute(sql: "DELETE FROM player") XCTAssertEqual(observer.deletionCount, 1) } } func testExecuteDeleteWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() var deletionEvents: [[String: Int]] = [] let observer = DeletionObserver { deletionEvents.append($0) } dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") let deleteStatement = try db.makeStatement(sql: "DELETE FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") deletionEvents = [] try deleteStatement.execute() XCTAssertEqual(deletionEvents.count, 1) XCTAssertEqual(deletionEvents[0], ["t": 2]) try db.execute(sql: "INSERT INTO t VALUES (NULL)") deletionEvents = [] try deleteStatement.execute() XCTAssertEqual(deletionEvents.count, 1) XCTAssertEqual(deletionEvents[0], ["t": 1]) } } func testExecuteDeleteWithCachedPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() var deletionEvents: [[String: Int]] = [] try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.cachedStatement(sql: "DELETE FROM t").execute() // Start observing after statement has been cached: it does not // prevent the truncate optimization. let observer = DeletionObserver { deletionEvents.append($0) } db.add(transactionObserver: observer, extent: .databaseLifetime) try db.execute(sql: "INSERT INTO t VALUES (NULL)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") deletionEvents = [] // This must be a recompiled statement, so that the truncate // optimization is prevented. try db.cachedStatement(sql: "DELETE FROM t").execute() XCTAssertEqual(deletionEvents.count, 1) XCTAssertEqual(deletionEvents[0], ["t": 2]) try db.execute(sql: "INSERT INTO t VALUES (NULL)") deletionEvents = [] try db.cachedStatement(sql: "DELETE FROM t").execute() XCTAssertEqual(deletionEvents.count, 1) XCTAssertEqual(deletionEvents[0], ["t": 1]) } } func testDropTable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) try db.execute(sql: "DROP TABLE t") // compile + execute try XCTAssertFalse(db.tableExists("t")) } } func testObservedDropTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) try db.execute(sql: "DROP TABLE t") // compile + execute try XCTAssertFalse(db.tableExists("t")) } } func testDropTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } } func testObservedDropTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } } func testDropTemporaryTable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) try db.execute(sql: "DROP TABLE t") // compile + execute try XCTAssertFalse(db.tableExists("t")) } } func testObservedDropTemporaryTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) try db.execute(sql: "DROP TABLE t") // compile + execute try XCTAssertFalse(db.tableExists("t")) } } func testDropTemporaryTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } } func testObservedDropTemporaryTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } } func testDropVirtualTable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) try db.execute(sql: "DROP TABLE t") // compile + execute try XCTAssertFalse(db.tableExists("t")) } } func testObservedDropVirtualTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) try db.execute(sql: "DROP TABLE t") // compile + execute try XCTAssertFalse(db.tableExists("t")) } } func testDropVirtualTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } } func testObservedDropVirtualTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) let dropStatement = try db.makeStatement(sql: "DROP TABLE t") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.tableExists("t")) } } func testDropView() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) try db.execute(sql: "DROP VIEW v") // compile + execute try XCTAssertFalse(db.viewExists("v")) } } func testObservedDropView() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) try db.execute(sql: "DROP VIEW v") // compile + execute try XCTAssertFalse(db.viewExists("v")) } } func testDropViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } } func testObservedDropViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } } func testDropTemporaryView() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) try db.execute(sql: "DROP VIEW v") // compile + execute try XCTAssertFalse(db.viewExists("v")) } } func testObservedDropTemporaryView() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) try db.execute(sql: "DROP VIEW v") // compile + execute try XCTAssertFalse(db.viewExists("v")) } } func testDropTemporaryViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } } func testObservedDropTemporaryViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute(sql: "INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.viewExists("v")) let dropStatement = try db.makeStatement(sql: "DROP VIEW v") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.viewExists("v")) } } func testDropIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) try db.execute(sql: "DROP INDEX i") // compile + execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testObservedDropIndex() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) try db.execute(sql: "DROP INDEX i") // compile + execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testDropIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testObservedDropIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testDropTemporaryIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) try db.execute(sql: "DROP INDEX i") // compile + execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testObservedDropTemporaryIndex() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) try db.execute(sql: "DROP INDEX i") // compile + execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testDropTemporaryIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testObservedDropTemporaryIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TEMPORARY TABLE t(a)") try db.execute(sql: "CREATE INDEX i ON t(a)") try db.execute(sql: "INSERT INTO t VALUES (1)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) let dropStatement = try db.makeStatement(sql: "DROP INDEX i") // compile... try dropStatement.execute() // ... then execute try XCTAssertTrue(db.indexes(on: "t").isEmpty) } } func testDropTrigger() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) try db.execute(sql: "DROP TRIGGER r") // compile + execute try XCTAssertFalse(db.triggerExists("r")) } } func testObservedDropTrigger() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) try db.execute(sql: "DROP TRIGGER r") // compile + execute try XCTAssertFalse(db.triggerExists("r")) } } func testDropTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } } func testObservedDropTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } } func testDropTemporaryTrigger() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) try db.execute(sql: "DROP TRIGGER r") // compile + execute try XCTAssertFalse(db.triggerExists("r")) } } func testObservedDropTemporaryTrigger() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) try db.execute(sql: "DROP TRIGGER r") // compile + execute try XCTAssertFalse(db.triggerExists("r")) } } func testDropTemporaryTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } } func testObservedDropTemporaryTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") try db.execute(sql: "CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) let dropStatement = try db.makeStatement(sql: "DROP TRIGGER r") // compile... try dropStatement.execute() // ... then execute try XCTAssertFalse(db.triggerExists("r")) } } }
mit
54987cfbe7872a3076816c617b232ce7
44.258268
98
0.606528
4.712084
false
true
false
false
roecrew/AudioKit
AudioKit/Common/Nodes/Effects/Reverb/Comb Filter Reverb/AKCombFilterReverb.swift
1
4747
// // AKCombFilterReverb.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This filter reiterates input with an echo density determined by /// loopDuration. The attenuation rate is independent and is determined by /// reverbDuration, the reverberation duration (defined as the time in seconds /// for a signal to decay to 1/1000, or 60dB down from its original amplitude). /// Output from a comb filter will appear only after loopDuration seconds. /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). /// - loopDuration: The loop time of the filter, in seconds. This can also be thought of as the delay time. Determines frequency response curve, loopDuration * sr/2 peaks spaced evenly between 0 and sr/2. /// public class AKCombFilterReverb: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKCombFilterReverbAudioUnit? internal var token: AUParameterObserverToken? private var reverbDurationParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). public var reverbDuration: Double = 1.0 { willSet { if reverbDuration != newValue { if internalAU!.isSetUp() { reverbDurationParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.reverbDuration = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The time in seconds for a signal to decay to 1/1000, or 60dB from its original amplitude. (aka RT-60). /// - loopDuration: The loop time of the filter, in seconds. This can also be thought of as the delay time. Determines frequency response curve, loopDuration * sr/2 peaks spaced evenly between 0 and sr/2. /// public init( _ input: AKNode, reverbDuration: Double = 1.0, loopDuration: Double = 0.1) { self.reverbDuration = reverbDuration var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = fourCC("comb") description.componentManufacturer = fourCC("AuKt") description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKCombFilterReverbAudioUnit.self, asComponentDescription: description, name: "Local AKCombFilterReverb", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKCombFilterReverbAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) self.internalAU!.setLoopDuration(Float(loopDuration)) } guard let tree = internalAU?.parameterTree else { return } reverbDurationParameter = tree.valueForKey("reverbDuration") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.reverbDurationParameter!.address { self.reverbDuration = Double(value) } } } internalAU?.reverbDuration = Float(reverbDuration) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
71c5638b6fd36bddd15450b81a001355
35.515385
210
0.64546
5.245304
false
false
false
false
xylxi/SLMenuView
SLMenuViewDemo/SLMenuViewDemo/SLMenuView.swift
2
9066
// // SLMenuView.swift // SLMenu // // Created by WangZHW on 16/5/5. // Copyright © 2016年 RobuSoft. All rights reserved. // import UIKit public enum CLMenuDirection { case up,down } public class CLItem { public typealias hClosure = (item: CLItem) -> Void let title: String let imageName: String? let handler: hClosure? public init(title: String,imageName: String? = nil , handler:hClosure?) { self.title = title self.imageName = imageName self.handler = handler } } public struct MenuConfig { // menu背景颜色 let bgColor: UIColor // 添加路径的颜色 let rectColor: UIColor // item分割线颜色 let separateColor: UIColor // 按钮颜色 let titleColor: UIColor // 圆角半径 let radius: CGFloat // 三角形的边长 let arrowLength: CGFloat // 按钮的高度 let itemHeight: CGFloat // 图片和文字的距离 // public let imagetitleSpace: CGFloat // 菜单的宽带 let menuWidth: CGFloat // 箭头的的x对于width的百分比 let percentage: CGFloat public init(bgColor: UIColor, rectColor: UIColor, separateColor: UIColor, titleColor: UIColor, radius: CGFloat, arrowLength: CGFloat, itemHeight: CGFloat, imagetitleSpace: CGFloat, menuWidth: CGFloat, percentage: CGFloat = CGFloat(5) / CGFloat(6)) { self.bgColor = bgColor self.rectColor = rectColor self.separateColor = separateColor self.titleColor = titleColor self.radius = radius self.arrowLength = arrowLength self.itemHeight = itemHeight // self.imagetitleSpace = imagetitleSpace self.menuWidth = menuWidth self.percentage = percentage } } public class MeunView: UIView,ShowDelegate { public weak var delegate : DisPlay? let config : MenuConfig let items : [CLItem] let direction: CLMenuDirection // 箭头的位置 let point : CGPoint public init(items: [CLItem], direction: CLMenuDirection = .up, point: CGPoint, config: MenuConfig? = nil) { self.items = items self.direction = direction self.point = point let bgColor = UIColor(red: CGFloat(204)/CGFloat(255), green: CGFloat(204)/CGFloat(255), blue: CGFloat(204)/CGFloat(255), alpha: 0.2) let separateColor = UIColor(red: CGFloat(179)/CGFloat(255), green: CGFloat(180)/CGFloat(255), blue: CGFloat(210)/CGFloat(255), alpha: 1.0) self.config = config ?? MenuConfig(bgColor: bgColor, rectColor: UIColor.whiteColor(), separateColor: separateColor, titleColor: UIColor.blackColor(),radius: 5,arrowLength: 6, itemHeight: 44,imagetitleSpace: 10, menuWidth: 150) // 计算高 let h = CGFloat(items.count) * (self.config.itemHeight + 0.5) + CGFloat(self.config.arrowLength * pow(3, 0.5)) + self.config.radius // 计算宽 let w = self.config.menuWidth + self.config.radius * 2 var x: CGFloat = 0 var y: CGFloat = 0 // 调整point switch self.direction { case .up: x = point.x - self.config.menuWidth * self.config.percentage y = point.y case .down: x = point.x - self.config.menuWidth * self.config.percentage y = point.y - h } let rect = CGRectMake(x, y, w, h); super.init(frame: rect) self.backgroundColor = UIColor.clearColor() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func drawRect(rect: CGRect) { // 设置颜色 self.config.rectColor.set() // 设置三角 let offX = rect.width * self.config.percentage var offY = CGFloat(0) switch self.direction { case .up: offY = rect.origin.y case .down: offY = rect.origin.y + rect.height - self.config.arrowLength * pow(3, 0.5) } let xl = offX - self.config.arrowLength let xr = offX + self.config.arrowLength let yt = offY let yd = offY + self.config.arrowLength * pow(3, 0.5) var pointl:CGPoint,pointr:CGPoint,pointh:CGPoint switch self.direction { case .up: pointl = CGPoint(x: xl, y: yd) pointr = CGPoint(x: xr, y: yd) pointh = CGPoint(x: xl + self.config.arrowLength, y: yt) case .down: pointl = CGPoint(x: xl, y: yt) pointr = CGPoint(x: xr, y: yt) pointh = CGPoint(x: xl + self.config.arrowLength, y: yd) } let arrowPath = UIBezierPath() arrowPath.moveToPoint(pointl) arrowPath.addLineToPoint(pointh) arrowPath.addLineToPoint(pointr) arrowPath.closePath() arrowPath.fill() var roundRect: CGRect switch self.direction { case .up: roundRect = CGRectMake(0, yd, rect.width, rect.height - yd) default: roundRect = CGRectMake(0, 0, rect.width, rect.height - self.config.arrowLength * pow(3, 0.5)) } let roundPath = UIBezierPath(roundedRect: roundRect, cornerRadius: self.config.radius) roundPath.addClip() roundPath.fill() } private var bc = [UIButton : CLItem]() override public func layoutSubviews() { let margin1 = self.config.arrowLength * pow(3, 0.5) let margin2 = self.config.radius / 2 var starty = margin2 let startx = margin2 if self.direction == .up { starty += margin1 } for (index, item) in self.items.enumerate() { // 按钮 let btn = SLButton(type: .Custom) btn.addTarget(self, action: #selector(MeunView.click(_:)), forControlEvents: .TouchUpInside) btn.frame = CGRectMake(startx, starty, self.config.menuWidth, self.config.itemHeight) btn.setTitle(item.title, forState: .Normal) btn.setTitleColor(self.config.titleColor, forState: .Normal) if let name = item.imageName { btn.setImage(UIImage(named: name), forState: .Normal) btn.setImage(UIImage(named: name), forState: .Highlighted) } self.addSubview(btn) // btn.addSpace(self.config.imagetitleSpace) starty = CGRectGetMaxY(btn.frame) // 分割线 if index != self.items.count - 1 { let v = UIImageView(image: UIImage.imageWithColor(self.config.separateColor)) v.frame = CGRectMake(0, starty, self.bounds.width, 0.5) self.addSubview(v) starty += 0.5 } self.bc[btn] = item } } func click(sender: UIButton) { if let item = self.bc[sender] { item.handler?(item: item) } delegate?.dismiss() } public func show() { // 自定义显示和隐藏动画 let s: ShowAnimalClosure = {[weak self] v in self?.alpha = 0.0 UIView.animateWithDuration(0.33, animations: { self?.alpha = 1.0 }) } let d: DismissAimalClosure = {[weak self] v , time in self?.alpha = 1.0 UIView.animateWithDuration(time, animations: { self?.alpha = 0.0 v?.alpha = 0.0 }, completion: { (finish) in v?.removeFromSuperview() }) } let showView = SLShowView(addView: self, height: self.bounds.height, position: .Custom(s,d), needVisua: false) showView.show() } } class SLButton: UIButton { let scale: CGFloat = 1.0 / 3.0 override func imageRectForContentRect(contentRect: CGRect) -> CGRect { return CGRectMake(0, 0, contentRect.width * scale, contentRect.height) } override func titleRectForContentRect(contentRect: CGRect) -> CGRect { return CGRectMake(contentRect.width * scale, 0, contentRect.width * (1 - scale), contentRect.height) } override init(frame: CGRect) { super.init(frame: frame) self.imageView?.contentMode = .Center self.titleLabel?.textAlignment = .Left } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension UIImage { class func imageWithColor(color: UIColor) ->UIImage{ let rect = CGRectMake(0, 0, 1, 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let theImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return theImage } }
mit
c67f9457bb18ed40e8eccc0d75bbd97a
33.003831
253
0.583775
4.158857
false
true
false
false
onevcat/CotEditor
CotEditor/Sources/MultipleReplacement+TextView.swift
1
6047
// // MultipleReplacement+TextView.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-03-26. // // --------------------------------------------------------------------------- // // © 2018-2022 1024jp // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import AppKit extension MultipleReplacement { /// highlight all matches in the textView func highlight(inSelection: Bool, completionHandler: @escaping (_ resultMessage: String) -> Void) { guard let textView = TextFinder.shared.client else { return NSSound.beep() } let string = textView.string.immutable let selectedRanges = textView.selectedRanges.map(\.rangeValue) textView.isEditable = false // setup progress sheet let progress = TextFindProgress(format: .find) let closesAutomatically = UserDefaults.standard[.findClosesIndicatorWhenDone] let indicator = NSStoryboard(name: "ProgressView").instantiateInitialController { (coder) in ProgressViewController(coder: coder, progress: progress, message: "Highlight".localized, closesAutomatically: closesAutomatically) }! textView.viewControllerForSheet?.presentAsSheet(indicator) DispatchQueue.global(qos: .userInitiated).async { [weak self] in guard let self = self else { return } let result = self.find(string: string, ranges: selectedRanges, inSelection: inSelection) { (stop) in guard !progress.isCancelled else { stop = true return } progress.completedUnitCount += 1 } DispatchQueue.main.async { textView.isEditable = true guard !progress.isCancelled else { return } if !result.isEmpty { // apply to the text view if let layoutManager = textView.layoutManager { layoutManager.removeTemporaryAttribute(.backgroundColor, forCharacterRange: string.nsRange) let color = NSColor.textHighlighterColor for range in result { layoutManager.addTemporaryAttribute(.backgroundColor, value: color, forCharacterRange: range) } } } else { NSSound.beep() progress.localizedDescription = "Not Found".localized } let resultMessage = !result.isEmpty ? String(format: "%i found".localized, locale: .current, result.count) : "Not Found".localized indicator.done() completionHandler(resultMessage) } } } /// replace all matches in the textView func replaceAll(inSelection: Bool, completionHandler: @escaping (_ resultMessage: String) -> Void) { guard let textView = TextFinder.shared.client, textView.isEditable, textView.window?.attachedSheet == nil else { return NSSound.beep() } let string = textView.string.immutable let selectedRanges = textView.selectedRanges.map(\.rangeValue) textView.isEditable = false // setup progress sheet let progress = TextFindProgress(format: .replacement) let closesAutomatically = UserDefaults.standard[.findClosesIndicatorWhenDone] let indicator = NSStoryboard(name: "ProgressView").instantiateInitialController { (coder) in ProgressViewController(coder: coder, progress: progress, message: "Replace All".localized, closesAutomatically: closesAutomatically) }! textView.viewControllerForSheet?.presentAsSheet(indicator) DispatchQueue.global(qos: .userInitiated).async { [weak self] in guard let self = self else { return } let result = self.replace(string: string, ranges: selectedRanges, inSelection: inSelection) { (stop) in guard !progress.isCancelled else { stop = true return } progress.completedUnitCount += 1 } DispatchQueue.main.async { textView.isEditable = true guard !progress.isCancelled else { return } if result.count > 0 { // apply to the text view textView.replace(with: [result.string], ranges: [string.nsRange], selectedRanges: result.selectedRanges, actionName: "Replace All".localized) } else { NSSound.beep() progress.localizedDescription = "Not Found".localized } let resultMessage = (result.count > 0) ? String(format: "%i replaced".localized, locale: .current, result.count) : "Not Replaced".localized indicator.done() completionHandler(resultMessage) } } } }
apache-2.0
983b8c3305988523b918ea6cdf6476f5
38.51634
144
0.549454
5.86421
false
false
false
false
lazerwalker/storyboard-iOS
Storyboard-Example/SensorInputs/ProximitySensor.swift
1
1965
import Foundation import UIKit import Storyboard class ProximitySensor: NSObject, Input { fileprivate var device = UIDevice.current let threshold:TimeInterval var timer = Timer(); var previousState = false var hasTriggered = false var callback:((AnyObject) -> Void)? var startTime:Date = Date() init(threshold:TimeInterval = 2) { self.threshold = threshold super.init() // TODO: We probably want to have startMonitoringProximity be a thing that // the dev manually enables, but I haven't thought through what that looks // like yet startMonitoringProximity() } func startMonitoringProximity() { device.isProximityMonitoringEnabled = true timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ProximitySensor.checkProximity), userInfo: nil, repeats: true) } func stopMonitoringProximity() { device.isProximityMonitoringEnabled = false timer.invalidate() } func onChange(_ cb:@escaping InputBlock) { callback = cb if (device.proximityState) { cb(true as AnyObject) self.previousState = true } else { cb(false as AnyObject) } checkProximity() } //- @objc func checkProximity() { let currentState = device.proximityState if(currentState && !previousState) { startTime = Date() hasTriggered = false } else if (currentState && previousState && !hasTriggered && abs(startTime.timeIntervalSinceNow) >= threshold) { hasTriggered = true if let cb = callback { cb(currentState as AnyObject) } } else if (!currentState && previousState) { if let cb = callback { cb(currentState as AnyObject) } } previousState = device.proximityState; } }
mit
738fbed3c97a2e5b20d13f0eef0fc684
27.071429
152
0.60916
5.254011
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Dining/SwiftUI/Views/Venue/Detail View/MenuDisclosureGroup.swift
1
5052
// // MenuDisclosureGroup.swift // PennMobile // // Created by CHOI Jongmin on 18/1/2021. // Copyright © 2021 PennLabs. All rights reserved. // import SwiftUI struct DiningMenuSectionRow: View { @Binding var isExpanded: Bool let title: String init(isExpanded: Binding<Bool>, title: String) { self.title = title.capitalizeMainWords() self._isExpanded = isExpanded } var body: some View { HStack { Text(title) Spacer() Image(systemName: "chevron.right.circle") .rotationEffect(.degrees(isExpanded ? -90 : 90)) .frame(width: 28, alignment: .center) } .contentShape(Rectangle()) .padding(.bottom) .onTapGesture { FirebaseAnalyticsManager.shared.trackEvent(action: "Open Menu", result: title, content: "") withAnimation { isExpanded.toggle() } } } } struct DiningMenuRow: View { init (for diningMenu: DiningMenu) { self.diningMenu = diningMenu } @State var isExpanded = true let diningMenu: DiningMenu var body: some View { VStack { DiningMenuSectionRow(isExpanded: $isExpanded, title: diningMenu.mealType) .font(.system(size: 21, weight: .medium)) if isExpanded { ForEach(diningMenu.diningStations, id: \.self) { diningStation in DiningStationRow(for: diningStation) } .padding(.leading) .transition(.moveAndFade) } }.clipped() } } struct DiningStationRow: View { init (for diningStation: DiningStation) { self.diningStation = diningStation } @State var isExpanded = false let diningStation: DiningStation var body: some View { VStack { DiningMenuSectionRow(isExpanded: $isExpanded, title: diningStation.stationDescription) .font(Font.system(size: 17)) if isExpanded { ForEach(diningStation.diningStationItems, id: \.self) { diningStationItem in DiningStationItemRow(for: diningStationItem) .padding(.leading) } .transition(.moveAndFade) } }.clipped() } } struct DiningStationItemRow: View { init (for diningStationItem: DiningStationItem) { self.diningStationItem = diningStationItem } let diningStationItem: DiningStationItem var body: some View { VStack(alignment: .leading) { HStack(alignment: .center) { Text(diningStationItem.title.capitalizeMainWords()) .font(Font.system(size: 17)) ForEach(diningStationItem.tableAttribute.attributeDescriptions, id: \.self) { attribute in // Unlike UIKit, image will simply not appear if it doesn't exist in assets // Hack as image set doesn't allow slashes let description = attribute.description == "Wheat/Gluten" ? "Wheat" : attribute.description Image(description) .resizable() .scaledToFit() .frame(width: 20.0, height: 20) } Spacer() }.padding(.bottom, 3) Text(diningStationItem.description) .font(.system(size: 17, weight: .thin)) .fixedSize(horizontal: false, vertical: true) }.padding(.bottom) } } extension AnyTransition { static var moveAndFade: AnyTransition { let insertion = AnyTransition .opacity.animation(.easeInOut(duration: 0.7)) .combined(with: .move(edge: .top)).animation(.easeInOut) let removal = AnyTransition .opacity.animation(.easeInOut(duration: 0.1)) .combined(with: .move(edge: .top)).animation(.easeInOut) return .asymmetric(insertion: insertion, removal: removal) } } struct MenuDisclosureGroup_Previews: PreviewProvider { static var previews: some View { let diningVenues: DiningMenuAPIResponse = Bundle.main.decode("mock_menu.json") return NavigationView { ScrollView { VStack { DiningVenueDetailMenuView(menus: diningVenues.document.menuDocument.menus, id: 1) Spacer() } }.navigationTitle("Dining") .padding() } } } extension String { func capitalizeMainWords() -> String { let nonCaptializingSet: Set = [ "a", "an", "the", "for", "and", "nor", "but", "or", "yet", "so", "with", "at", "around", "by", "after", "along", "for", "from", "of", "on", "to", "with", "without" ] return self.split(separator: " ").map({nonCaptializingSet.contains(String($0)) ? $0.lowercased() : $0.capitalized}).joined(separator: " ") } }
mit
6319b2bed241ddd174a49f1ef19a6330
29.79878
175
0.563255
4.566908
false
false
false
false
practicalswift/swift
test/Interpreter/tuples.swift
38
1034
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test typealias Interval = (lo: Int, hi: Int) infix operator <+> infix operator <-> infix operator <+>= func <+>(a: Interval, b: Interval) -> Interval { return (a.lo + b.lo, a.hi + b.hi) } func <->(a: Interval, b: Interval) -> Interval { return (a.lo - b.hi, a.hi - b.lo) } func <+>=(a: inout Interval, b: Interval) { a.lo += b.lo a.hi += b.hi } func print(_ x: Interval) { print("(lo=\(x.lo), hi=\(x.hi))") } // CHECK: (lo=4, hi=6) print((1,2) <+> (3,4)) // CHECK: (lo=4, hi=6) print((hi:2,lo:1) <+> (lo:3,hi:4)) // CHECK: (lo=1, hi=3) print((3,4) <-> (1,2)) func mutate() { var x:Interval = (1, 2) x <+>= (3, 4) // CHECK: (lo=4, hi=6) print(x) } mutate() func printInts(_ ints: Int...) { print("\(ints.count) ints: ", terminator: "") for int in ints { print("\(int) ", terminator: "") } print("\n", terminator: "") } // CHECK: 0 ints printInts() // CHECK: 1 ints: 1 printInts(1) // CHECK: 3 ints: 1 2 3 printInts(1,2,3)
apache-2.0
90ff27f33dfac27dfbd1ee97ba415ab1
17.8
48
0.547389
2.46778
false
false
false
false
qinting513/Learning-QT
2016 Plan/5月/PictureInPicture/PipDemo/ViewController.swift
1
2033
// // ViewController.swift // PipDemo // // Created by Qinting on 16/6/5. // Copyright © 2016年 Qinting. All rights reserved. // import UIKit import AVKit import AVFoundation var currentItemStatus = "currentItem.status" var mcontext = 0 class ViewController: UIViewController,AVPictureInPictureControllerDelegate { @IBOutlet var pipView: PipVideoPlay! lazy var player:AVPlayer = { let p = AVPlayer() p.addObserver(self, forKeyPath: currentItemStatus, options: .New, context: &mcontext) return p }() override func viewDidLoad() { let u = NSBundle.mainBundle().URLForResource("video", withExtension: ".mov") let asset = AVAsset(URL: u!) let item = AVPlayerItem(asset: asset) player.replaceCurrentItemWithPlayerItem(item) pipView.pipPlayerPlay = player player.play() } var pipController : AVPictureInPictureController? override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == currentItemStatus { let statusInt = change?[NSKeyValueChangeNewKey] as? NSNumber let status = AVPlayerItemStatus(rawValue: statusInt!.integerValue) if status != .ReadyToPlay { return } pipController = AVPictureInPictureController(playerLayer: pipView.pipLayer) pipController?.delegate = self; } } func pictureInPictureControllerWillStartPictureInPicture(pictureInPictureController: AVPictureInPictureController){ print("Will Start") } func pictureInPictureControllerDidStartPictureInPicture(pictureInPictureController: AVPictureInPictureController){ print("Did Start") } func pictureInPictureController(pictureInPictureController: AVPictureInPictureController, failedToStartPictureInPictureWithError error: NSError){ print("failedToStart:%@",error) } }
apache-2.0
1a298006285c3e48edfb28c2aa1b92d4
31.741935
157
0.692611
5.356201
false
false
false
false
onebytecode/krugozor-iOSVisitors
krugozor-visitorsApp/GQLBuilder.swift
1
2032
// // GQLBuilder.swift // krugozor-visitorsApp // // Created by Alexander Danilin on 21/10/2017. // Copyright © 2017 oneByteCode. All rights reserved. // import Foundation public enum GQLErrors: String, Error { case noMethod = "ERROR: No Query Or Mutation Provided" } public struct GQLParam { let key: String! let value: String! } public struct GQLArgument { let key: String! public init(key: String!) { self.key = key } } protocol GQLBuilding { static func build () -> String } // TODO: To Test And Cover Tests /// Builds GQL Parameters For APIManager /// Version 0.0.1 /// Supports Basic Mutations and Queries class GQLBuilder { /// STEP 1: /// STEP 2: /// STEP 3: public static func build(query: Query?, mutation: Mutation?, params: [GQLParam], arguments: [GQLArgument]) throws -> String { // STEP 1 // Validation For Optonal Parameters Presence guard query != nil || mutation != nil else { throw GQLErrors.noMethod } // Main Function Return String var finalString = String() // Optional Chaining For Query if query != nil { switch query { default: finalString += query!.methodType() + query!.rawValue }} // Optional Chaining For Mutation if mutation != nil { switch mutation { default: finalString += mutation!.methodType() + mutation!.rawValue} } // STEP 2 finalString += "(" for param in params { if param.value != nil { finalString += param.key finalString += ":" finalString += ("\u{22}\(param.value!)\u{22}") finalString += "," } } finalString = String(finalString.characters.dropLast()) finalString += "){" // STEP 3 finalString += "\n" for argument in arguments { finalString += argument.key; finalString += "\n" } finalString += "}}" return finalString } }
apache-2.0
7ca9f54a848ebd31f112212179d47f82
25.038462
129
0.578533
4.424837
false
false
false
false
ormaa/Bluetooth-LE-IOS-Swift
Central Manager/SharedCode/BLE Stack/BLE_Connection.swift
1
4211
// // BLECentralManager+Connect.swift // BlueToothCentral // // Created by Olivier Robin on 07/11/2016. // Copyright © 2016 fr.ormaa. All rights reserved. // import Foundation //import UIKit import CoreBluetooth extension BLECentralManager { // Connect to a peripheral, listed in the peripherals list // func connectToAsync(serviceUUID: String) { //centralManager?.stopScan() bleError = "" if peripherals.count > 0 { for i in 0...peripherals.count - 1 { let n = getPeripheralUUID(number: i) print(n) if n == serviceUUID { connect(peripheral: peripherals[i]) } } } } // Connect to a peripheral // func connect(peripheral: CBPeripheral?) { //stopBLEScan() log("connect to peripheral \(peripheral?.identifier)") if (peripheral != nil) { peripheralConnecting = peripheral peripheralConnected = nil let options = [CBConnectPeripheralOptionNotifyOnConnectionKey: true as AnyObject, CBConnectPeripheralOptionNotifyOnDisconnectionKey: true as AnyObject, CBConnectPeripheralOptionNotifyOnNotificationKey: true as AnyObject, CBCentralManagerRestoredStatePeripheralsKey: true as AnyObject, CBCentralManagerRestoredStateScanServicesKey : true as AnyObject] peripheral?.delegate = self centralManager?.connect(peripheral!, options: options) } } // disconnect from a connected peripheral // func disconnect() { log( "disconnect peripheral") if peripheralConnecting != nil { centralManager?.cancelPeripheralConnection(peripheralConnecting!) } } // delegate // // Connected to a peripheral // func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral){ if peripheral.name != nil { log("didConnect event, peripheral: " + peripheral.name!) } else { log("didConnect event, peripheral identifier: " + peripheral.identifier.uuidString) } peripheralConnected = peripheral var name = "nil" if peripheral.name != nil { name = peripheral.name! } bleDelegate?.connected(message: name) } // delegate // Fail to connect // func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { if error != nil { bleError = ("Error didFailToConnect : \(error!.localizedDescription)") log(bleError) bleDelegate?.failConnected(message: error!.localizedDescription) } else { log("didFailToConnect") bleDelegate?.failConnected(message: "") } } // delegate // // disconnected form a peripheral // func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { if error != nil { bleError = ("Error didDisconnectPeripheral : \(error!.localizedDescription)") log(bleError) bleDelegate?.disconnected(message: error!.localizedDescription) } else { log("didDisconnectPeripheral") bleDelegate?.disconnected(message: "") } } // delegate // Called when connection is lost, or done again // func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { log("peripheral service modified. May be connection is lost !") for s in invalidatedServices { log("service: " + s.uuid.uuidString) } } // delegate // name of the device update // func peripheralDidUpdateName(_ peripheral: CBPeripheral) { log("peripheral name has change : " + peripheral.name!) } }
mit
76701cdbbfb0f0142eac87ec550a5ab9
26.51634
119
0.578622
5.620828
false
false
false
false
bencochran/LLVM.swift
LLVM/Module.swift
1
2136
// // Created by Ben Cochran on 11/12/15. // Copyright © 2015 Ben Cochran. All rights reserved. // import Foundation public class Module { internal let ref: LLVMModuleRef public init(name: String, context: Context) { ref = LLVMModuleCreateWithNameInContext(name, context.ref) } deinit { LLVMDisposeModule(ref) } public var string: String? { let charStar = LLVMPrintModuleToString(ref) defer { LLVMDisposeMessage(charStar) } return String.fromCString(charStar) } public var dataLayout: String { get { return String.fromCString(LLVMGetDataLayout(ref))! } set { LLVMSetDataLayout(ref, dataLayout) } } public var target: String { get { return String.fromCString(LLVMGetTarget(ref))! } set { LLVMSetTarget(ref, target) } } // TODO: LLVMSetModuleInlineAsm public var context: Context { return Context(ref: LLVMGetModuleContext(ref), managed: false) } public func typeByName(name: String) -> TypeType? { let typeRef = LLVMGetTypeByName(ref, name) if typeRef == nil { return .None } return AnyType(ref: typeRef) } public func functionByName(name: String) -> Function? { let funcRef = LLVMGetNamedFunction(ref, name) if funcRef == nil { return .None } return Function(ref: funcRef) } // true = valid, false = invalid (opposite of LLVM’s whacky status) public func verify() -> Bool { return LLVMVerifyModule(ref, LLVMReturnStatusAction, nil) == 0 } public var functions: AnyGenerator<Function> { var previousRef: LLVMValueRef? return anyGenerator { let ref: LLVMValueRef if let previous = previousRef { ref = LLVMGetNextFunction(previous) } else { ref = LLVMGetFirstFunction(self.ref) } previousRef = ref return ref != nil ? Function(ref: ref) : nil } } }
mit
4037407d439b2e2937446beb5fa51c95
26
71
0.58181
4.379877
false
false
false
false
Vadimkomis/Myclok
Pods/Auth0/Auth0/NSURLComponents+OAuth2.swift
2
1843
// NSURLComponents+OAuth2.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // 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 extension URLComponents { var a0_fragmentValues: [String: String] { var dict: [String: String] = [:] let items = fragment?.components(separatedBy: "&") items?.forEach { item in let parts = item.components(separatedBy: "=") guard parts.count == 2, let key = parts.first, let value = parts.last else { return } dict[key] = value } return dict } var a0_queryValues: [String: String] { var dict: [String: String] = [:] self.queryItems?.forEach { dict[$0.name] = $0.value } return dict } }
mit
2adb3d2050482710aabeb3bc586dc29a
39.065217
80
0.669018
4.46247
false
false
false
false
argent-os/argent-ios
app-ios/AuthViewControllerStepThree.swift
1
3871
// // AuthViewControllerStepThree.swift // app-ios // // Created by Sinan Ulkuatam on 8/1/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import UIKit import Spring class AuthViewControllerStepThree: UIPageViewController, UIPageViewControllerDelegate { let lbl = UILabel() let lblDetail = SpringLabel() let lblBody = SpringLabel() let imageView = UIImageView() override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLoad() { super.viewDidLoad() // Border radius on uiview configureView() } func configureView() { // screen width and height: let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height self.view.backgroundColor = UIColor.whiteColor() let imageName = "BackgroundCoffeeTouchID" let image = UIImage(named: imageName) imageView.image = image imageView.contentMode = .ScaleAspectFill imageView.layer.masksToBounds = true imageView.tag = 7577 imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight*0.5) imageView.frame.origin.y = 0 self.view.addSubview(imageView) // Set range of string length to exactly 8, the number of characters lblDetail.frame = CGRect(x: 0, y: screenHeight*0.5+20, width: screenWidth, height: 40) lblDetail.tag = 7579 lblDetail.textAlignment = NSTextAlignment.Center lblDetail.textColor = UIColor.whiteColor() lblDetail.adjustAttributedString("SEARCH & PAY", spacing: 2, fontName: "SFUIText-SemiBold", fontSize: 13, fontColor: UIColor.darkBlue().colorWithAlphaComponent(0.75)) // Set range of string length to exactly 8, the number of characters lblBody.frame = CGRect(x: 20, y: screenHeight*0.5+20, width: screenWidth-40, height: 170) lblBody.numberOfLines = 0 lblBody.alpha = 0.9 let atrString = adjustAttributedString("Search and pay instantly with either Apple Pay, ACH, credit, or debit card.", spacing: 1, fontName: "SFUIText-Light", fontSize: 14, fontColor: UIColor.darkBlue(), lineSpacing: 9.0, alignment: .Center) lblBody.attributedText = atrString lblBody.tag = 7579 lblBody.textAlignment = NSTextAlignment.Center // iphone6+ check if self.view.layer.frame.height > 667.0 { lblBody.frame = CGRect(x: 90, y: 280, width: screenWidth-180, height: 200) lblDetail.frame = CGRect(x: 0, y: 290, width: screenWidth, height: 40) } else if self.view.layer.frame.height <= 480.0 { lblBody.frame = CGRect(x: 90, y: 235, width: screenWidth-180, height: 200) lblDetail.frame = CGRect(x: 0, y: 250, width: screenWidth, height: 40) } } //Changing Status Bar override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func viewDidAppear(animated: Bool) { lblDetail.animation = "fadeInUp" lblDetail.duration = 1 lblDetail.animate() addSubviewWithFade(lblDetail, parentView: self, duration: 0.3) lblBody.animation = "fadeInUp" lblBody.duration = 1.2 lblBody.animate() addSubviewWithFade(lblBody, parentView: self, duration: 0.3) } override func viewWillDisappear(animated: Bool) { lblDetail.animation = "fadeInUp" lblDetail.duration = 3 lblDetail.animateTo() lblBody.animation = "fadeInUp" lblBody.duration = 1 lblBody.animateTo() } }
mit
76cebebf8a0f55692961ac07311c8434
35.168224
248
0.637984
4.690909
false
false
false
false
ddralves/json_test
json_test/json_test/User.swift
1
1603
// // User.swift // json_test // // Created by Dino Alves on 2017/03/30. // Copyright © 2017 Dino Alves. All rights reserved. // import Foundation // Model used to represent each user class User { var id: Int? // Unique ID representing the user. Optional as this cannot not be defaulted var name: String = "User's name not supplied!" // Name of the user var username: String = "Username not supplied!" // Username of the user var email: String = "No e-mail supplied!" // E-mail address of user var address = Address() // User's physical address var phone: String = "No phone number supplied!" // User's phone number var website: String = "Website link not supplied!" // User's website link var company = Company() // User's associated company /** Default init */ init() { // Do nothing } /** Inits - paramters: - id: Unique user ID - name: User's name - username: Username of the user - email: E-mail address of user - address: User's physical address - phone: User's phone number - website: User's website link - company: User's associated company */ init(id: Int, name: String, username: String, email: String, address: Address, phone: String, website: String, company: Company) { self.id = id self.name = name self.username = username self.email = email self.address = address self.phone = phone self.website = website self.company = company } }
mit
012a5b0570af9222aad88ecd3cb073d1
28.666667
93
0.601748
4.294906
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/GRMustache.swift/Mustache/Rendering/MustacheBox.swift
1
10834
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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 /** Mustache templates don't eat raw values: they eat values boxed in `MustacheBox`. To box something in a `MustacheBox`, you use one variant of the `Box()` function. It comes in several variants so that nearly anything can be boxed and feed templates: - Basic Swift values: `template.render(Box("foo"))` - Dictionaries & collections: template.render(Box(["numbers": [1,2,3]])) - Custom types via the `MustacheBoxable` protocol: extension User: MustacheBoxable { ... } template.render(Box(user)) - Functions such as `FilterFunction`, `RenderFunction`, `WillRenderFunction` and `DidRenderFunction`: let square = Filter { (x?: Int, _) in Box(x! * x!) } template.registerInBaseContext("square", Box(square)) Warning: the fact that `MustacheBox` is a subclass of NSObject is an implementation detail that is enforced by the Swift 1.2 language itself. This may change in the future: do not rely on it. */ public class MustacheBox : NSObject { // IMPLEMENTATION NOTE // // Why is MustacheBox a subclass of NSObject, and not, say, a Swift struct? // // Swift does not allow a class extension to override a method that is // inherited from an extension to its superclass and incompatible with // Objective-C. // // If MustacheBox were a pure Swift type, this Swift limit would prevent // NSObject subclasses such as NSNull, NSNumber, etc. to override // MustacheBoxable.mustacheBox, and provide custom rendering behavior. // // For an example of this limitation, see example below: // // import Foundation // // // A type that is not compatible with Objective-C // struct MustacheBox { } // // // So far so good // extension NSObject { // var mustacheBox: MustacheBox { return MustacheBox() } // } // // // Error: declarations in extensions cannot override yet // extension NSNull { // override var mustacheBox: MustacheBox { return MustacheBox() } // } // // This problem does not apply to Objc-C compatible protocols: // // import Foundation // // // So far so good // extension NSObject { // var prop: String { return "NSObject" } // } // // // No error // extension NSNull { // override var prop: String { return "NSNull" } // } // // NSObject().prop // "NSObject" // NSNull().prop // "NSNull" // // In order to let the user easily override NSObject.mustacheBox, we had to // keep its return type compatible with Objective-C, that is to say make // MustacheBox a subclass of NSObject. // ------------------------------------------------------------------------- // MARK: - The boxed value /// The boxed value. public let value: Any? /// The only empty box is `Box()`. public let isEmpty: Bool /** The boolean value of the box. It tells whether the Box should trigger or prevent the rendering of regular `{{#section}}...{{/}}` and inverted `{{^section}}...{{/}}`. */ public let boolValue: Bool /** If the boxed value can be iterated (Swift collection, NSArray, NSSet, etc.), returns an array of `MustacheBox`. */ public var arrayValue: [MustacheBox]? { return converter?.arrayValue() } /** If the boxed value is a dictionary (Swift dictionary, NSDictionary, etc.), returns a dictionary `[String: MustacheBox]`. */ public var dictionaryValue: [String: MustacheBox]? { return converter?.dictionaryValue() } /** Extracts a key out of a box. let box = Box(["firstName": "Arthur"]) box["firstName"].value // "Arthur" :param: key A key :returns: the MustacheBox for this key. */ public subscript (key: String) -> MustacheBox { return keyedSubscript?(key: key) ?? Box() } // ------------------------------------------------------------------------- // MARK: - Other facets /// See the documentation of `RenderFunction`. public private(set) var render: RenderFunction /// See the documentation of `FilterFunction`. public let filter: FilterFunction? /// See the documentation of `WillRenderFunction`. public let willRender: WillRenderFunction? /// See the documentation of `DidRenderFunction`. public let didRender: DidRenderFunction? // ------------------------------------------------------------------------- // MARK: - Internal let keyedSubscript: KeyedSubscriptFunction? let converter: Converter? init( boolValue: Bool? = nil, value: Any? = nil, converter: Converter? = nil, keyedSubscript: KeyedSubscriptFunction? = nil, filter: FilterFunction? = nil, render: RenderFunction? = nil, willRender: WillRenderFunction? = nil, didRender: DidRenderFunction? = nil) { let empty = (value == nil) && (keyedSubscript == nil) && (render == nil) && (filter == nil) && (willRender == nil) && (didRender == nil) self.isEmpty = empty self.value = value self.converter = converter self.boolValue = boolValue ?? !empty self.keyedSubscript = keyedSubscript self.filter = filter self.willRender = willRender self.didRender = didRender if let render = render { self.render = render super.init() } else { // The default render function: it renders {{variable}} tags as the // boxed value, and {{#section}}...{{/}} tags by adding the box to // the context stack. // // IMPLEMENTATIN NOTE // // We have to set self.render twice in order to avoid the compiler // error: "variable 'self.render' captured by a closure before being // initialized" // // Despite this message, the `self` "captured" in the second closure // is the one whose `render` property contains that same second // closure: everything works as if no value was actually captured. self.render = { (_, _) in return nil } super.init() self.render = { (info: RenderingInfo, error: NSErrorPointer) in switch info.tag.type { case .Variable: // {{ box }} if let value = value { return Rendering("\(value)") } else { return Rendering("") } case .Section: // {{# box }}...{{/ box }} let context = info.context.extendedContext(self) return info.tag.render(context, error: error) } } } } // Converter wraps all the conversion closures that help MustacheBox expose // its raw value (typed Any) as useful types such as Int, Double, etc. // // Without those conversions, it would be very difficult for the library // user to write code that processes, for example, a boxed number: she // would have to try casting the boxed value to Int, UInt, Double, NSNumber // etc. until she finds its actual type. struct Converter { let arrayValue: (() -> [MustacheBox]?) let dictionaryValue: (() -> [String: MustacheBox]?) init( @autoclosure(escaping) arrayValue: () -> [MustacheBox]? = nil, @autoclosure(escaping) dictionaryValue: () -> [String: MustacheBox]? = nil) { self.arrayValue = arrayValue self.dictionaryValue = dictionaryValue } // IMPLEMENTATION NOTE // // It looks like Swift does not provide any way to perform a safe // conversion between its numeric types. // // For example, there exists a UInt(Int) initializer, but it fails // with EXC_BAD_INSTRUCTION when given a negative Int. // // So we implement below our own numeric conversion functions. static func uint(x: Int) -> UInt? { if x >= 0 { return UInt(x) } else { return nil } } static func uint(x: Double) -> UInt? { if x == Double(UInt.max) { return UInt.max } else if x >= 0 && x < Double(UInt.max) { return UInt(x) } else { return nil } } static func int(x: UInt) -> Int? { if x <= UInt(Int.max) { return Int(x) } else { return nil } } static func int(x: Double) -> Int? { if x == Double(Int.max) { return Int.max } else if x >= Double(Int.min) && x < Double(Int.max) { return Int(x) } else { return nil } } } } extension MustacheBox : DebugPrintable { /// A textual representation of `self`, suitable for debugging. public override var debugDescription: String { if let value = value { return "MustacheBox(\(value))" // remove "Optional" from the output } else { return "MustacheBox(nil)" } } }
mit
1c4a069e0e50b6279320b4804df5e98b
33.610224
144
0.564202
4.917385
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01927-swift-type-walk.swift
1
674
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class c { func a: c == { typealias e == F>(mx : S.c> : Any) { } } var d = true } (self.E var f = c, self.init() -> String { override func g<T.advance(" protocol a { protocol a { protocol c { } }(f, V>? = g() { let foo as [".b { func a<T, length: A, f: a { func a" class A : a
apache-2.0
c61eea796224814e04cc2aa1518ce6c0
24.923077
79
0.667656
3.12037
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/View Collection/ConversationView/QConversationCollectionView+chatCellDelegate.swift
1
9861
// // QConversationCollectionView+chatCellDelegate.swift // Qiscus // // Created by Ahmad Athaullah on 16/12/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import UIKit import AVFoundation import SwiftyJSON extension QConversationCollectionView: QCellCarouselDelegate{ public func cellCarousel(carouselCell: QCellCarousel, didTapCard card: QCard) { self.cellDelegate?.cellDelegate?(didTapCard: card) } public func cellCarousel(carouselCell: QCellCarousel, didTapAction action: QCardAction) { self.cellDelegate?.cellDelegate?(didTapCardAction: action) } } extension QConversationCollectionView: ChatCellDelegate, ChatCellAudioDelegate { public func enableReplyMenuItem(onCell cell:QChatCell)->Bool { guard let comment = cell.comment else {return true} if let config = self.configDelegate?.configDelegate?(enableReplyMenuItem: self, forComment: comment){ return config } return true } public func enableForwardMenuItem(onCell cell:QChatCell)->Bool { guard let comment = cell.comment else {return true} if let config = self.configDelegate?.configDelegate?(enableForwardMenuItem: self, forComment: comment){ return config } return true } public func enableResendMenuItem(onCell cell:QChatCell)->Bool { guard let comment = cell.comment else {return true} if let config = self.configDelegate?.configDelegate?(enableResendMenuItem: self, forComment: comment){ return config } return true } public func enableDeleteMenuItem(onCell cell:QChatCell)->Bool { guard let comment = cell.comment else {return true} if let config = self.configDelegate?.configDelegate?(enableDeleteMenuItem: self, forComment: comment){ return config } return true } public func enableDeleteForMeMenuItem(onCell cell:QChatCell)->Bool { guard let comment = cell.comment else {return true} if let config = self.configDelegate?.configDelegate?(enableDeleteForMeMenuItem: self, forComment: comment){ return config } return true } public func enableShareMenuItem(onCell cell:QChatCell)->Bool { guard let comment = cell.comment else {return true} if let config = self.configDelegate?.configDelegate?(enableShareMenuItem: self, forComment: comment){ return config } return true } public func enableInfoMenuItem(onCell cell:QChatCell)->Bool { guard let comment = cell.comment else {return true} if let config = self.configDelegate?.configDelegate?(enableInfoMenuItem: self, forComment: comment){ return config } return true } public func deletedMessageText(selfMessage isSelf:Bool)->String { if let config = self.configDelegate?.configDelegate?(deletedMessageText: self, selfMessage: isSelf){ return config }else if isSelf { return "🚫 You deleted this message." }else{ return "🚫 This message was deleted." } } public func willDeleteComment(onIndexPath indexPath: IndexPath) { } public func didDeleteComment(onIndexPath indexPath: IndexPath) { var hardDelete = true if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self){ hardDelete = !softDelete } if hardDelete { self.refreshData() }else{ self.reloadItems(at: [indexPath]) } } public func useSoftDelete() -> Bool { if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self) { return softDelete } return false } public func getInfo(comment: QComment) { self.cellDelegate?.cellDelegate?(didTapInfoOnComment: comment) } public func didForward(comment: QComment) { self.cellDelegate?.cellDelegate?(didTapForwardOnComment: comment) } public func didReply(comment: QComment) { self.cellDelegate?.cellDelegate?(didTapReplyOnComment: comment) } public func didShare(comment: QComment) { self.cellDelegate?.cellDelegate?(didTapShareOnComment: comment) } public func didTapAccountLinking(onComment comment: QComment) { self.cellDelegate?.cellDelegate?(didTapAccountLinking: comment) } public func didTapCardButton(onComment comment: QComment, index: Int) { self.cellDelegate?.cellDelegate?(didTapCardButton: comment, buttonIndex: index) } public func didTapPostbackButton(onComment comment: QComment, index: Int) { self.cellDelegate?.cellDelegate?(didTapPostbackButton: comment, buttonIndex: index) } public func didTouchLink(onComment comment: QComment) { if comment.type == .reply{ let replyData = JSON(parseJSON: comment.data) let commentId = replyData["replied_comment_id"].intValue if let targetComment = QComment.comment(withId: commentId){ self.scrollToComment(comment: targetComment) } self.cellDelegate?.cellDelegate?(didTapCommentLink: comment) } } public func didTapCell(onComment comment: QComment){ self.cellDelegate?.cellDelegate?(didTapMediaCell: comment) } public func didTapSaveContact(onComment comment: QComment) { self.cellDelegate?.cellDelegate?(didTapSaveContact: comment) } public func didTapFile(comment: QComment) { if let file = comment.file { if file.ext == "doc" || file.ext == "docx" || file.ext == "ppt" || file.ext == "pptx" || file.ext == "xls" || file.ext == "xlsx" || file.ext == "txt" { self.cellDelegate?.cellDelegate?(didTapKnownFile: comment, room: self.room!) } else if file.ext == "pdf" || file.ext == "pdf_" { if QFileManager.isFileExist(inLocalPath: file.localPath){ self.cellDelegate?.cellDelegate?(didTapDocumentFile: comment, room: self.room!) } } else{ self.cellDelegate?.cellDelegate?(didTapUnknownFile: comment, room: self.room!) } } } // MARK: ChatCellAudioDelegate func didTapPlayButton(_ button: UIButton, onCell cell: QCellAudio) { if let file = cell.comment?.file { if let url = URL(string: file.localPath) { if audioPlayer != nil { if audioPlayer!.isPlaying { if let activeCell = activeAudioCell{ DispatchQueue.main.async { autoreleasepool{ if let targetCell = activeCell as? QCellAudioRight{ targetCell.isPlaying = false } if let targetCell = activeCell as? QCellAudioLeft{ targetCell.isPlaying = false } activeCell.comment?.updatePlaying(playing: false) }} } audioPlayer?.stop() stopAudioTimer() updateAudioDisplay() } } activeAudioCell = cell do { audioPlayer = try AVAudioPlayer(contentsOf: url) } catch let error as NSError { Qiscus.printLog(text: error.localizedDescription) } audioPlayer?.delegate = self audioPlayer?.currentTime = Double(cell.comment!.currentTimeSlider) do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) //Qiscus.printLog(text: "AVAudioSession Category Playback OK") do { try AVAudioSession.sharedInstance().setActive(true) //Qiscus.printLog(text: "AVAudioSession is Active") audioPlayer?.prepareToPlay() audioPlayer?.play() audioTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(audioTimerFired(_:)), userInfo: nil, repeats: true) } catch _ as NSError { Qiscus.printLog(text: "Audio player error") } } catch _ as NSError { Qiscus.printLog(text: "Audio player error") } } } } func didTapPauseButton(_ button: UIButton, onCell cell: QCellAudio){ audioPlayer?.pause() stopAudioTimer() updateAudioDisplay() } func didTapDownloadButton(_ button: UIButton, onCell cell: QCellAudio){ cell.displayAudioDownloading() self.room!.downloadMedia(onComment: cell.comment!, isAudioFile: true) } func didStartSeekTimeSlider(_ slider: UISlider, onCell cell: QCellAudio){ if audioTimer != nil { stopAudioTimer() } } func didEndSeekTimeSlider(_ slider: UISlider, onCell cell: QCellAudio){ audioPlayer?.stop() let currentTime = cell.comment!.currentTimeSlider audioPlayer?.currentTime = Double(currentTime) if let targetCell = cell as? QCellAudioLeft{ targetCell.isPlaying = false } if let targetCell = cell as? QCellAudioRight{ targetCell.isPlaying = false } } }
mit
1c568d37e49fc47c293b4684f0139d9e
39.385246
163
0.595799
5.113648
false
true
false
false
AlphaJian/LarsonApp
LarsonApp/LarsonApp/View/MKButton/MKWhiteBtn.swift
1
514
// // MKWhiteBtn.swift // LarsonApp // // Created by appledev018 on 11/10/16. // Copyright © 2016 Jian Zhang. All rights reserved. // import UIKit class MKWhiteBtn: MKButton { override func awakeFromNib() { self.setTitleColor(UIColor.black, for: .normal) self.cornerRadius = 3 self.layer.shadowOpacity = 0.8 self.layer.shadowRadius = 2 self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowColor = UIColor.gray.cgColor } }
apache-2.0
847ef1123736e1362bd130cbaf823bc1
21.304348
61
0.639376
3.664286
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/UIViewController+Extensions.swift
1
3139
// // UIViewController+Extensions.swift // Slide for Reddit // // Created by Jonathan Cole on 7/6/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import UIKit extension UIViewController { @objc func setupBaseBarColors(_ overrideColor: UIColor? = nil) { if #available(iOS 13, *) { self.navigationController?.navigationBar.standardAppearance = UINavigationBarAppearance() self.navigationController?.navigationBar.standardAppearance.configureWithOpaqueBackground() self.navigationController?.navigationBar.standardAppearance.backgroundColor = overrideColor ?? ColorUtil.getColorForSub(sub: "", true) self.navigationController?.navigationBar.standardAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: SettingValues.reduceColor ? ColorUtil.theme.fontColor : UIColor.white] self.navigationController?.navigationBar.standardAppearance.shadowColor = UIColor.clear self.navigationController?.navigationBar.compactAppearance = UINavigationBarAppearance() self.navigationController?.navigationBar.compactAppearance?.configureWithOpaqueBackground() self.navigationController?.navigationBar.compactAppearance?.backgroundColor = overrideColor ?? ColorUtil.getColorForSub(sub: "", true) self.navigationController?.navigationBar.compactAppearance?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: SettingValues.reduceColor ? ColorUtil.theme.fontColor : UIColor.white] } else { navigationController?.navigationBar.barTintColor = overrideColor ?? ColorUtil.getColorForSub(sub: "", true) let textAttributes = [convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): SettingValues.reduceColor ? ColorUtil.theme.fontColor : .white] navigationController?.navigationBar.titleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary(textAttributes) } self.setNeedsUpdateOfHomeIndicatorAutoHidden() navigationController?.navigationBar.tintColor = SettingValues.reduceColor ? ColorUtil.theme.fontColor : UIColor.white setNeedsStatusBarAppearanceUpdate() } public func disableDismissalRecognizers() { navigationController?.presentationController?.presentedView?.gestureRecognizers?.forEach { $0.isEnabled = false } } public func enableDismissalRecognizers() { navigationController?.presentationController?.presentedView?.gestureRecognizers?.forEach { $0.isEnabled = true } } } // Helper function inserted by Swift 4.2 migrator. private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) }) }
apache-2.0
a58218b850ae020a51de11343bc98207
52.186441
205
0.749522
5.909605
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/TitleCell.swift
1
1874
// // TitleCell.swift // RealmModelGenerator // // Created by Brandon Erbschloe on 3/10/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Cocoa protocol TitleCellDelegate: AnyObject { func titleCell(titleCell:TitleCell, shouldChangeTitle title:String) -> Bool } @IBDesignable class TitleCell: NibDesignableView, NSTextFieldDelegate { static let IDENTIFIER = NSUserInterfaceItemIdentifier("TitleCell") @IBOutlet var titleTextField:NSTextField! @IBOutlet var letterTextField:NSTextField! weak var delegate:TitleCellDelegate? // Workaround for Xcode bug that prevents you from connecting the delegate in the storyboard. // Remove this extra property once Xcode gets fixed. @IBOutlet var ibDelegate:Any? { set { self.delegate = newValue as? TitleCellDelegate } get { return self.delegate } } override func nibDidLoad() { super.nibDidLoad() } @IBInspectable var letterColor:NSColor? { set { self.letterTextField.backgroundColor = newValue } get { return self.letterTextField.backgroundColor } } @IBInspectable var title:String { set { self.titleTextField.stringValue = newValue } get { return self.titleTextField.stringValue } } @IBInspectable var letter:String { set { self.letterTextField.stringValue = newValue } get { return self.letterTextField.stringValue } } func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { if let shouldEnd = self.delegate?.titleCell(titleCell: self, shouldChangeTitle: fieldEditor.string) { return shouldEnd } return true } }
mit
6d199e62b2c1763058f566e14f0dbb8e
25.013889
109
0.634277
5.048518
false
false
false
false
tardieu/swift
stdlib/public/core/Join.swift
10
6225
//===--- Join.swift - Protocol and Algorithm for concatenation ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// internal enum _JoinIteratorState { case start case generatingElements case generatingSeparator case end } /// An iterator that presents the elements of the sequences traversed /// by a base iterator, concatenated using a given separator. public struct JoinedIterator<Base : IteratorProtocol> : IteratorProtocol where Base.Element : Sequence { /// Creates an iterator that presents the elements of the sequences /// traversed by `base`, concatenated using `separator`. /// /// - Complexity: O(`separator.count`). public init<Separator : Sequence>(base: Base, separator: Separator) where Separator.Iterator.Element == Base.Element.Iterator.Element { self._base = base self._separatorData = ContiguousArray(separator) } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Base.Element.Iterator.Element? { while true { switch _state { case .start: if let nextSubSequence = _base.next() { _inner = nextSubSequence.makeIterator() _state = .generatingElements } else { _state = .end return nil } case .generatingElements: let result = _inner!.next() if _fastPath(result != nil) { return result } _inner = _base.next()?.makeIterator() if _inner == nil { _state = .end return nil } if !_separatorData.isEmpty { _separator = _separatorData.makeIterator() _state = .generatingSeparator } case .generatingSeparator: let result = _separator!.next() if _fastPath(result != nil) { return result } _state = .generatingElements case .end: return nil } } } internal var _base: Base internal var _inner: Base.Element.Iterator? internal var _separatorData: ContiguousArray<Base.Element.Iterator.Element> internal var _separator: ContiguousArray<Base.Element.Iterator.Element>.Iterator? internal var _state: _JoinIteratorState = .start } /// A sequence that presents the elements of a base sequence of sequences /// concatenated using a given separator. public struct JoinedSequence<Base : Sequence> : Sequence where Base.Iterator.Element : Sequence { /// Creates a sequence that presents the elements of `base` sequences /// concatenated using `separator`. /// /// - Complexity: O(`separator.count`). public init<Separator : Sequence>(base: Base, separator: Separator) where Separator.Iterator.Element == Base.Iterator.Element.Iterator.Element { self._base = base self._separator = ContiguousArray(separator) } /// Return an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> JoinedIterator<Base.Iterator> { return JoinedIterator( base: _base.makeIterator(), separator: _separator) } public func _copyToContiguousArray() -> ContiguousArray<Base.Iterator.Element.Iterator.Element> { var result = ContiguousArray<Iterator.Element>() let separatorSize: Int = numericCast(_separator.count) let reservation = _base._preprocessingPass { () -> Int in var r = 0 for chunk in _base { r += separatorSize + chunk.underestimatedCount } return r - separatorSize } if let n = reservation { result.reserveCapacity(numericCast(n)) } if separatorSize == 0 { for x in _base { result.append(contentsOf: x) } return result } var iter = _base.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append(contentsOf: _separator) result.append(contentsOf: next) } } return result } internal var _base: Base internal var _separator: ContiguousArray<Base.Iterator.Element.Iterator.Element> } extension Sequence where Iterator.Element : Sequence { /// Returns the concatenated elements of this sequence of sequences, /// inserting the given separator between each element. /// /// This example shows how an array of `[Int]` instances can be joined, using /// another `[Int]` instance as the separator: /// /// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] /// let joined = nestedNumbers.joined(separator: [-1, -2]) /// print(Array(joined)) /// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]" /// /// - Parameter separator: A sequence to insert between each of this /// sequence's elements. /// - Returns: The joined sequence of elements. /// /// - SeeAlso: `joined()` public func joined<Separator : Sequence>( separator: Separator ) -> JoinedSequence<Self> where Separator.Iterator.Element == Iterator.Element.Iterator.Element { return JoinedSequence(base: self, separator: separator) } } @available(*, unavailable, renamed: "JoinedIterator") public struct JoinGenerator<Base : IteratorProtocol> where Base.Element : Sequence {} extension JoinedSequence { @available(*, unavailable, renamed: "makeIterator()") public func generate() -> JoinedIterator<Base.Iterator> { Builtin.unreachable() } } extension Sequence where Iterator.Element : Sequence { @available(*, unavailable, renamed: "joined(separator:)") public func joinWithSeparator<Separator : Sequence>( _ separator: Separator ) -> JoinedSequence<Self> where Separator.Iterator.Element == Iterator.Element.Iterator.Element { Builtin.unreachable() } }
apache-2.0
85cc8463a9ae3c4bf396a949fd7ec641
30.439394
80
0.649478
4.475198
false
false
false
false
yapstudios/YapImageManager
Example/Source/ViewController.swift
1
2989
// // ViewController.swift // YapImageManager // // Created by Trevor Stout on 5/3/17. // Copyright © 2017 Yap Studios. All rights reserved. // import UIKit import Alamofire // This is a test Imgur app created for the example app and may be rate limited. Replace this with your own at the following URL: // https://api.imgur.com/oauth2/addclient let ImgurAPIClientId = "Client-ID e217e987f703b46" class ViewController: UIViewController { fileprivate var collectionView: UICollectionView? fileprivate let flowLayout = UICollectionViewFlowLayout() fileprivate let cellIdentifier = "cellIdentifier" fileprivate var images: [String]? func loadImages(forSubreddit subreddit: String, completion: @escaping ([String]?) -> Void) { var headers = [String: String]() headers["Authorization"] = ImgurAPIClientId let url = "https://api.imgur.com/3/gallery/r/\(subreddit)/time/0.json" SessionManager.default.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers) .validate() .responseJSON() { response in switch response.result { case .success: if let result = response.result.value as? [String: AnyObject], let data = result["data"] as? [[String: AnyObject]] { let images = data.flatMap { $0["link"] as? String } completion(images) } else { completion(nil) } case .failure (let error): print("Error loading images: \(error)") completion(nil) } } } override func viewDidLoad() { super.viewDidLoad() let inset = CGFloat(10.0) flowLayout.minimumLineSpacing = inset let imageWidth = view.bounds.width - 2.0 * inset flowLayout.itemSize = CGSize(width: imageWidth, height: (9.0 / 16.0 * imageWidth).rounded()) collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout) collectionView!.contentInset = UIEdgeInsetsMake(30.0, 0.0, inset, 0.0) collectionView!.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView!.dataSource = self collectionView!.backgroundColor = .clear collectionView!.register(ImageCell.self, forCellWithReuseIdentifier: cellIdentifier) collectionView!.alwaysBounceVertical = true view.addSubview(self.collectionView!) loadImages(forSubreddit: "earthporn") { images in if let images = images { self.images = images self.collectionView?.reloadData() } } } } extension ViewController: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images?.count ?? 0 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ImageCell cell.backgroundColor = .lightGray cell.URLString = images![indexPath.item] return cell } }
bsd-2-clause
01b6df2c646648fda770957cc5ffb03d
34.571429
129
0.719545
4.33672
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/TakeOrder/器械信息/Controller/KitTableViewController.swift
1
4418
// // KitTableViewController.swift // OMS-WH // // Created by xuech on 2017/11/1. // Copyright © 2017年 medlog. All rights reserved. // import UIKit protocol KitTableViewControllerDelegate { func kitViewController(didSelectedMode selectedModel:[KitModel]) } class KitTableViewController: UITableViewController { var paramsCode : (String?,String?) var delegate : KitTableViewControllerDelegate? fileprivate var viewModel = OMSBrandViewModel() fileprivate var kitModel = [KitModel]() fileprivate var selectedIndexs: [Int] = [] override func viewDidLoad() { super.viewDidLoad() title = "请选择套件" tableView.tableFooterView = UIView() tableView.rowHeight = 116 tableView.register(PackageTableViewCell.self) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确认", style: UIBarButtonItemStyle.done, target: self, action: #selector(submitKit)) requestData() } private func requestData(){ guard let oiOrgCode = paramsCode.1 else { return } viewModel.requestKitData(oIOrgCode: oiOrgCode) { (model, error) in if model.count > 0 { self.kitModel = model self.tableView.reloadData() } } } @objc private func submitKit(){ //检验资质 guard let dlOrgCode = paramsCode.0,let oIOrgCode = paramsCode.1 else { return } let selectedKitModel = kitModel.filter({$0.reqQty > 0}) let kitNumbers = selectedKitModel.flatMap({$0.medKitInternalNo}) let paramters :[String : Any] = ["oIOrgCode":oIOrgCode,"dLOrgCode":dlOrgCode,"medKitInternalNos":kitNumbers] viewModel.checkMaterialInKit(paramters: paramters) { (result, error) in if result["info"] as? [String:Any] == nil { self.requestKitInventory() } } } ///请求套件库存数量 private func requestKitInventory(){ let selectedKitModel = kitModel.filter({$0.reqQty > 0}) var paramters = [[String:String]]() for model in selectedKitModel { var paramter = [String:String]() paramter["medMIWarehouse"] = model.medMIWarehouse paramter["kitCode"] = model.kitCode paramters.append(paramter) } viewModel.queryKitInventory(paramters: ["jsonArray":paramters]) { (result, error) in if result.count > 0 { for (i,item) in selectedKitModel.enumerated() { item.inventory = result[i]["inventory"] as? Int ?? 0 } if let del = self.delegate { del.kitViewController(didSelectedMode: selectedKitModel) self.navigationController?.popViewController(animated: true) } } } } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return kitModel.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PackageTableViewCell", for: indexPath) as!PackageTableViewCell let model = kitModel[indexPath.row] cell.configKitData(medkitModel: model,hiddenInventory: true) cell.delegate = self return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let kitTemplateVC = KitTemplateDetailViewController() kitTemplateVC.medKitInternalNo = kitModel[indexPath.row].medKitInternalNo self.navigationController?.pushViewController(kitTemplateVC, animated: true) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 5 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } } extension KitTableViewController : PackageTableViewCellDelegate{ func editUsePackageTableViewCell(cell: PackageTableViewCell, modifiedModel: KitModel) { let index = tableView.indexPath(for: cell) guard let indexPath = index else { return } kitModel[indexPath.row] = modifiedModel } }
mit
af4ba34c1fdf77778e9406c081235b00
35.475
150
0.643363
4.794085
false
false
false
false
gu704823/huobanyun
huobanyun/Spring/SpringTextView.swift
18
2738
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([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 UIKit open class SpringTextView: UITextView, Springable { @IBInspectable public var autostart: Bool = false @IBInspectable public var autohide: Bool = false @IBInspectable public var animation: String = "" @IBInspectable public var force: CGFloat = 1 @IBInspectable public var delay: CGFloat = 0 @IBInspectable public var duration: CGFloat = 0.7 @IBInspectable public var damping: CGFloat = 0.7 @IBInspectable public var velocity: CGFloat = 0.7 @IBInspectable public var repeatCount: Float = 1 @IBInspectable public var x: CGFloat = 0 @IBInspectable public var y: CGFloat = 0 @IBInspectable public var scaleX: CGFloat = 1 @IBInspectable public var scaleY: CGFloat = 1 @IBInspectable public var rotate: CGFloat = 0 @IBInspectable public var curve: String = "" public var opacity: CGFloat = 1 public var animateFrom: Bool = false lazy private var spring : Spring = Spring(self) override open func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } open override func layoutSubviews() { super.layoutSubviews() spring.customLayoutSubviews() } public func animate() { self.spring.animate() } public func animateNext(completion: @escaping () -> ()) { self.spring.animateNext(completion: completion) } public func animateTo() { self.spring.animateTo() } public func animateToNext(completion: @escaping () -> ()) { self.spring.animateToNext(completion: completion) } }
mit
089fdb35c076112863c478c68447021e
37.027778
81
0.711833
4.688356
false
false
false
false
rogertjr/chatty
Chatty/Chatty/Model/Message.swift
1
936
// // Message.swift // Chatty // // Created by Roger on 31/08/17. // Copyright © 2017 Decodely. All rights reserved. // import UIKit class Message { //MARK: Properties var _owner: MessageOwner var _type: MessageType var _content: Any var _timestamp: Int var _isRead: Bool var _image: UIImage? private var _toID: String? private var _fromID: String? var owner: MessageOwner { return _owner } var type: MessageType { return _type } var content: Any { return _content } var isRead: Bool { return _isRead } var timeStamp: Int { return _timestamp } var image: UIImage { return _image! } var toID: String { return _toID! } var fromID: String { return _fromID! } init(type: MessageType, content: Any, owner: MessageOwner, timestamp: Int, isRead: Bool) { self._type = type self._content = content self._owner = owner self._timestamp = timestamp self._isRead = isRead } }
gpl-3.0
afab4eb0c60986cb18864caad0523a53
13.609375
91
0.659893
2.949527
false
false
false
false
andrewloyola/siesta
Examples/GithubBrowser/Source/UI/RepositoryViewController.swift
1
4772
// // RepositoryViewController.swift // GithubBrowser // // Created by Paul on 2016/7/16. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import UIKit import Siesta class RepositoryViewController: UIViewController, ResourceObserver { // MARK: UI Elements @IBOutlet weak var starIcon: UILabel? @IBOutlet weak var starButton: UIButton? @IBOutlet weak var starCountLabel: UILabel? @IBOutlet weak var descriptionLabel: UILabel? var statusOverlay = ResourceStatusOverlay() // MARK: Resources var repositoryResource: Resource? { didSet { updateObservation(from: oldValue, to: repositoryResource) } } var starredResource: Resource? { didSet { updateObservation(from: oldValue, to: starredResource) } } private func updateObservation(from oldResource: Resource?, to newResource: Resource?) { guard oldResource != newResource else { return } oldResource?.removeObservers(ownedBy: self) newResource? .addObserver(self) .addObserver(statusOverlay, owner: self) .loadIfNeeded() } // MARK: Content conveniences var repository: Repository? { return repositoryResource?.typedContent() } var isStarred: Bool { return starredResource?.typedContent() ?? false } // MARK: Display override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = SiestaTheme.darkColor statusOverlay.embedIn(self) statusOverlay.displayPriority = [.AnyData, .Loading, .Error] // Prioritize partial data over loading indicator showRepository() } func resourceChanged(resource: Resource, event: ResourceEvent) { showRepository() } func showRepository() { showBasicInfo() showStarred() } func showBasicInfo() { navigationItem.title = repository?.name descriptionLabel?.text = repository?.description } func showStarred() { if let repository = repository { starredResource = GithubAPI.currentUserStarred(repository) } else { starredResource = nil } starCountLabel?.text = repository?.starCount?.description starIcon?.text = isStarred ? "★" : "☆" starButton?.setTitle(isStarred ? "Unstar" : "Star", forState: .Normal) starButton?.enabled = (repository != nil) } // MARK: Actions @IBAction func toggleStar(sender: AnyObject) { guard let repository = repository else { return } // Two things of note here: // // 1. Siesta guarantees onCompletion will be called exactly once, no matter what the error condition, so // it’s safe to rely on it to stop the animation and reenable the button. No error recovery gymnastics! // // 2. Who changes the button title between “Star” and “Unstar?” Who updates the star count? // // Answer: the setStarred(…) method itself updates both the starred resource and the repository resource, // if the call succeeds. And why don’t we have to take any special action to deal with that here in // toggleStar(…)? Because RepositoryViewController is already observing those resources, and will thus // pick up the changes made by setStarred(…) without any futher intervention. // // This is exactly what chainable callbacks are for: we add our onCompletion callback, somebody else adds // their onSuccess callback, and neither knows about the other. Decoupling is lovely! And because Siesta // parses responses only once, no matter how many callback there are, the performance cost is negligible. startStarRequestAnimation() GithubAPI.setStarred(!isStarred, repository: repository) .onCompletion { _ in self.stopStarRequestAnimation() } } private func startStarRequestAnimation() { starButton?.enabled = false let rotation = CABasicAnimation(keyPath: "transform.rotation.z") rotation.fromValue = 0 rotation.toValue = 2 * M_PI rotation.duration = 1.6 rotation.repeatCount = Float.infinity starIcon?.layer.addAnimation(rotation, forKey: "loadingIndicator") } @objc private func stopStarRequestAnimation() { starButton?.enabled = true let stopRotation = CASpringAnimation(keyPath: "transform.rotation.z") stopRotation.toValue = -M_PI * 2 / 5 stopRotation.damping = 6 stopRotation.duration = stopRotation.settlingDuration starIcon?.layer.addAnimation(stopRotation, forKey: "loadingIndicator") } }
mit
62d08e0d8da6249be0b2ba1399841f1b
33.165468
119
0.655928
4.840979
false
false
false
false
tomburns/ios
FiveCalls/FiveCalls/IssuesContainerViewController.swift
1
7461
// // IssuesContainerViewController.swift // FiveCalls // // Created by Ben Scheirman on 2/1/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit import CoreLocation class IssuesContainerViewController : UIViewController, EditLocationViewControllerDelegate { @IBOutlet weak var headerView: UIView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var locationButton: UIButton! @IBOutlet weak var footerView: UIView! @IBOutlet weak var headerContainer: UIView! @IBOutlet weak var iPadShareButton: UIButton! static let headerHeight: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 90 : 105 var issuesViewController: IssuesViewController! var issuesManager: IssuesManager { return issuesViewController.issuesManager } lazy var effectView: UIVisualEffectView = { let effectView = UIVisualEffectView(frame: self.headerContainer.bounds) effectView.translatesAutoresizingMaskIntoConstraints = false effectView.effect = UIBlurEffect(style: .light) return effectView }() private func configureChildViewController() { let isRegularWidth = traitCollection.horizontalSizeClass == .regular let issuesVC = R.storyboard.main.issuesViewController()! issuesVC.issuesDelegate = self let childController: UIViewController if isRegularWidth { let splitController = UISplitViewController() splitController.viewControllers = [issuesVC, UIViewController()] splitController.preferredDisplayMode = .allVisible childController = splitController issuesVC.iPadShareButton = self.iPadShareButton self.navigationController?.setNavigationBarHidden(true, animated: false) } else { childController = issuesVC } addChildViewController(childController) view.insertSubview(childController.view, belowSubview: headerContainer) childController.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ childController.view.topAnchor.constraint(equalTo: view.topAnchor), childController.view.leftAnchor.constraint(equalTo: view.leftAnchor), childController.view.rightAnchor.constraint(equalTo: view.rightAnchor), childController.view.bottomAnchor.constraint(equalTo: footerView.topAnchor) ]) childController.didMove(toParentViewController: self) issuesViewController = issuesVC } override func viewDidLoad() { super.viewDidLoad() setTitleLabel(location: UserLocation.current) configureChildViewController() setupHeaderWithBlurEffect() } private func setupHeaderWithBlurEffect() { headerView.translatesAutoresizingMaskIntoConstraints = false effectView.contentView.addSubview(headerView) headerContainer.addSubview(effectView) NSLayoutConstraint.activate([ effectView.contentView.topAnchor.constraint(equalTo: headerView.topAnchor), effectView.contentView.bottomAnchor.constraint(equalTo: headerView.bottomAnchor), effectView.contentView.leftAnchor.constraint(equalTo: headerView.leftAnchor), effectView.contentView.rightAnchor.constraint(equalTo: headerView.rightAnchor), headerContainer.topAnchor.constraint(equalTo: effectView.topAnchor), headerContainer.bottomAnchor.constraint(equalTo: effectView.bottomAnchor), headerContainer.leftAnchor.constraint(equalTo: effectView.leftAnchor), headerContainer.rightAnchor.constraint(equalTo: effectView.rightAnchor) ]) } private func setContentInset() { // Fix for odd force unwrapping in crash noted in bug #75 guard issuesViewController != nil && headerContainer != nil else { return } issuesViewController.tableView.contentInset.top = headerContainer.frame.size.height issuesViewController.tableView.scrollIndicatorInsets.top = headerContainer.frame.size.height } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if previousTraitCollection != nil && previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass { issuesViewController.willMove(toParentViewController: nil) issuesViewController.view.constraints.forEach { constraint in issuesViewController.view.removeConstraint(constraint) } issuesViewController.view.removeFromSuperview() issuesViewController.removeFromParentViewController() configureChildViewController() } setContentInset() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) setContentInset() // don't need to listen anymore because any change comes from this VC (otherwise we'll end up fetching twice) NotificationCenter.default.removeObserver(self, name: .locationChanged, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // we need to know if location changes by any other VC so we can update our UI NotificationCenter.default.addObserver(self, selector: #selector(IssuesContainerViewController.locationDidChange(_:)), name: .locationChanged, object: nil) } @IBAction func setLocationTapped(_ sender: Any) { } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let nc = segue.destination as? UINavigationController, let vc = nc.topViewController as? EditLocationViewController { vc.delegate = self } } func locationDidChange(_ notification: Notification) { let location = notification.object as! UserLocation setTitleLabel(location: location) } // MARK: - EditLocationViewControllerDelegate func editLocationViewControllerDidCancel(_ vc: EditLocationViewController) { dismiss(animated: true, completion: nil) } func editLocationViewController(_ vc: EditLocationViewController, didUpdateLocation location: UserLocation) { DispatchQueue.main.async { [weak self] in self?.dismiss(animated: true) { self?.issuesManager.userLocation = location self?.issuesViewController.loadIssues() self?.setTitleLabel(location: location) } } } // MARK: - Private functions private func setTitleLabel(location: UserLocation?) { locationButton.setTitle(UserLocation.current.locationDisplay ?? "Set Location", for: .normal) } } extension IssuesContainerViewController : IssuesViewControllerDelegate { func didStartLoadingIssues() { activityIndicator.startAnimating() } func didFinishLoadingIssues() { activityIndicator.stopAnimating() } }
mit
a85f3f3781f6335f4bdbcb7c6714e01c
39.543478
163
0.694236
6.07987
false
false
false
false
zhouxinv/SwiftThirdTest
SwiftTest/ViewController.swift
1
2606
// // ViewController.swift // SwiftTest // // Created by GeWei on 2016/12/19. // Copyright © 2016年 GeWei. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let snapKitButton: UIButton = UIButton() snapKitButton.tag = 1 snapKitButton.setTitle("SnapKit", for:.normal) snapKitButton.backgroundColor = UIColor.red snapKitButton.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside) self.view .addSubview(snapKitButton) snapKitButton.snp.makeConstraints { (make) in make.width.equalTo(100) make.height.equalTo(30) make.center.equalTo(self.view) } let kingfisherButton: UIButton = UIButton() kingfisherButton.tag = 2 kingfisherButton.setTitle("Kingfisher", for:.normal) kingfisherButton.backgroundColor = UIColor.red kingfisherButton.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside) self.view .addSubview(kingfisherButton) kingfisherButton.snp.makeConstraints { (make) in make.width.equalTo(100) make.height.equalTo(30) make.top.equalTo(snapKitButton.snp.bottom).offset(10) make.centerX.equalTo(snapKitButton) } let AlamofireButton: UIButton = UIButton() AlamofireButton.tag = 3 AlamofireButton.setTitle("Alamofire", for:.normal) AlamofireButton.backgroundColor = UIColor.red AlamofireButton.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside) self.view .addSubview(AlamofireButton) AlamofireButton.snp.makeConstraints { (make) in make.width.equalTo(100) make.height.equalTo(30) make.top.equalTo(kingfisherButton.snp.bottom).offset(10) make.centerX.equalTo(snapKitButton) } } func tapped(_ button: UIButton){ print("tapped") if button.tag == 1 { let snapKitVC = SnapKitTableViewController() navigationController?.pushViewController(snapKitVC, animated: true) } else if button.tag == 2{ let kingfisherVC = KingfisherViewController() navigationController?.pushViewController(kingfisherVC, animated: true) }else if button.tag == 3{ let alamofireVC = AlamofireController() navigationController?.pushViewController(alamofireVC, animated: true); } } }
mit
b65f512a6fd80cadeb598ac55a591f07
33.706667
92
0.629274
4.639929
false
false
false
false
benlangmuir/swift
test/Inputs/SmallStringTestUtilities.swift
4
3401
#if _runtime(_ObjC) import Foundation #endif import StdlibUnittest extension String: Error {} func verifySmallString(_ small: _SmallString, _ input: String, file: String = #file, line: UInt = #line ) { let loc = SourceLoc(file, line, comment: "test data") expectEqual(_SmallString.capacity, small.count + small.unusedCapacity, stackTrace: SourceLocStack().with(loc)) let tiny = Array(input.utf8) expectEqual(tiny.count, small.count, stackTrace: SourceLocStack().with(loc)) for (lhs, rhs) in zip(tiny, small) { expectEqual(lhs, rhs, stackTrace: SourceLocStack().with(loc)) } let smallFromUTF16 = _SmallString(Array(input.utf16)) expectNotNil(smallFromUTF16, stackTrace: SourceLocStack().with(loc)) expectEqualSequence(small, smallFromUTF16!, stackTrace: SourceLocStack().with(loc)) // Test slicing // for i in 0..<small.count { for j in i...small.count { expectEqualSequence(tiny[i..<j], small[i..<j], stackTrace: SourceLocStack().with(loc)) if j < small.count { expectEqualSequence(tiny[i...j], small[i...j], stackTrace: SourceLocStack().with(loc)) } } } // Test RAC and Mutable var copy = small for i in 0..<small.count / 2 { let tmp = copy[i] copy[i] = copy[copy.count - 1 - i] copy[copy.count - 1 - i] = tmp } expectEqualSequence(small.reversed(), copy, stackTrace: SourceLocStack().with(loc)) } // Testing helper inits extension _SmallString { init?(_ codeUnits: Array<UInt8>) { guard let smol = codeUnits.withUnsafeBufferPointer({ return _SmallString($0) }) else { return nil } self = smol } init?(_ codeUnits: Array<UInt16>) { let str = codeUnits.withUnsafeBufferPointer { return String._uncheckedFromUTF16($0) } if !str._guts.isSmall { return nil } self.init(str._guts._object) } #if _runtime(_ObjC) init?(_cocoaString ns: NSString) { #if arch(i386) || arch(arm) || arch(arm64_32) return nil #else guard _isObjCTaggedPointer(ns) else { return nil } self = (ns as String)._guts.asSmall //regular tagged NSStrings are guaranteed to bridge to SmallStrings assert(_StringGuts(self).isSmall) #endif } #endif func _appending(_ other: _SmallString) -> _SmallString? { return _SmallString(self, appending: other) } func _repeated(_ n: Int) -> _SmallString? { var base = self let toAppend = self for _ in 0..<(n &- 1) { guard let s = _SmallString( base, appending: toAppend) else { return nil } base = s } return base } } func expectSmall(_ str: String, stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { switch str._classify()._form { case ._small: return default: expectationFailure("expected: small", trace: "", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } func expectCocoa(_ str: String, stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { switch str._classify()._form { case ._cocoa: return default: expectationFailure("expected: cocoa", trace: "", stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } }
apache-2.0
a2374f1b14dcb14c5feb578d86340c89
26.427419
107
0.629227
3.940904
false
false
false
false
jkolb/Asheron
Sources/Asheron/GraphicsObject.swift
1
15896
/* The MIT License (MIT) Copyright (c) 2020 Justin Kolb 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. */ public final class GraphicsObject : Identifiable { public struct Flags : OptionSet, CustomStringConvertible, Packable { public static let collidable = Flags(rawValue: 1 << 0) public static let renderable = Flags(rawValue: 1 << 1) public static let degradable = Flags(rawValue: 1 << 3) public let rawValue: UInt32 public init(rawValue: UInt32) { precondition(rawValue & 0b0100 == 0) // No proof this bit is ever used precondition(rawValue & 0b11111111_11111111_11111111_1111_0000 == 0) // These bits should be unused self.rawValue = rawValue } public var description: String { var values = self var strings = [String]() while !values.isEmpty { if values.contains(.collidable) { strings.append("collidable") values.subtract(.collidable) } if values.contains(.renderable) { strings.append("renderable") values.subtract(.renderable) } if values.contains(.degradable) { strings.append("degradable") values.subtract(.degradable) } } return "[\(strings.joined(separator: ", "))]" } } public var id: Identifier public var flags: Flags public var rgSurfaces: [Identifier] public var vertexArray: VertexArray public var collisionPolygons: [Polygon] public var collisionBSP: CollisionBSPTree public var sortCenter: Vector3 public var renderPolygons: [Polygon] public var renderBSP: RenderBSPTree public var degradeId: UInt32? public init(from dataStream: DataStream, id: Identifier) { let diskId = Identifier(from: dataStream) precondition(diskId == id) self.id = id self.flags = Flags(from: dataStream) self.rgSurfaces = [Identifier](uncompress: dataStream) self.vertexArray = VertexArray(from: dataStream) self.collisionPolygons = flags.contains(.collidable) ? [Polygon](uncompress: dataStream) : [] self.collisionBSP = flags.contains(.collidable) ? CollisionBSPTree(from: dataStream) : .empty self.sortCenter = Vector3(from: dataStream) self.renderPolygons = flags.contains(.renderable) ? [Polygon](uncompress: dataStream) : [] self.renderBSP = flags.contains(.renderable) ? RenderBSPTree(from: dataStream) : .empty self.degradeId = flags.contains(.degradable) ? UInt32(from: dataStream) : nil // 0x11000000 } public enum SidesType : UInt32, Hashable, Packable { case single = 0 case double = 1 case both = 2 } public struct StipplingType : OptionSet, Hashable, CustomStringConvertible, Packable { public static let none: StipplingType = [] public static let positive = StipplingType(rawValue: 1 << 0) public static let negative = StipplingType(rawValue: 1 << 1) public static let both: StipplingType = [.positive, .negative] public static let noPosUVs = StipplingType(rawValue: 1 << 2) public static let noNegUVs = StipplingType(rawValue: 1 << 3) public static let noUVs: StipplingType = [.noPosUVs, .noNegUVs] public let rawValue: UInt8 public init(rawValue: UInt8) { precondition(rawValue != 20) // NO_UVS == 20 ?? self.rawValue = rawValue } public var description: String { var values = self var strings = [String]() while !values.isEmpty { if values.contains(.positive) { strings.append("positive") values.subtract(.positive) } if values.contains(.negative) { strings.append("negative") values.subtract(.negative) } if values.contains(.noPosUVs) { strings.append("noPosUVs") values.subtract(.noPosUVs) } if values.contains(.noNegUVs) { strings.append("noNegUVs") values.subtract(.noNegUVs) } } return "[\(strings.joined(separator: ", "))]" } } public struct Polygon : Packable { public var polyId: UInt16 public var numPts: Int public var stippling: StipplingType public var sidesType: SidesType public var posSurface: Int16 public var negSurface: Int16 public var vertexIds: [UInt16] public var posUVIndices: [UInt8] public var negUVIndices: [UInt8] public init(from dataStream: DataStream) { self.polyId = UInt16(from: dataStream) self.numPts = numericCast(UInt8(from: dataStream)) let stippling = StipplingType(from: dataStream) self.stippling = stippling let sidesType = SidesType(from: dataStream) self.sidesType = sidesType self.posSurface = Int16(from: dataStream) self.negSurface = Int16(from: dataStream) self.vertexIds = [UInt16](from: dataStream, count: numPts) self.posUVIndices = [UInt8](from: dataStream, count: !stippling.contains(.noPosUVs) ? numPts : 0) self.negUVIndices = [UInt8](from: dataStream, count: sidesType == .both && !stippling.contains(.noNegUVs) ? numPts : 0) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public enum VertexType : UInt32, Packable { case unknown = 0 case csw = 1 // ?? // 2? // 3? } public struct VertexArray : Packable { public var vertexType: VertexType public var vertices: [Vertex] public init(from dataStream: DataStream) { let vertexType = VertexType(from: dataStream) precondition(vertexType == .csw) self.vertexType = vertexType self.vertices = [Vertex](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct VertexUV : Packable { public var u: Float32 public var v: Float32 public init(from dataStream: DataStream) { self.u = Float32(from: dataStream) self.v = Float32(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { u.encode(to: dataStream) v.encode(to: dataStream) } } public struct Vertex : Packable { public var index: Int16 public var position: Vector3 public var normal: Vector3 public var uvs: [VertexUV] public init(from dataStream: DataStream) { self.index = Int16(from: dataStream) let numUVs = Int16(from: dataStream) self.position = Vector3(from: dataStream) self.normal = Vector3(from: dataStream) self.uvs = [VertexUV](from: dataStream, count: numericCast(numUVs)) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public enum BSPTag : String, Packable { case LEAF = "LEAF" // Front child only case BPnn = "BPnn" case BPIn = "BPIn" // Back child only case BpIN = "BpIN" case BpnN = "BpnN" // Both front and back children case BPIN = "BPIN" case BPnN = "BPnN" case PORT = "PORT" // Neither child case BpIn = "BpIn" case BPOL = "BPOL" public var hasPosNode: Bool { switch self { case .BPnn, .BPIn, .BPIN, .BPnN, .PORT: return true case .BpIN, .BpnN, .BpIn, .BPOL, .LEAF: return false } } public var hasNegNode: Bool { switch self { case .BpnN, .BpIN, .BPIN, .BPnN, .PORT: return true case .BPnn, .BPIn, .BpIn, .BPOL, .LEAF: return false } } public init(from dataStream: DataStream) { let bytes = [UInt8](from: dataStream, count: 4) let string = String(bytes: bytes, encoding: .utf8)! self.init(rawValue: String(string.reversed()))! } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public indirect enum CollisionBSPTree : Packable { case empty case node(CollisionBSPNode) case leaf(CollisionBSPLeaf) public var isEmpty: Bool { switch self { case .empty: return true case .node, .leaf: return false } } public init(from dataStream: DataStream) { let bspTag = BSPTag(from: dataStream) switch bspTag { case .PORT: fatalError("Unexpected PORT node") case .LEAF: self = .leaf(CollisionBSPLeaf(from: dataStream)) case .BPIN, .BPIn, .BpIN, .BpIn, .BPnN, .BPnn, .BpnN, .BPOL: self = .node(CollisionBSPNode(from: dataStream, bspTag: bspTag)) } } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct CollisionBSPNode { public var bspTag: BSPTag public var splittingPlane: Plane public var posNode: CollisionBSPTree public var negNode: CollisionBSPTree public var sphere: Sphere public init(from dataStream: DataStream, bspTag: BSPTag) { self.bspTag = bspTag self.splittingPlane = Plane(from: dataStream) self.posNode = bspTag.hasPosNode ? CollisionBSPTree(from: dataStream) : .empty self.negNode = bspTag.hasNegNode ? CollisionBSPTree(from: dataStream) : .empty self.sphere = Sphere(from: dataStream) } } public struct CollisionBSPLeaf : Packable { public var bspTag: BSPTag { return .LEAF } public var leafIndex: UInt32 public var solid: Bool public var sphere: Sphere public var inPolys: [UInt16] public init(from dataStream: DataStream) { self.leafIndex = UInt32(from: dataStream) self.solid = Bool(from: dataStream) self.sphere = Sphere(from: dataStream) self.inPolys = [UInt16](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public indirect enum RenderBSPTree : Packable { case empty case node(RenderBSPNode) case leaf(RenderBSPLeaf) case portal(RenderBSPPortal) public var isEmpty: Bool { switch self { case .empty: return true case .node, .leaf, .portal: return false } } public init(from dataStream: DataStream) { let bspTag = BSPTag(from: dataStream) switch bspTag { case .PORT: self = .portal(RenderBSPPortal(from: dataStream)) case .LEAF: self = .leaf(RenderBSPLeaf(from: dataStream)) case .BPIN, .BPIn, .BpIN, .BpIn, .BPnN, .BPnn, .BpnN, .BPOL: self = .node(RenderBSPNode(from: dataStream, bspTag: bspTag)) } } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct PortalPoly : Packable { public var portalIndex: UInt16 public var polygonId: UInt16 public init(from dataStream: DataStream) { self.portalIndex = UInt16(from: dataStream) self.polygonId = UInt16(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct RenderBSPPortal : Packable { public var bspTag: BSPTag { return .PORT } public var splittingPlane: Plane public var posNode: RenderBSPTree public var negNode: RenderBSPTree public var sphere: Sphere public var inPolys: [UInt16] public var inPortals: [PortalPoly] public init(from dataStream: DataStream) { self.splittingPlane = Plane(from: dataStream) self.posNode = RenderBSPTree(from: dataStream) self.negNode = RenderBSPTree(from: dataStream) self.sphere = Sphere(from: dataStream) let numPolys = Int32(from: dataStream) let numPortals = Int32(from: dataStream) self.inPolys = [UInt16](from: dataStream, count: numericCast(numPolys)) self.inPortals = [PortalPoly](from: dataStream, count: numericCast(numPortals)) precondition(!posNode.isEmpty) precondition(!negNode.isEmpty) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct RenderBSPNode { public var bspTag: BSPTag public var splittingPlane: Plane public var posNode: RenderBSPTree public var negNode: RenderBSPTree public var sphere: Sphere public var inPolys: [UInt16] public init(from dataStream: DataStream, bspTag: BSPTag) { self.bspTag = bspTag self.splittingPlane = Plane(from: dataStream) self.posNode = bspTag.hasPosNode ? RenderBSPTree(from: dataStream) : .empty self.negNode = bspTag.hasNegNode ? RenderBSPTree(from: dataStream) : .empty self.sphere = Sphere(from: dataStream) self.inPolys = [UInt16](from: dataStream) } } public struct RenderBSPLeaf : Packable { public var bspTag: BSPTag { return .LEAF } public var leafIndex: UInt32 public init(from dataStream: DataStream) { self.leafIndex = UInt32(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } }
mit
18175a89d2ffc26db6fae9392598fb84
35.542529
137
0.581907
4.554728
false
false
false
false
amujic5/iVictim
iVictim/Application/AppDelegate.swift
1
5188
// // AppDelegate.swift // iVictim // // Created by Azzaro Mujic on 5/31/16 // Copyright (c) 2016 . All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let imageView = UIImageView() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { imageView.image = UIImage(named: "screen_image") window = UIWindow() let navigationController = UINavigationController() window?.rootViewController = navigationController window?.makeKeyAndVisible() let mainWireframe = MainWireframe(navigationController: navigationController) mainWireframe.showHomeScreen() return true } func applicationDidEnterBackground(_ application: UIApplication) { if let value = UserDefaults.standard.object(forKey: "hideWindow") as? Bool, value { if let window = window { window.addSubview(imageView) imageView.frame = window.bounds } } } func applicationWillEnterForeground(_ application: UIApplication) { imageView.removeFromSuperview() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.infinum.a" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "CoreDataSensitiveModel", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } }}
gpl-3.0
194c15080739ea4a95ee9e74916a4691
46.163636
291
0.680224
5.942726
false
false
false
false
nathanlentz/rivals
Rivals/Rivals/UserProfileViewController.swift
1
6175
// // UserProfileViewController.swift // Rivals // // Created by Nate Lentz on 4/16/17. // Copyright © 2017 ntnl.design. All rights reserved. // import UIKit import Firebase class UserProfileViewController: UIViewController { var user = User() var currentUser = User() var currentUserFriendsList = [String]() var doesRequestExist = false var currentUserId: String? @IBOutlet weak var bioTextField: UITextView! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var winsLabel: UILabel! @IBOutlet weak var lossesLabel: UILabel! @IBOutlet weak var friendButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = user.name! self.friendButton.backgroundColor = RIVALS_PRIMARY profileImageView.layer.cornerRadius = 50 profileImageView.layer.masksToBounds = true self.currentUserId = FIRAuth.auth()?.currentUser?.uid loadUserSettings() getCurrentUser() getFriendStatus() self.winsLabel.text = String(user.wins!) self.lossesLabel.text = String(user.losses!) } func loadUserSettings() { self.winsLabel.text = String(self.user.wins!) self.lossesLabel.text = String(self.user.losses!) if self.user.profileImageUrl != nil { self.profileImageView.loadImageUsingCacheWithUrlString(urlString: self.user.profileImageUrl!) } if self.user.bio == "" || self.user.bio == nil { self.bioTextField.text = "Looks like \(self.user.name ?? "this user") doesn't have a bio yet. What a loser" } else { self.bioTextField.text = self.user.bio } } func getCurrentUser() { ref.child("profiles").child(currentUserId!).observeSingleEvent(of: .value, with: { (snapshot) in if let dict = snapshot.value as? [String : Any] { self.currentUser.uid = dict["uid"] as? String self.currentUser.name = dict["name"] as? String self.currentUser.bio = dict["bio"] as? String } }, withCancel: nil) } func getFriendStatus() { ref.child("profiles").child(currentUserId!).child("friends").child(self.user.uid!).observeSingleEvent(of: .value, with: { (snapshot) in if let friendsDict = snapshot.value as? [String : Any] { let friend = Friend() friend.friendUid = friendsDict["friend_uid"] as? String friend.name = friendsDict["name"] as? String friend.status = friendsDict["status"] as? String if friend.friendUid == self.user.uid { if friend.status == "pending" { self.friendButton.setTitle("Pending", for: .normal) self.friendButton.backgroundColor = RIVALS_BLUISH } else if friend.status == "Accepted" { self.friendButton.setTitle("Remove Friend", for: .normal) // Turn this into a red button } else { self.friendButton.setTitle("Add Friend", for: .normal) } } } }) } @IBAction func addFriendButtonDidPress(_ sender: UIButton) { if self.friendButton.titleLabel?.text == "Add Friend" { // Add pending friend request to current user let friendData = ["status": "pending", "name": self.user.name!, "friend_uid": self.user.uid!] ref.child("profiles").child(self.currentUser.uid!).child("friends").child(self.user.uid!).setValue(friendData) // Add a request to the friend receiving the request let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short) let userRequest = ["requester_uid": self.currentUser.uid!, "request_date": timestamp, "requester_name": self.currentUser.name!] ref.child("profiles").child(self.user.uid!).child("requests").child(self.currentUser.uid!).setValue(userRequest) self.friendButton.setTitle("Pending", for: UIControlState.normal) self.friendButton.backgroundColor = RIVALS_BLUISH } // If request is pending, just pop an alert saying the request is pending if self.friendButton.titleLabel?.text == "Pending" { let alertController = UIAlertController(title: "Hey!", message: "Your friend request is pending. Go tell your buddy to accept!", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } if self.friendButton.titleLabel?.text == "Remove Friend" { // Alert asking for confirmation let alertController = UIAlertController(title: "Whoa!", message: "Too much beef between you two?", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let removeAction = UIAlertAction(title: "Remove Friend", style: .default) { (_) -> Void in // Remove from current user ref.child("profiles").child(self.currentUser.uid!).child("friends").child(self.user.uid!).removeValue() // Remove from user ref.child("profiles").child(self.user.uid!).child("friends").child(self.currentUser.uid!).removeValue() self.friendButton.setTitle("Add Friend", for: .normal) } alertController.addAction(cancelAction) alertController.addAction(removeAction) self.present(alertController, animated: true, completion: nil) // Remove if yes } } }
apache-2.0
acb23213b8c98149fb622b97abcbeb30
39.887417
164
0.58633
4.819672
false
false
false
false