repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
apple/swift
refs/heads/main
test/AutoDiff/SILOptimizer/differentiation_control_flow_sil.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-sil -verify -Xllvm -debug-only=differentiation 2>&1 %s | %FileCheck %s -check-prefix=CHECK-DATA-STRUCTURES // RUN: %target-swift-frontend -emit-sil -verify -Xllvm -sil-print-after=differentiation -o /dev/null 2>&1 %s | %FileCheck %s -check-prefix=CHECK-SIL // REQUIRES: asserts // TODO: Add FileCheck tests. import _Differentiation //===----------------------------------------------------------------------===// // Conditionals //===----------------------------------------------------------------------===// @differentiable(reverse) @_silgen_name("cond") func cond(_ x: Float) -> Float { if x > 0 { return x + x } return x - x } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb0__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb1__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: var predecessor: _AD__cond_bb1__Pred__src_0_wrt_0 // CHECK-DATA-STRUCTURES: var pullback_0: (Float) -> (Float, Float) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb2__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: var predecessor: _AD__cond_bb2__Pred__src_0_wrt_0 // CHECK-DATA-STRUCTURES: var pullback_1: (Float) -> (Float, Float) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb3__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: var predecessor: _AD__cond_bb3__Pred__src_0_wrt_0 // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb0__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb1__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: case bb0(_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb2__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: case bb0(_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb3__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: case bb2(_AD__cond_bb2__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: case bb1(_AD__cond_bb1__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: } // CHECK-SIL-LABEL: sil hidden [ossa] @condTJrSpSr : $@convention(thin) (Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) { // CHECK-SIL: bb0([[INPUT_ARG:%.*]] : $Float): // CHECK-SIL: [[BB0_PB_STRUCT:%.*]] = struct $_AD__cond_bb0__PB__src_0_wrt_0 () // CHECK-SIL: cond_br {{%.*}}, bb1, bb2 // CHECK-SIL: bb1: // CHECK-SIL: [[BB1_PRED:%.*]] = enum $_AD__cond_bb1__Pred__src_0_wrt_0, #_AD__cond_bb1__Pred__src_0_wrt_0.bb0!enumelt, [[BB0_PB_STRUCT]] // CHECK-SIL: [[BB1_PB_STRUCT:%.*]] = struct $_AD__cond_bb1__PB__src_0_wrt_0 // CHECK-SIL: [[BB3_PRED_PRED1:%.*]] = enum $_AD__cond_bb3__Pred__src_0_wrt_0, #_AD__cond_bb3__Pred__src_0_wrt_0.bb1!enumelt, [[BB1_PB_STRUCT]] // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED1]] : $_AD__cond_bb3__Pred__src_0_wrt_0) // CHECK-SIL: bb2: // CHECK-SIL: [[BB2_PRED:%.*]] = enum $_AD__cond_bb2__Pred__src_0_wrt_0, #_AD__cond_bb2__Pred__src_0_wrt_0.bb0!enumelt, [[BB0_PB_STRUCT]] // CHECK-SIL: [[BB2_PB_STRUCT:%.*]] = struct $_AD__cond_bb2__PB__src_0_wrt_0 // CHECK-SIL: [[BB3_PRED_PRED2:%.*]] = enum $_AD__cond_bb3__Pred__src_0_wrt_0, #_AD__cond_bb3__Pred__src_0_wrt_0.bb2!enumelt, [[BB2_PB_STRUCT]] // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED2]] : $_AD__cond_bb3__Pred__src_0_wrt_0) // CHECK-SIL: bb3([[ORIG_RES:%.*]] : $Float, [[BB3_PRED_ARG:%.*]] : @owned $_AD__cond_bb3__Pred__src_0_wrt_0) // CHECK-SIL: [[BB3_PB_STRUCT:%.*]] = struct $_AD__cond_bb3__PB__src_0_wrt_0 // CHECK-SIL: [[PULLBACK_REF:%.*]] = function_ref @condTJpSpSr // CHECK-SIL: [[PB:%.*]] = partial_apply [callee_guaranteed] [[PULLBACK_REF]]([[BB3_PB_STRUCT]]) // CHECK-SIL: [[VJP_RESULT:%.*]] = tuple ([[ORIG_RES]] : $Float, [[PB]] : $@callee_guaranteed (Float) -> Float) // CHECK-SIL: return [[VJP_RESULT]] // CHECK-SIL-LABEL: sil private [ossa] @condTJpSpSr : $@convention(thin) (Float, @owned _AD__cond_bb3__PB__src_0_wrt_0) -> Float { // CHECK-SIL: bb0([[SEED:%.*]] : $Float, [[BB3_PB_STRUCT:%.*]] : @owned $_AD__cond_bb3__PB__src_0_wrt_0): // CHECK-SIL: [[BB3_PRED:%.*]] = destructure_struct [[BB3_PB_STRUCT]] : $_AD__cond_bb3__PB__src_0_wrt_0 // CHECK-SIL: switch_enum [[BB3_PRED]] : $_AD__cond_bb3__Pred__src_0_wrt_0, case #_AD__cond_bb3__Pred__src_0_wrt_0.bb2!enumelt: bb1, case #_AD__cond_bb3__Pred__src_0_wrt_0.bb1!enumelt: bb3 // CHECK-SIL: bb1([[BB3_PRED2_TRAMP_PB_STRUCT:%.*]] : @owned $_AD__cond_bb2__PB__src_0_wrt_0): // CHECK-SIL: br bb2({{%.*}} : $Float, {{%.*}}: $Float, [[BB3_PRED2_TRAMP_PB_STRUCT]] : $_AD__cond_bb2__PB__src_0_wrt_0) // CHECK-SIL: bb2({{%.*}} : $Float, {{%.*}} : $Float, [[BB2_PB_STRUCT:%.*]] : @owned $_AD__cond_bb2__PB__src_0_wrt_0): // CHECK-SIL: ([[BB2_PRED:%.*]], [[BB2_PB:%.*]]) = destructure_struct [[BB2_PB_STRUCT]] // CHECK-SIL: [[BB2_ADJVALS:%.*]] = apply [[BB2_PB]]([[SEED]]) : $@callee_guaranteed (Float) -> (Float, Float) // CHECK-SIL: switch_enum [[BB2_PRED]] : $_AD__cond_bb2__Pred__src_0_wrt_0, case #_AD__cond_bb2__Pred__src_0_wrt_0.bb0!enumelt: bb6 // CHECK-SIL: bb3([[BB3_PRED1_TRAMP_PB_STRUCT:%.*]] : @owned $_AD__cond_bb1__PB__src_0_wrt_0): // CHECK-SIL: br bb4({{%.*}} : $Float, {{%.*}}: $Float, [[BB3_PRED1_TRAMP_PB_STRUCT]] : $_AD__cond_bb1__PB__src_0_wrt_0) // CHECK-SIL: bb4({{%.*}} : $Float, {{%.*}} : $Float, [[BB1_PB_STRUCT:%.*]] : @owned $_AD__cond_bb1__PB__src_0_wrt_0): // CHECK-SIL: ([[BB1_PRED:%.*]], [[BB1_PB:%.*]]) = destructure_struct [[BB1_PB_STRUCT]] // CHECK-SIL: [[BB1_ADJVALS:%.*]] = apply [[BB1_PB]]([[SEED]]) : $@callee_guaranteed (Float) -> (Float, Float) // CHECK-SIL: switch_enum [[BB1_PRED]] : $_AD__cond_bb1__Pred__src_0_wrt_0, case #_AD__cond_bb1__Pred__src_0_wrt_0.bb0!enumelt: bb5 // CHECK-SIL: bb5([[BB1_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB1_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb6([[BB2_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB2_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb7({{%.*}} : $Float, [[BB0_PB_STRUCT:%.*]] : $_AD__cond_bb0__PB__src_0_wrt_0): // CHECK-SIL: return {{%.*}} : $Float @differentiable(reverse) @_silgen_name("nested_cond") func nested_cond(_ x: Float, _ y: Float) -> Float { if x > 0 { if y > 10 { return x * y } else { return x + y } } return y - x } @differentiable(reverse) @_silgen_name("nested_cond_generic") func nested_cond_generic<T : Differentiable & FloatingPoint>(_ x: T, _ y: T) -> T { if x > 0 { if y > 10 { return y } else { return x } } return y } @differentiable(reverse) @_silgen_name("loop_generic") func loop_generic<T : Differentiable & FloatingPoint>(_ x: T) -> T { var result = x for _ in 1..<3 { var y = x for _ in 1..<3 { result = y y = result } } return result } // Test `switch_enum`. enum Enum { case a(Float) case b(Float, Float) } @differentiable(reverse) @_silgen_name("enum_notactive") func enum_notactive(_ e: Enum, _ x: Float) -> Float { switch e { case let .a(a): return x * a case let .b(b1, b2): return x * b1 * b2 } } // CHECK-SIL-LABEL: sil hidden [ossa] @enum_notactiveTJrUSpSr : $@convention(thin) (Enum, Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) { // CHECK-SIL: bb0([[ENUM_ARG:%.*]] : $Enum, [[X_ARG:%.*]] : $Float): // CHECK-SIL: [[BB0_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb0__PB__src_0_wrt_1 () // CHECK-SIL: switch_enum [[ENUM_ARG]] : $Enum, case #Enum.a!enumelt: bb1, case #Enum.b!enumelt: bb2 // CHECK-SIL: bb1([[ENUM_A:%.*]] : $Float): // CHECK-SIL: [[BB1_PRED_PRED0:%.*]] = enum $_AD__enum_notactive_bb1__Pred__src_0_wrt_1, #_AD__enum_notactive_bb1__Pred__src_0_wrt_1.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_notactive_bb0__PB__src_0_wrt_1 // CHECK-SIL: [[BB1_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb1__PB__src_0_wrt_1 ({{.*}}) // CHECK-SIL: [[BB3_PRED_PRED1:%.*]] = enum $_AD__enum_notactive_bb3__Pred__src_0_wrt_1, #_AD__enum_notactive_bb3__Pred__src_0_wrt_1.bb1!enumelt, [[BB1_PB_STRUCT]] : $_AD__enum_notactive_bb1__PB__src_0_wrt_1 // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED1]] : $_AD__enum_notactive_bb3__Pred__src_0_wrt_1) // CHECK-SIL: bb2([[ENUM_B:%.*]] : $(Float, Float)): // CHECK-SIL: [[BB2_PRED_PRED0:%.*]] = enum $_AD__enum_notactive_bb2__Pred__src_0_wrt_1, #_AD__enum_notactive_bb2__Pred__src_0_wrt_1.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_notactive_bb0__PB__src_0_wrt_1 // CHECK-SIL: [[BB2_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb2__PB__src_0_wrt_1 ({{.*}}) // CHECK-SIL: [[BB3_PRED_PRED2:%.*]] = enum $_AD__enum_notactive_bb3__Pred__src_0_wrt_1, #_AD__enum_notactive_bb3__Pred__src_0_wrt_1.bb2!enumelt, [[BB2_PB_STRUCT]] : $_AD__enum_notactive_bb2__PB__src_0_wrt_1 // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED2]] : $_AD__enum_notactive_bb3__Pred__src_0_wrt_1) // CHECK-SIL: bb3([[ORIG_RES:%.*]] : $Float, [[BB3_PRED_ARG:%.*]] : @owned $_AD__enum_notactive_bb3__Pred__src_0_wrt_1) // CHECK-SIL: [[BB3_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb3__PB__src_0_wrt_1 // CHECK-SIL: [[PULLBACK_REF:%.*]] = function_ref @enum_notactiveTJpUSpSr // CHECK-SIL: [[PB:%.*]] = partial_apply [callee_guaranteed] [[PULLBACK_REF]]([[BB3_PB_STRUCT]]) // CHECK-SIL: [[VJP_RESULT:%.*]] = tuple ([[ORIG_RES]] : $Float, [[PB]] : $@callee_guaranteed (Float) -> Float) // CHECK-SIL: return [[VJP_RESULT]] // Test `switch_enum_addr`. // Clone of `enum Optional<Wrapped>`. enum AddressOnlyEnum<T> { case some(T) case none } @differentiable(reverse) @_silgen_name("enum_addr_notactive") func enum_addr_notactive<T>(_ e: AddressOnlyEnum<T>, _ x: Float) -> Float { switch e { case .none: break case .some: break } return x } // CHECK-SIL-LABEL: sil hidden [ossa] @enum_addr_notactivelTJrUSpSr : $@convention(thin) <τ_0_0> (@in_guaranteed AddressOnlyEnum<τ_0_0>, Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) { // CHECK-SIL: bb0([[ENUM_ARG:%.*]] : $*AddressOnlyEnum<τ_0_0>, [[X_ARG:%.*]] : $Float): // CHECK-SIL: [[ENUM_ADDR:%.*]] = alloc_stack $AddressOnlyEnum<τ_0_0> // CHECK-SIL: copy_addr [[ENUM_ARG]] to [init] [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0> // CHECK-SIL: [[BB0_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb0__PB__src_0_wrt_1_l<τ_0_0> () // CHECK-SIL: switch_enum_addr [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0>, case #AddressOnlyEnum.none!enumelt: bb1, case #AddressOnlyEnum.some!enumelt: bb2 // CHECK-SIL: bb1: // CHECK-SIL: [[BB1_PRED_PRED0:%.*]] = enum $_AD__enum_addr_notactive_bb1__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb1__Pred__src_0_wrt_1_l.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_addr_notactive_bb0__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: dealloc_stack [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0> // CHECK-SIL: [[BB1_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb1__PB__src_0_wrt_1_l<τ_0_0> ([[BB1_PRED_PRED0]] : $_AD__enum_addr_notactive_bb1__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: [[BB3_PRED_PRED1:%.*]] = enum $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l.bb1!enumelt, [[BB1_PB_STRUCT]] : $_AD__enum_addr_notactive_bb1__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: br bb3([[BB3_PRED_PRED1]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: bb2: // CHECK-SIL: [[BB2_PRED_PRED0:%.*]] = enum $_AD__enum_addr_notactive_bb2__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb2__Pred__src_0_wrt_1_l.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_addr_notactive_bb0__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: [[ENUM_DATA:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0>, #AddressOnlyEnum.some!enumelt // CHECK-SIL: destroy_addr [[ENUM_DATA]] : $*τ_0_0 // CHECK-SIL: dealloc_stack [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0> // CHECK-SIL: [[BB2_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb2__PB__src_0_wrt_1_l<τ_0_0> ([[BB2_PRED_PRED0]] : $_AD__enum_addr_notactive_bb2__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: [[BB3_PRED_PRED2:%.*]] = enum $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l.bb2!enumelt, [[BB2_PB_STRUCT]] : $_AD__enum_addr_notactive_bb2__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: br bb3([[BB3_PRED_PRED2]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: bb3([[BB3_PRED_ARG:%.*]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>): // CHECK-SIL: [[BB3_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb3__PB__src_0_wrt_1_l<τ_0_0> ([[BB3_PRED_ARG]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: [[PB_FNREF:%.*]] = function_ref @enum_addr_notactivelTJpUSpSr : $@convention(thin) <τ_0_0> (Float, @owned _AD__enum_addr_notactive_bb3__PB__src_0_wrt_1_l<τ_0_0>) -> Float // CHECK-SIL: [[PB:%.*]] = partial_apply [callee_guaranteed] [[PB_FNREF]]<τ_0_0>([[BB3_PB_STRUCT]]) : $@convention(thin) <τ_0_0> (Float, @owned _AD__enum_addr_notactive_bb3__PB__src_0_wrt_1_l<τ_0_0>) -> Float // CHECK-SIL: [[VJP_RESULT:%.*]] = tuple ([[X_ARG]] : $Float, [[PB]] : $@callee_guaranteed (Float) -> Float) // CHECK-SIL: return [[VJP_RESULT]] : $(Float, @callee_guaranteed (Float) -> Float) // Test control flow + tuple buffer. // Verify that pullback buffers are not allocated for address projections. @differentiable(reverse) @_silgen_name("cond_tuple_var") func cond_tuple_var(_ x: Float) -> Float { // expected-warning @+1 {{variable 'y' was never mutated; consider changing to 'let' constant}} var y = (x, x) if x > 0 { return y.0 } return y.1 } // CHECK-SIL-LABEL: sil private [ossa] @cond_tuple_varTJpSpSr : $@convention(thin) (Float, @owned _AD__cond_tuple_var_bb3__PB__src_0_wrt_0) -> Float { // CHECK-SIL: bb0([[SEED:%.*]] : $Float, [[BB3_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb3__PB__src_0_wrt_0): // CHECK-SIL: [[BB3_PRED:%.*]] = destructure_struct [[BB3_PB_STRUCT]] : $_AD__cond_tuple_var_bb3__PB__src_0_wrt_0 // CHECK-SIL: copy_addr {{%.*}} to {{%.*}} : $*(Float, Float) // CHECK-SIL-NOT: copy_addr {{%.*}} to {{%.*}} : $*Float // CHECK-SIL: switch_enum [[BB3_PRED]] : $_AD__cond_tuple_var_bb3__Pred__src_0_wrt_0, case #_AD__cond_tuple_var_bb3__Pred__src_0_wrt_0.bb2!enumelt: bb1, case #_AD__cond_tuple_var_bb3__Pred__src_0_wrt_0.bb1!enumelt: bb3 // CHECK-SIL: bb1([[BB3_PRED2_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb2__PB__src_0_wrt_0): // CHECK-SIL: br bb2({{%.*}} : $Float, {{%.*}} : $Float, [[BB3_PRED2_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb2__PB__src_0_wrt_0) // CHECK-SIL: bb2({{%.*}} : $Float, {{%.*}} : $Float, [[BB2_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb2__PB__src_0_wrt_0): // CHECK-SIL: [[BB2_PRED:%.*]] = destructure_struct [[BB2_PB_STRUCT]] // CHECK-SIL: copy_addr {{%.*}} to {{%.*}} : $*(Float, Float) // CHECK-SIL-NOT: copy_addr {{%.*}} to {{%.*}} : $*Float // CHECK-SIL: switch_enum [[BB2_PRED]] : $_AD__cond_tuple_var_bb2__Pred__src_0_wrt_0, case #_AD__cond_tuple_var_bb2__Pred__src_0_wrt_0.bb0!enumelt: bb6 // CHECK-SIL: bb3([[BB3_PRED1_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb1__PB__src_0_wrt_0): // CHECK-SIL: br bb4({{%.*}} : $Float, {{%.*}} : $Float, [[BB3_PRED1_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb1__PB__src_0_wrt_0) // CHECK-SIL: bb4({{%.*}} : $Float, {{%.*}} : $Float, [[BB1_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb1__PB__src_0_wrt_0): // CHECK-SIL: [[BB1_PRED:%.*]] = destructure_struct [[BB1_PB_STRUCT]] // CHECK-SIL: copy_addr {{%.*}} to {{%.*}} : $*(Float, Float) // CHECK-SIL-NOT: copy_addr {{%.*}} to {{%.*}} : $*Float // CHECK-SIL: switch_enum [[BB1_PRED]] : $_AD__cond_tuple_var_bb1__Pred__src_0_wrt_0, case #_AD__cond_tuple_var_bb1__Pred__src_0_wrt_0.bb0!enumelt: bb5 // CHECK-SIL: bb5([[BB1_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB1_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb6([[BB2_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB2_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb7({{%.*}} : $Float, [[BB0_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0): // CHECK-SIL: return {{%.*}} : $Float
70a32bae76f9376866cf2dc3f3e56d73
58.807971
244
0.592779
false
false
false
false
anpavlov/swiftperl
refs/heads/master
Sources/Perl/UnsafeSV.swift
mit
1
import CPerl public enum SvType { case scalar, array, hash, code, format, io init(_ t: svtype) { switch t { case SVt_PVAV: self = .array case SVt_PVHV: self = .hash case SVt_PVCV: self = .code case SVt_PVFM: self = .format case SVt_PVIO: self = .io default: self = .scalar } } } public typealias UnsafeSV = CPerl.SV public typealias UnsafeSvPointer = UnsafeMutablePointer<UnsafeSV> extension UnsafeSV { @discardableResult mutating func refcntInc() -> UnsafeSvPointer { return SvREFCNT_inc(&self) } mutating func refcntDec(perl: UnsafeInterpreterPointer) { SvREFCNT_dec(perl, &self) } var type: SvType { mutating get { return SvType(SvTYPE(&self)) } } var defined: Bool { mutating get { return SvOK(&self) } } var isInt: Bool { mutating get { return SvIOK(&self) } } var isDouble: Bool { mutating get { return SvNOK(&self) } } var isString: Bool { mutating get { return SvPOK(&self) } } var isRef: Bool { mutating get { return SvROK(&self) } } var referent: UnsafeSvPointer? { mutating get { return SvROK(&self) ? SvRV(&self) : nil } } mutating func isObject(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool { return perl.pointee.sv_isobject(&self) } mutating func isDerived(from: String, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool { return from.withCString { perl.pointee.sv_derived_from(&self, $0) } } mutating func classname(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> String? { guard isObject(perl: perl) else { return nil } return String(cString: perl.pointee.sv_reftype(SvRV(&self), true)) } mutating func hasSwiftObjectMagic(perl: UnsafeInterpreterPointer) -> Bool { return SvTYPE(&self) == SVt_PVMG && perl.pointee.mg_findext(&self, PERL_MAGIC_ext, &objectMgvtbl) != nil } mutating func swiftObject(perl: UnsafeInterpreterPointer) -> PerlBridgedObject? { guard isObject(perl: perl) else { return nil } let sv = SvRV(&self)! guard sv.pointee.hasSwiftObjectMagic(perl: perl) else { return nil } let iv = perl.pointee.SvIV(sv) let u = Unmanaged<AnyObject>.fromOpaque(UnsafeRawPointer(bitPattern: iv)!) return (u.takeUnretainedValue() as! PerlBridgedObject) } } extension UnsafeInterpreter { mutating func newSV(_ v: Bool) -> UnsafeSvPointer { return newSV(boolSV(v)) } mutating func newSV(_ v: String, mortal: Bool = false) -> UnsafeSvPointer { let flags = mortal ? SVf_UTF8|SVs_TEMP : SVf_UTF8 return v.withCStringWithLength { newSVpvn_flags($0, $1, UInt32(flags)) } } mutating func newSV(_ v: UnsafeRawBufferPointer, utf8: Bool = false, mortal: Bool = false) -> UnsafeSvPointer { let flags = (utf8 ? SVf_UTF8 : 0) | (mortal ? SVs_TEMP : 0) return newSVpvn_flags(v.baseAddress?.assumingMemoryBound(to: CChar.self), v.count, UInt32(flags)) } mutating func newRV<T: UnsafeSvCastable>(inc v: UnsafeMutablePointer<T>) -> UnsafeSvPointer { return v.withMemoryRebound(to: UnsafeSV.self, capacity: 1) { newRV(inc: $0) } } mutating func newRV<T: UnsafeSvCastable>(noinc v: UnsafeMutablePointer<T>) -> UnsafeSvPointer { return v.withMemoryRebound(to: UnsafeSV.self, capacity: 1) { newRV(noinc: $0) } } mutating func newSV(_ v: AnyObject, isa: String) -> UnsafeSvPointer { let u = Unmanaged<AnyObject>.passRetained(v) let iv = unsafeBitCast(u, to: Int.self) let sv = sv_setref_iv(newSV(), isa, iv) sv_magicext(SvRV(sv), nil, PERL_MAGIC_ext, &objectMgvtbl, nil, 0) return sv } mutating func newSV(_ v: PerlBridgedObject) -> UnsafeSvPointer { return newSV(v, isa: type(of: v).perlClassName) } } private var objectMgvtbl = MGVTBL( svt_get: nil, svt_set: nil, svt_len: nil, svt_clear: nil, svt_free: { (perl, sv, magic) in let iv = perl.unsafelyUnwrapped.pointee.SvIV(sv.unsafelyUnwrapped) let u = Unmanaged<AnyObject>.fromOpaque(UnsafeRawPointer(bitPattern: iv)!) u.release() return 0 }, svt_copy: nil, svt_dup: nil, svt_local: nil ) extension Bool { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { self = perl.pointee.SvTRUE(sv) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { guard SvOK(sv) else { return nil } self = perl.pointee.SvTRUE(sv) } } extension Int { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvNIOK(sv) || perl.pointee.looks_like_number(sv) else { throw PerlError.notNumber(fromUnsafeSvPointer(inc: sv, perl: perl)) } self.init(unchecked: sv, perl: perl) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvOK(sv) else { return nil } try self.init(sv, perl: perl) } public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { self = perl.pointee.SvIV(sv) } } extension Double { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvNIOK(sv) || perl.pointee.looks_like_number(sv) else { throw PerlError.notNumber(fromUnsafeSvPointer(inc: sv, perl: perl)) } self.init(unchecked: sv, perl: perl) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvOK(sv) else { return nil } try self.init(sv, perl: perl) } public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { self = perl.pointee.SvNV(sv) } } extension String { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvPOK(sv) || SvNIOK(sv) else { throw PerlError.notStringOrNumber(fromUnsafeSvPointer(inc: sv, perl: perl)) } self.init(unchecked: sv, perl: perl) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvOK(sv) else { return nil } try self.init(sv, perl: perl) } public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { var clen = 0 let cstr = perl.pointee.SvPV(sv, &clen)! self = String(cString: cstr, withLength: clen) } }
b6adca4fe73dd8323f82ed1764ccb748
31.430052
112
0.717846
false
false
false
false
randallli/material-components-ios
refs/heads/develop
demos/Shrine/Shrine/ShrineHeaderContentView.swift
apache-2.0
3
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialPageControl class ShrineHeaderContentView: UIView, UIScrollViewDelegate { var pageControl = MDCPageControl() var scrollView = UIScrollView() var logoImageView = UIImageView(image: UIImage(named: "ShrineLogo")) var logoTextImageView = UIImageView(image: UIImage(named: "ShrineTextLogo")) fileprivate var pages = NSMutableArray() fileprivate var label = UILabel() fileprivate var labelDesc = UILabel() fileprivate var label2 = UILabel() fileprivate var labelDesc2 = UILabel() fileprivate var label3 = UILabel() fileprivate var labelDesc3 = UILabel() fileprivate var cyanBox = UIView() fileprivate var cyanBox2 = UIView() fileprivate var cyanBox3 = UIView() fileprivate var imageView = UIImageView() fileprivate var imageView2 = UIImageView() fileprivate var imageView3 = UIImageView() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder: NSCoder) { super.init(coder: coder)! } func commonInit() { let boundsWidth = bounds.width let boundsHeight = bounds.height scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.delegate = self scrollView.isPagingEnabled = true scrollView.showsHorizontalScrollIndicator = false addSubview(scrollView) autoresizingMask = [.flexibleWidth, .flexibleHeight] for i in 0...2 { let boundsLeft = CGFloat(i) * boundsWidth let pageFrame = bounds.offsetBy(dx: boundsLeft, dy: 0) let page = UIView(frame:pageFrame) page.clipsToBounds = true page.autoresizingMask = [.flexibleWidth, .flexibleHeight] pages.add(page) scrollView.addSubview(page) } pageControl.numberOfPages = 3 pageControl.autoresizingMask = [.flexibleWidth, .flexibleHeight] let pageControlSize = pageControl.sizeThatFits(bounds.size) pageControl.frame = CGRect(x: 0, y: boundsHeight - pageControlSize.height, width: boundsWidth, height: pageControlSize.height) pageControl.addTarget(self, action: #selector(didChangePage), for: UIControlEvents.valueChanged) addSubview(pageControl) addHeaderPages() addSubview(logoImageView) addSubview(logoTextImageView) } func addHeaderPages() { _ = ShrineHeaderPage(page: pages[0] as! UIView, imageView: imageView, label: label, labelDesc: labelDesc, cyanBox: cyanBox, imageName: "chair.png", description: "Green \ncomfort chair") _ = ShrineHeaderPage(page: pages[1] as! UIView, imageView: imageView2, label: label2, labelDesc: labelDesc2, cyanBox: cyanBox2, imageName: "backpack.png", description: "Best gift for \nthe traveler") _ = ShrineHeaderPage(page: pages[2] as! UIView, imageView: imageView3, label: label3, labelDesc: labelDesc3, cyanBox: cyanBox3, imageName: "heels.png", description: "Better \nwearing heels") } override func layoutSubviews() { super.layoutSubviews() var safeAreaInset: CGFloat = 0 #if swift(>=3.2) if #available(iOS 11.0, *) { safeAreaInset = min(self.safeAreaInsets.top, 10) } #endif let boundsWidth = bounds.width let boundsHeight = bounds.height for i in 0...pages.count - 1 { let boundsLeft = CGFloat(i) * boundsWidth let pageFrame = bounds.offsetBy(dx: boundsLeft, dy: 0) let page = pages[i] as! UIView page.frame = pageFrame } let pageControlSize = pageControl.sizeThatFits(bounds.size) pageControl.frame = CGRect(x: 0, y: boundsHeight - pageControlSize.height, width: boundsWidth, height: pageControlSize.height) let scrollWidth: CGFloat = boundsWidth * CGFloat(pages.count) scrollView.frame = CGRect(x: 0, y: 0, width: boundsWidth, height: boundsHeight) scrollView.contentSize = CGSize(width: scrollWidth, height: boundsHeight) let scrollViewOffsetX = CGFloat(pageControl.currentPage) * boundsWidth scrollView.setContentOffset(CGPoint(x: scrollViewOffsetX, y: 0), animated: false) logoImageView.center = CGPoint(x: (frame.size.width) / 2, y: 44 + safeAreaInset) logoTextImageView.center = CGPoint(x: (frame.size.width) / 2, y: 44 + safeAreaInset) let labelWidth = CGFloat(250) let labelWidthFrame = CGRect(x: frame.size.width - labelWidth, y: 90, width: labelWidth, height: label.frame.size.height) let labelDescWidth = CGFloat(200) let labelDescWidthFrame = CGRect(x: frame.size.width - labelDescWidth - 10, y: 190, width: labelDescWidth, height: 40) label.frame = labelWidthFrame labelDesc.frame = labelDescWidthFrame label2.frame = labelWidthFrame labelDesc2.frame = labelDescWidthFrame label3.frame = labelWidthFrame labelDesc3.frame = labelDescWidthFrame let cyanBoxFrame = CGRect(x: frame.size.width - 210, y: 180, width: 100, height: 8) cyanBox.frame = cyanBoxFrame cyanBox2.frame = cyanBoxFrame cyanBox3.frame = cyanBoxFrame imageView.frame = CGRect(x: -180, y: 120, width: 420, height: frame.size.height) imageView2.frame = CGRect(x: -220, y: 110, width: 420, height: frame.size.height) imageView3.frame = CGRect(x: -180, y: 40, width: 420, height: frame.size.height) } func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl.scrollViewDidScroll(scrollView) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { pageControl.scrollViewDidEndDecelerating(scrollView) } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { pageControl.scrollViewDidEndScrollingAnimation(scrollView) } func didChangePage(_ sender: MDCPageControl) { var offset = scrollView.contentOffset offset.x = CGFloat(sender.currentPage) * scrollView.bounds.size.width scrollView.setContentOffset(offset, animated: true) } }
8c2abbf09fb26b578be9aefbf64d729b
37.661111
98
0.670786
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/View/LinearEquations/Project/Items/VLinearEquationsProjectCellNewPolynomial.swift
mit
1
import UIKit class VLinearEquationsProjectCellNewPolynomial:VLinearEquationsProjectCell { override init(frame:CGRect) { super.init(frame:frame) let imageView:UIImageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.isUserInteractionEnabled = false imageView.image = #imageLiteral(resourceName: "assetGenericColNew") addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self) } required init?(coder:NSCoder) { return nil } }
10abb41c9fff0b0b1cfa591da39d2028
25.851852
75
0.656552
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/Components/ConversationIconBasedCell.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireDataModel class ConversationIconBasedCell: UIView { let imageContainer = UIView() let imageView = UIImageView() let textLabel = WebLinkTextView() let lineView = UIView() let topContentView = UIView() let bottomContentView = UIView() let labelFont: UIFont = .mediumFont private var containerWidthConstraint: NSLayoutConstraint! private var textLabelTrailingConstraint: NSLayoutConstraint! private var textLabelTopConstraint: NSLayoutConstraint! private var topContentViewTrailingConstraint: NSLayoutConstraint! weak var delegate: ConversationMessageCellDelegate? weak var message: ZMConversationMessage? var isSelected: Bool = false var selectionView: UIView? { return textLabel } var selectionRect: CGRect { return textLabel.bounds } var attributedText: NSAttributedString? { didSet { textLabel.attributedText = attributedText textLabel.accessibilityLabel = attributedText?.string let font = attributedText?.attributes(at: 0, effectiveRange: nil)[.font] as? UIFont if let lineHeight = font?.lineHeight { textLabelTopConstraint.constant = (32 - lineHeight) / 2 } else { textLabelTopConstraint.constant = 0 } } } private var trailingTextMargin: CGFloat { return -conversationHorizontalMargins.right * 2 } override init(frame: CGRect) { super.init(frame: frame) configureSubviews() configureConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init?(coder aDecoder: NSCoder) is not implemented") } func configureSubviews() { imageView.contentMode = .center imageView.isAccessibilityElement = true imageView.accessibilityLabel = "Icon" textLabel.isAccessibilityElement = true textLabel.backgroundColor = .clear textLabel.font = labelFont textLabel.delegate = self textLabel.linkTextAttributes = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle().rawValue as NSNumber, NSAttributedString.Key.foregroundColor: SelfUser.provider?.selfUser.accentColor ?? UIColor.accent() ] lineView.backgroundColor = SemanticColors.View.backgroundSeparatorConversationView imageContainer.addSubview(imageView) addSubview(imageContainer) addSubview(textLabel) addSubview(topContentView) addSubview(bottomContentView) addSubview(lineView) } func configureConstraints() { imageContainer.translatesAutoresizingMaskIntoConstraints = false imageView.translatesAutoresizingMaskIntoConstraints = false textLabel.translatesAutoresizingMaskIntoConstraints = false topContentView.translatesAutoresizingMaskIntoConstraints = false bottomContentView.translatesAutoresizingMaskIntoConstraints = false lineView.translatesAutoresizingMaskIntoConstraints = false topContentViewTrailingConstraint = topContentView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: trailingTextMargin) containerWidthConstraint = imageContainer.widthAnchor.constraint(equalToConstant: conversationHorizontalMargins.left) textLabelTrailingConstraint = textLabel.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: trailingTextMargin) textLabelTopConstraint = textLabel.topAnchor.constraint(equalTo: topContentView.bottomAnchor) // We want the content view to at least be below the image container let contentViewTopConstraint = bottomContentView.topAnchor.constraint(equalTo: imageContainer.bottomAnchor) contentViewTopConstraint.priority = .defaultLow NSLayoutConstraint.activate([ // imageContainer containerWidthConstraint, imageContainer.leadingAnchor.constraint(equalTo: leadingAnchor), imageContainer.topAnchor.constraint(equalTo: topContentView.bottomAnchor, constant: 0), imageContainer.heightAnchor.constraint(equalTo: imageView.heightAnchor), imageContainer.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: 0), // imageView imageView.widthAnchor.constraint(equalToConstant: 32), imageView.heightAnchor.constraint(equalToConstant: 32), imageView.centerXAnchor.constraint(equalTo: imageContainer.centerXAnchor), imageView.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor), // topContentView topContentView.topAnchor.constraint(equalTo: topAnchor), topContentView.leadingAnchor.constraint(equalTo: textLabel.leadingAnchor), topContentViewTrailingConstraint, // textLabel textLabel.leadingAnchor.constraint(equalTo: imageContainer.trailingAnchor), textLabelTopConstraint, textLabelTrailingConstraint, // lineView lineView.leadingAnchor.constraint(equalTo: textLabel.trailingAnchor, constant: 16), lineView.heightAnchor.constraint(equalToConstant: .hairline), lineView.trailingAnchor.constraint(equalTo: trailingAnchor), lineView.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor), // bottomContentView bottomContentView.leadingAnchor.constraint(equalTo: textLabel.leadingAnchor), bottomContentView.topAnchor.constraint(greaterThanOrEqualTo: textLabel.bottomAnchor), bottomContentView.trailingAnchor.constraint(equalTo: trailingAnchor), bottomContentView.bottomAnchor.constraint(equalTo: bottomAnchor), contentViewTopConstraint ]) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) containerWidthConstraint.constant = conversationHorizontalMargins.left textLabelTrailingConstraint.constant = trailingTextMargin topContentViewTrailingConstraint.constant = trailingTextMargin } } extension ConversationIconBasedCell: UITextViewDelegate { public func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { // Fixes Swift 5.0 release build child class overridden method not called bug return false } }
d09bdf0356908ee131b7ee8dc8b92072
40.793103
151
0.723322
false
false
false
false
macemmi/HBCI4Swift
refs/heads/master
HBCI4Swift/HBCI4Swift/Source/Syntax/HBCISegmentDescription.swift
gpl-2.0
1
// // HBCISegmentDescription.swift // HBCIBackend // // Created by Frank Emminghaus on 27.12.14. // Copyright (c) 2014 Frank Emminghaus. All rights reserved. // import Foundation class HBCISegmentDescription: HBCISyntaxElementDescription { let code:String; let version:Int; init(syntax:HBCISyntax, element:XMLElement, code:String, version:Int) throws { self.code = code; self.version = version; try super.init(syntax: syntax, element: element); self.delimiter = HBCIChar.plus.rawValue; self.elementType = ElementType.segment; } override func elementDescription() -> String { if self.identifier == nil { let type = self.type ?? "none" let name = self.name ?? "none" return "SEG type: \(type), name: \(name) \n" } else { return "SEG id: \(self.identifier!) \n" } } override func parse(_ bytes: UnsafePointer<CChar>, length: Int, binaries:Array<Data>)->HBCISyntaxElement? { let seg = HBCISegment(description: self); var ref:HBCISyntaxElementReference; var refIdx = 0; var num = 0; var count = 0; var delimiter = HBCIChar.plus.rawValue; var p: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>(mutating: bytes); var resLength = length; while(refIdx < self.children.count) { ref = self.children[refIdx]; // check if optional tail is cut if delimiter == HBCIChar.quote.rawValue { if num >= ref.minnum { refIdx += 1; continue; // check next } else { // error: non-optional element but end of SEG logInfo("Parse error: non-optional element is missing at the end of data element group"); return nil; } } if p.pointee == HBCIChar.plus.rawValue && refIdx > 0 { // empty element - check if element was optional if ref.minnum > num { // error: minimal occurence logInfo("Parse error: element \(ref.name ?? "?") is empty but not optional"); return nil; } else { num = 0; refIdx += 1; p = p.advanced(by: 1); // consume delimiter count += 1; resLength = length - count; } } else { if let element = ref.elemDescr.parse(p, length: resLength, binaries: binaries) { if ref.name != nil { element.name = ref.name; } else { logInfo("Parse error: reference without name"); return nil; } seg.children.append(element); if element.isEmpty { // check if element was optional if ref.minnum > num { // error: minimal occurence logInfo("Parse error: element \(ref.name ?? "?") is empty but not optional"); return nil; } else { num = 0; refIdx += 1; } } else { num += 1; if num == ref.maxnum { // new object num = 0; refIdx += 1; } } p = p.advanced(by: element.length); delimiter = p.pointee; p = p.advanced(by: 1); // consume delimiter count += element.length + 1; resLength = length - count; } else { // parse error for children return nil; } } } seg.length = count-1; if seg.name == "" { seg.name = seg.descr.type ?? ""; } return seg; } func parse(_ segData:Data, binaries:Array<Data>) ->HBCISegment? { return parse((segData as NSData).bytes.bindMemory(to: CChar.self, capacity: segData.count), length: segData.count, binaries: binaries) as? HBCISegment; } override func getElement() -> HBCISyntaxElement? { return HBCISegment(description: self); } }
87f8ce88888e91b04798c0ed948d5d91
34.80303
159
0.454084
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
iOSRACSwift/iOSRACSwift/ViewController.swift
mit
1
// // ViewController.swift // iOSRACSwift // // Created by Hanguang on 1/18/16. // Copyright © 2016 Hanguang. All rights reserved. // import UIKit import ReactiveCocoa class ViewController: UIViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBAction func loginButton(sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. nameTextField.rac_textSignal() .toSignalProducer() .skip(2) .filter { (text) -> Bool in let string = text as! String return string.characters.count > 3 }.startWithNext { (text) -> () in print(text!) } // let searchStrings = nameTextField.rac_textSignal() // .toSignalProducer() // .map { text in text as! String } // .throttle(0.5, onScheduler: QueueScheduler.mainQueueScheduler) // // let searchResult = searchStrings // .flatMap(.Latest) { (query: String) -> SignalProducer<(NSData, NSURLResponse), NSError> in // let URLRequest = NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!) // return NSURLSession.sharedSession() // .rac_dataWithRequest(URLRequest) // .retry(2) // .flatMapError { error in // print("Error: \(error)") // return SignalProducer.empty // } // } // .map { (data, URLResponse) -> String in // let string = String(data: data, encoding: NSUTF8StringEncoding)! // return string // } // .observeOn(UIScheduler()) // // searchResult.startWithNext { (results) -> () in // print("Search results: \(results)") // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d4d39b2ca5c44993a319ca2bb6e7a45d
32.523077
104
0.543827
false
false
false
false
sammyd/VT_InAppPurchase
refs/heads/master
projects/01_GettingStarted/001_ChallengeComplete/GreenGrocer/IAPHelper.swift
mit
3
/* * Copyright (c) 2015 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 StoreKit import Foundation class IAPHelper: NSObject { typealias ProductsRequestCompletionHandler = (products: [SKProduct]?) -> () private let productIndentifiers: Set<String> private var productsRequest: SKProductsRequest? private var productsRequestCompletionHandler: ProductsRequestCompletionHandler? init(prodIds: Set<String>) { self.productIndentifiers = prodIds super.init() } } //:- API extension IAPHelper { func requestProducts(completionHandler: ProductsRequestCompletionHandler) { productsRequest?.cancel() productsRequestCompletionHandler = completionHandler productsRequest = SKProductsRequest(productIdentifiers: productIndentifiers) productsRequest?.delegate = self productsRequest?.start() } } //:- SKProductsRequestDelegate extension IAPHelper: SKProductsRequestDelegate { func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { productsRequestCompletionHandler?(products: response.products) productsRequestCompletionHandler = .None productsRequest = .None } func request(request: SKRequest, didFailWithError error: NSError) { print("Error: \(error.localizedDescription)") productsRequestCompletionHandler?(products: .None) productsRequestCompletionHandler = .None productsRequest = .None } }
3203c0b0bf24bd263d1ea745010d8735
35.205882
101
0.773355
false
false
false
false
tamanyan/SwiftPageMenu
refs/heads/master
PageMenuExample/Sources/StoryboardPageTabMenuViewController.swift
mit
1
// // StoryboardPageTabMenuViewController.swift // PageMenuExample // // Created by Tamanyan on 9/3/31 H. // Copyright © 31 Heisei Tamanyan. All rights reserved. // import UIKit import SwiftPageMenu class StoryboardPageTabMenuViewController: PageMenuController { let items: [[String]] let titles: [String] init(items: [[String]], titles: [String], options: PageMenuOptions? = nil) { self.items = items self.titles = titles super.init(options: options) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = [] if options.layout == .layoutGuide && options.tabMenuPosition == .bottom { self.view.backgroundColor = Theme.mainColor } else { self.view.backgroundColor = .white } if self.options.tabMenuPosition == .custom { self.view.addSubview(self.tabMenuView) self.tabMenuView.translatesAutoresizingMaskIntoConstraints = false self.tabMenuView.heightAnchor.constraint(equalToConstant: self.options.menuItemSize.height).isActive = true self.tabMenuView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.tabMenuView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true if #available(iOS 11.0, *) { self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true } else { self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } } self.delegate = self self.dataSource = self } } extension StoryboardPageTabMenuViewController: PageMenuControllerDataSource { func viewControllers(forPageMenuController pageMenuController: PageMenuController) -> [UIViewController] { return self.titles.enumerated().map({ (i, title) -> UIViewController in let storyboard = UIStoryboard(name: "StoryboardChildViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "StoryboardChildViewController") as! StoryboardChildViewController controller.title = "Storyboard #\(i) (\(title))" return controller }) } func menuTitles(forPageMenuController pageMenuController: PageMenuController) -> [String] { return self.titles } func defaultPageIndex(forPageMenuController pageMenuController: PageMenuController) -> Int { return 0 } } extension StoryboardPageTabMenuViewController: PageMenuControllerDelegate { func pageMenuController(_ pageMenuController: PageMenuController, didScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) { // The page view controller will begin scrolling to a new page. print("didScrollToPageAtIndex index:\(index)") } func pageMenuController(_ pageMenuController: PageMenuController, willScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) { // The page view controller scroll progress between pages. print("willScrollToPageAtIndex index:\(index)") } func pageMenuController(_ pageMenuController: PageMenuController, scrollingProgress progress: CGFloat, direction: PageMenuNavigationDirection) { // The page view controller did complete scroll to a new page. print("scrollingProgress progress: \(progress)") } func pageMenuController(_ pageMenuController: PageMenuController, didSelectMenuItem index: Int, direction: PageMenuNavigationDirection) { print("didSelectMenuItem index: \(index)") } }
0002e62f07fcda5c8074eedb8a186632
37.989796
148
0.70191
false
false
false
false
mercadopago/px-ios
refs/heads/develop
MercadoPagoSDK/MercadoPagoSDK/Services/Models/PXOneTapItem.swift
mit
1
import Foundation /// :nodoc: open class PXOneTapItem: NSObject, Codable { open var paymentMethodId: String open var paymentTypeId: String? open var oneTapCard: PXOneTapCard? public init(paymentMethodId: String, paymentTypeId: String?, oneTapCard: PXOneTapCard?) { self.paymentMethodId = paymentMethodId self.paymentTypeId = paymentTypeId self.oneTapCard = oneTapCard } public enum PXOneTapItemKeys: String, CodingKey { case paymentMethodId = "payment_method_id" case paymentTypeId = "payment_type_id" case oneTapCard = "card" } public required convenience init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PXOneTapItemKeys.self) let oneTapCard: PXOneTapCard? = try container.decodeIfPresent(PXOneTapCard.self, forKey: .oneTapCard) let paymentMethodId: String = try container.decode(String.self, forKey: .paymentMethodId) let paymentTypeId: String? = try container.decodeIfPresent(String.self, forKey: .paymentTypeId) self.init(paymentMethodId: paymentMethodId, paymentTypeId: paymentTypeId, oneTapCard: oneTapCard) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: PXOneTapItemKeys.self) try container.encodeIfPresent(self.oneTapCard, forKey: .oneTapCard) try container.encodeIfPresent(self.paymentMethodId, forKey: .paymentMethodId) try container.encodeIfPresent(self.paymentTypeId, forKey: .paymentTypeId) } open func toJSONString() throws -> String? { let encoder = JSONEncoder() let data = try encoder.encode(self) return String(data: data, encoding: .utf8) } open func toJSON() throws -> Data { let encoder = JSONEncoder() return try encoder.encode(self) } open class func fromJSONToPXOneTapItem(data: Data) throws -> PXOneTapItem { return try JSONDecoder().decode(PXOneTapItem.self, from: data) } open class func fromJSON(data: Data) throws -> PXOneTapItem { return try JSONDecoder().decode(PXOneTapItem.self, from: data) } }
3fd5693e1b0107697b081c414145c55c
39.222222
109
0.701657
false
false
false
false
Lucky-Orange/Tenon
refs/heads/master
Pitaya/Source/Helper.swift
mit
1
// The MIT License (MIT) // Copyright (c) 2015 JohnLui <[email protected]> https://github.com/johnlui // 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. // // Helper.swift // Pitaya // // Created by 吕文翰 on 15/10/7. // import Foundation class Helper { // stolen from Alamofire static func buildParams(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value: AnyObject! = parameters[key] components += Helper.queryComponents(key, value) } return components.map{"\($0)=\($1)"}.joinWithSeparator("&") } // stolen from Alamofire static func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] components.appendContentsOf([(Helper.escape(key), Helper.escape("\(value)"))]) return components } // stolen from Alamofire static func escape(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*" return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } }
c8690d1d8fc8dbf1835bb0c91100a43a
42.264151
153
0.698517
false
false
false
false
WenchaoD/FSPagerView
refs/heads/master
Sources/FSPageViewTransformer.swift
mit
1
// // FSPagerViewTransformer.swift // FSPagerView // // Created by Wenchao Ding on 05/01/2017. // Copyright © 2017 Wenchao Ding. All rights reserved. // import UIKit @objc public enum FSPagerViewTransformerType: Int { case crossFading case zoomOut case depth case overlap case linear case coverFlow case ferrisWheel case invertedFerrisWheel case cubic } open class FSPagerViewTransformer: NSObject { open internal(set) weak var pagerView: FSPagerView? open internal(set) var type: FSPagerViewTransformerType @objc open var minimumScale: CGFloat = 0.65 @objc open var minimumAlpha: CGFloat = 0.6 @objc public init(type: FSPagerViewTransformerType) { self.type = type switch type { case .zoomOut: self.minimumScale = 0.85 case .depth: self.minimumScale = 0.5 default: break } } // Apply transform to attributes - zIndex: Int, frame: CGRect, alpha: CGFloat, transform: CGAffineTransform or transform3D: CATransform3D. open func applyTransform(to attributes: FSPagerViewLayoutAttributes) { guard let pagerView = self.pagerView else { return } let position = attributes.position let scrollDirection = pagerView.scrollDirection let itemSpacing = (scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height) + self.proposedInteritemSpacing() switch self.type { case .crossFading: var zIndex = 0 var alpha: CGFloat = 0 var transform = CGAffineTransform.identity switch scrollDirection { case .horizontal: transform.tx = -itemSpacing * position case .vertical: transform.ty = -itemSpacing * position } if (abs(position) < 1) { // [-1,1] // Use the default slide transition when moving to the left page alpha = 1 - abs(position) zIndex = 1 } else { // (1,+Infinity] // This page is way off-screen to the right. alpha = 0 zIndex = Int.min } attributes.alpha = alpha attributes.transform = transform attributes.zIndex = zIndex case .zoomOut: var alpha: CGFloat = 0 var transform = CGAffineTransform.identity switch position { case -CGFloat.greatestFiniteMagnitude ..< -1 : // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0 case -1 ... 1 : // [-1,1] // Modify the default slide transition to shrink the page as well let scaleFactor = max(self.minimumScale, 1 - abs(position)) transform.a = scaleFactor transform.d = scaleFactor switch scrollDirection { case .horizontal: let vertMargin = attributes.bounds.height * (1 - scaleFactor) / 2; let horzMargin = itemSpacing * (1 - scaleFactor) / 2; transform.tx = position < 0 ? (horzMargin - vertMargin*2) : (-horzMargin + vertMargin*2) case .vertical: let horzMargin = attributes.bounds.width * (1 - scaleFactor) / 2; let vertMargin = itemSpacing * (1 - scaleFactor) / 2; transform.ty = position < 0 ? (vertMargin - horzMargin*2) : (-vertMargin + horzMargin*2) } // Fade the page relative to its size. alpha = self.minimumAlpha + (scaleFactor-self.minimumScale)/(1-self.minimumScale)*(1-self.minimumAlpha) case 1 ... CGFloat.greatestFiniteMagnitude : // (1,+Infinity] // This page is way off-screen to the right. alpha = 0 default: break } attributes.alpha = alpha attributes.transform = transform case .depth: var transform = CGAffineTransform.identity var zIndex = 0 var alpha: CGFloat = 0.0 switch position { case -CGFloat.greatestFiniteMagnitude ..< -1: // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0 zIndex = 0 case -1 ... 0: // [-1,0] // Use the default slide transition when moving to the left page alpha = 1 transform.tx = 0 transform.a = 1 transform.d = 1 zIndex = 1 case 0 ..< 1: // (0,1) // Fade the page out. alpha = CGFloat(1.0) - position // Counteract the default slide transition switch scrollDirection { case .horizontal: transform.tx = itemSpacing * -position case .vertical: transform.ty = itemSpacing * -position } // Scale the page down (between minimumScale and 1) let scaleFactor = self.minimumScale + (1.0 - self.minimumScale) * (1.0 - abs(position)); transform.a = scaleFactor transform.d = scaleFactor zIndex = 0 case 1 ... CGFloat.greatestFiniteMagnitude: // [1,+Infinity) // This page is way off-screen to the right. alpha = 0 zIndex = 0 default: break } attributes.alpha = alpha attributes.transform = transform attributes.zIndex = zIndex case .overlap,.linear: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } let scale = max(1 - (1-self.minimumScale) * abs(position), self.minimumScale) let transform = CGAffineTransform(scaleX: scale, y: scale) attributes.transform = transform let alpha = (self.minimumAlpha + (1-abs(position))*(1-self.minimumAlpha)) attributes.alpha = alpha let zIndex = (1-abs(position)) * 10 attributes.zIndex = Int(zIndex) case .coverFlow: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } let position = min(max(-position,-1) ,1) let rotation = sin(position*(.pi)*0.5)*(.pi)*0.25*1.5 let translationZ = -itemSpacing * 0.5 * abs(position) var transform3D = CATransform3DIdentity transform3D.m34 = -0.002 transform3D = CATransform3DRotate(transform3D, rotation, 0, 1, 0) transform3D = CATransform3DTranslate(transform3D, 0, 0, translationZ) attributes.zIndex = 100 - Int(abs(position)) attributes.transform3D = transform3D case .ferrisWheel, .invertedFerrisWheel: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } // http://ronnqvi.st/translate-rotate-translate/ var zIndex = 0 var transform = CGAffineTransform.identity switch position { case -5 ... 5: let itemSpacing = attributes.bounds.width+self.proposedInteritemSpacing() let count: CGFloat = 14 let circle: CGFloat = .pi * 2.0 let radius = itemSpacing * count / circle let ty = radius * (self.type == .ferrisWheel ? 1 : -1) let theta = circle / count let rotation = position * theta * (self.type == .ferrisWheel ? 1 : -1) transform = transform.translatedBy(x: -position*itemSpacing, y: ty) transform = transform.rotated(by: rotation) transform = transform.translatedBy(x: 0, y: -ty) zIndex = Int((4.0-abs(position)*10)) default: break } attributes.alpha = abs(position) < 0.5 ? 1 : self.minimumAlpha attributes.transform = transform attributes.zIndex = zIndex case .cubic: switch position { case -CGFloat.greatestFiniteMagnitude ... -1: attributes.alpha = 0 case -1 ..< 1: attributes.alpha = 1 attributes.zIndex = Int((1-position) * CGFloat(10)) let direction: CGFloat = position < 0 ? 1 : -1 let theta = position * .pi * 0.5 * (scrollDirection == .horizontal ? 1 : -1) let radius = scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height var transform3D = CATransform3DIdentity transform3D.m34 = -0.002 switch scrollDirection { case .horizontal: // ForwardX -> RotateY -> BackwardX attributes.center.x += direction*radius*0.5 // ForwardX transform3D = CATransform3DRotate(transform3D, theta, 0, 1, 0) // RotateY transform3D = CATransform3DTranslate(transform3D,-direction*radius*0.5, 0, 0) // BackwardX case .vertical: // ForwardY -> RotateX -> BackwardY attributes.center.y += direction*radius*0.5 // ForwardY transform3D = CATransform3DRotate(transform3D, theta, 1, 0, 0) // RotateX transform3D = CATransform3DTranslate(transform3D,0, -direction*radius*0.5, 0) // BackwardY } attributes.transform3D = transform3D case 1 ... CGFloat.greatestFiniteMagnitude: attributes.alpha = 0 default: attributes.alpha = 0 attributes.zIndex = 0 } } } // An interitem spacing proposed by transformer class. This will override the default interitemSpacing provided by the pager view. open func proposedInteritemSpacing() -> CGFloat { guard let pagerView = self.pagerView else { return 0 } let scrollDirection = pagerView.scrollDirection switch self.type { case .overlap: guard scrollDirection == .horizontal else { return 0 } return pagerView.itemSize.width * -self.minimumScale * 0.6 case .linear: guard scrollDirection == .horizontal else { return 0 } return pagerView.itemSize.width * -self.minimumScale * 0.2 case .coverFlow: guard scrollDirection == .horizontal else { return 0 } return -pagerView.itemSize.width * sin(.pi*0.25*0.25*3.0) case .ferrisWheel,.invertedFerrisWheel: guard scrollDirection == .horizontal else { return 0 } return -pagerView.itemSize.width * 0.15 case .cubic: return 0 default: break } return pagerView.interitemSpacing } }
3c885851638a9701828c8f75cd90802d
40.901099
145
0.537722
false
false
false
false
Motsai/neblina-motiondemo-swift
refs/heads/master
src/NeblinaControl.swift
mit
2
// // NeblinaControl.swift // // // Created by Hoan Hoang on 2017-04-06. // Copyright © 2017 Motsai. All rights reserved. // import Foundation import CoreBluetooth extension Neblina { // // MARK : **** API // // ******************************** // * Neblina Command API // ******************************** // // *** // *** Subsystem General // *** func getSystemStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS, paramLen: 0, paramData: [0]) } func getFusionStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FUSION_STATUS, paramLen: 0, paramData: [0]) } func getRecorderStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_RECORDER_STATUS, paramLen: 0, paramData: [0]) } func getFirmwareVersion() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION, paramLen: 0, paramData: [0]) } func getDataPortState() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS, paramLen: 0, paramData: [0]) } func setDataPort(_ PortIdx : Int, Ctrl : UInt8) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(PortIdx) param[1] = Ctrl // 1 - Open, 0 - Close sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, paramLen: 2, paramData: param) } func getPowerStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_POWER_STATUS, paramLen: 0, paramData: [0]) } func getSensorStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SENSOR_STATUS, paramLen: 0, paramData: [0]) } func disableStreaming() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DISABLE_STREAMING, paramLen: 0, paramData: [0]) } func resetTimeStamp( Delayed : Bool) { var param = [UInt8](repeating: 0, count: 1) if Delayed == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, paramLen: 1, paramData: param) } func firmwareUpdate() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, paramLen: 0, paramData: [0]) } func getDeviceName() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_GET, paramLen: 0, paramData: [0]) } func setDeviceName(name : String) { let param = [UInt8](name.utf8) print("setDeviceName \(name) \(param))") var len = param.count if len > Int(NEBLINA_NAME_LENGTH_MAX) { len = Int(NEBLINA_NAME_LENGTH_MAX) } sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET, paramLen: len, paramData: param) } func shutdown() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_SHUTDOWN, paramLen: 0, paramData: [0]) } func getUnixTime(uTime : UInt32) { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_GET_UNIX_TIMESTAMP, paramLen: 0, paramData: [0]) } func setUnixTime(uTime : UInt32) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(uTime & 0xFF) param[1] = UInt8((uTime >> 8) & 0xFF) param[2] = UInt8((uTime >> 16) & 0xFF) param[3] = UInt8((uTime >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SET_UNIX_TIMESTAMP, paramLen: param.count, paramData: param) } // *** // *** EEPROM // *** func eepromRead(_ pageNo : UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(pageNo & 0xff) param[1] = UInt8((pageNo >> 8) & 0xff) sendCommand(subSys: NEBLINA_SUBSYSTEM_EEPROM, cmd: NEBLINA_COMMAND_EEPROM_READ, paramLen: param.count, paramData: param) } func eepromWrite(_ pageNo : UInt16, data : UnsafePointer<UInt8>) { var param = [UInt8](repeating: 0, count: 10) param[0] = UInt8(pageNo & 0xff) param[1] = UInt8((pageNo >> 8) & 0xff) for i in 0..<8 { param[i + 2] = data[i] } sendCommand(subSys: NEBLINA_SUBSYSTEM_EEPROM, cmd: NEBLINA_COMMAND_EEPROM_WRITE, paramLen: param.count, paramData: param) } // *** LED subsystem commands func getLed() { sendCommand(subSys: NEBLINA_SUBSYSTEM_LED, cmd: NEBLINA_COMMAND_LED_STATUS, paramLen: 0, paramData: [0]) } func setLed(_ LedNo : UInt8, Value:UInt8) { var param = [UInt8](repeating: 0, count: 2) param[0] = LedNo param[1] = Value sendCommand(subSys: NEBLINA_SUBSYSTEM_LED, cmd: NEBLINA_COMMAND_LED_STATE, paramLen: param.count, paramData: param) } // *** Power management sybsystem commands func getTemperature() { sendCommand(subSys: NEBLINA_SUBSYSTEM_POWER, cmd: NEBLINA_COMMAND_POWER_TEMPERATURE, paramLen: 0, paramData: [0]) } func setBatteryChargeCurrent(_ Current: UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Current & 0xFF) param[1] = UInt8((Current >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_POWER, cmd: NEBLINA_COMMAND_POWER_CHARGE_CURRENT, paramLen: param.count, paramData: param) } // *** // *** Fusion subsystem commands // *** func setFusionRate(_ Rate: NeblinaRate_t) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Rate.rawValue & 0xFF) param[1] = UInt8((Rate.rawValue >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_RATE, paramLen: param.count, paramData: param) } func setFusionDownSample(_ Rate: UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Rate & 0xFF) param[1] = UInt8((Rate >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_DOWNSAMPLE, paramLen: param.count, paramData: param) } func streamMotionState(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM, paramLen: param.count, paramData: param) } func streamQuaternion(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, paramLen: param.count, paramData: param) } func streamEulerAngle(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM, paramLen: param.count, paramData: param) } func streamExternalForce(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM, paramLen: param.count, paramData: param) } func setFusionType(_ Mode:UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = Mode sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_FUSION_TYPE, paramLen: param.count, paramData: param) } func recordTrajectory(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD, paramLen: param.count, paramData: param) } func streamTrajectoryInfo(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM, paramLen: param.count, paramData: param) } func streamPedometer(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM, paramLen: param.count, paramData: param) } func streamSittingStanding(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SITTING_STANDING_STREAM, paramLen: param.count, paramData: param) } func lockHeadingReference() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, paramLen: 0, paramData: [0]) } func streamFingerGesture(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_FINGER_GESTURE_STREAM, paramLen: param.count, paramData: param) } func streamRotationInfo(_ Enable:Bool, Type : UInt8) { var param = [UInt8](repeating: 0, count: 2) param[1] = Type if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM, paramLen: param.count, paramData: param) } func externalHeadingCorrection(yaw : Int16, error : UInt16 ) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(yaw & 0xFF) param[1] = UInt8((yaw >> 8) & 0xFF) param[2] = UInt8(error & 0xFF) param[3] = UInt8((error >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EXTERNAL_HEADING_CORRECTION, paramLen: param.count, paramData: param) } func resetAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_RESET, paramLen: 0, paramData: [0]) } func calibrateAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_CALIBRATE, paramLen: 0, paramData: [0]) } func createPoseAnalysis(id : UInt8, qtf : [Int16]) { var param = [UInt8](repeating: 0, count: 2 + 8) param[0] = UInt8(id & 0xFF) for i in 0..<4 { param[1 + (i << 1)] = UInt8(qtf[i] & 0xFF) param[2 + (i << 1)] = UInt8((qtf[i] >> 8) & 0xFF) } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_CREATE_POSE, paramLen: param.count, paramData: param) } func setActivePoseAnalysis(id : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = id sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_SET_ACTIVE_POSE, paramLen: param.count, paramData: param) } func getActivePoseAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_GET_ACTIVE_POSE, paramLen: 0, paramData: [0]) } func streamAnalysis(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_STREAM, paramLen: param.count, paramData: param) } func getPoseAnalysisInfo(_ id: UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = id sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_POSE_INFO, paramLen: param.count, paramData: param) } func calibrateForwardPosition() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, paramLen: 0, paramData: [0]) } func calibrateDownPosition() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, paramLen: 0, paramData: [0]) } func streamMotionDirection(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_MOTION_DIRECTION_STREAM, paramLen: param.count, paramData: param) } func streamShockSegment(_ Enable:Bool, threshold : UInt8 ) { var param = [UInt8](repeating: 0, count: 2) if Enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = threshold sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM, paramLen: param.count, paramData: param) } func setGolfSwingAnalysisMode(_ mode : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = mode sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SET_GOLFSWING_ANALYSIS_MODE, paramLen: param.count, paramData: param) } func setGolfSwingMaxError(_ count : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = count sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SET_GOLFSWING_MAXIMUM_ERROR, paramLen: param.count, paramData: param) } func streamFunsionClustering(_ enable:Bool, mode : UInt8, sensor : UInt8, downSample : UInt8, snr : UInt8) { var param = [UInt8](repeating: 0, count: 5) if enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = mode param[2] = sensor param[3] = downSample param[4] = snr sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CLUSTERING_INFO_STREAM, paramLen: param.count, paramData: param) } // *** // *** Storage subsystem commands // *** func getSessionCount() { sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_COUNT, paramLen: 0, paramData: [0]) } func getSessionInfo(_ sessionId : UInt16, idx : UInt8) { var param = [UInt8](repeating: 0, count: 3) param[0] = UInt8(sessionId & 0xFF) param[1] = UInt8((sessionId >> 8) & 0xFF) param[2] = idx; sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_GENERAL_INFO, paramLen: param.count, paramData: param) } func getSessionName(_ sessionId : UInt16) { var param = [UInt8](repeating: 0, count: 3) param[0] = UInt8(sessionId & 0xFF) param[1] = UInt8((sessionId >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_NAME, paramLen: param.count, paramData: param) } func eraseStorage(_ quickErase:Bool) { var param = [UInt8](repeating: 0, count: 1) if quickErase == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_ERASE_ALL, paramLen: param.count, paramData: param) } func sessionPlayback(_ Enable:Bool, sessionId : UInt16) { var param = [UInt8](repeating: 0, count: 3) if Enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = UInt8(sessionId & 0xff) param[2] = UInt8((sessionId >> 8) & 0xff) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_PLAYBACK, paramLen: param.count, paramData: param) } func sessionRecord(_ Enable:Bool, info : String) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } print("\(info)") param += info.utf8 print("\(param)") sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_RECORD, paramLen: min(param.count, 16), paramData: param) } func sessionRead(_ SessionId:UInt16, Len:UInt16, Offset:UInt32) { var param = [UInt8](repeating: 0, count: 8) // Command parameter param[0] = UInt8(SessionId & 0xFF) param[1] = UInt8((SessionId >> 8) & 0xFF) param[2] = UInt8(Len & 0xFF) param[3] = UInt8((Len >> 8) & 0xFF) param[4] = UInt8(Offset & 0xFF) param[5] = UInt8((Offset >> 8) & 0xFF) param[6] = UInt8((Offset >> 16) & 0xFF) param[7] = UInt8((Offset >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_READ, paramLen: param.count, paramData: param) } func sessionDownload(_ Start : Bool, SessionId:UInt16, Len:UInt16, Offset:UInt32) { var param = [UInt8](repeating: 0, count: 9) // Command parameter if Start == true { param[0] = 1 } else { param[0] = 0 } param[1] = UInt8(SessionId & 0xFF) param[2] = UInt8((SessionId >> 8) & 0xFF) param[3] = UInt8(Len & 0xFF) param[4] = UInt8((Len >> 8) & 0xFF) param[5] = UInt8(Offset & 0xFF) param[6] = UInt8((Offset >> 8) & 0xFF) param[7] = UInt8((Offset >> 16) & 0xFF) param[8] = UInt8((Offset >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD, paramLen: param.count, paramData: param) } // *** // *** Sensor subsystem commands // *** func sensorSetDownsample(stream : UInt16, factor : UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(stream & 0xFF) param[1] = UInt8(stream >> 8) param[2] = UInt8(factor & 0xFF) param[3] = UInt8(factor >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_DOWNSAMPLE, paramLen: param.count, paramData: param) } func sensorSetRange(type : UInt16, range: UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(type & 0xFF) param[1] = UInt8(type >> 8) param[2] = UInt8(range & 0xFF) param[3] = UInt8(range >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_RANGE, paramLen: param.count, paramData: param) } func sensorSetRate(type : UInt16, rate: UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(type & 0xFF) param[1] = UInt8(type >> 8) param[2] = UInt8(rate & 0xFF) param[3] = UInt8(rate >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_RATE, paramLen: param.count, paramData: param) } func sensorGetDownsample(stream : NeblinaSensorStream_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = stream.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_DOWNSAMPLE, paramLen: param.count, paramData: param) } func sensorGetRange(type : NeblinaSensorType_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = type.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_RANGE, paramLen: param.count, paramData: param) } func sensorGetRate(type : NeblinaSensorType_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = type.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_RATE, paramLen: param.count, paramData: param) } func sensorStreamAccelData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, paramLen: param.count, paramData: param) } func sensorStreamGyroData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamHumidityData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, paramLen: param.count, paramData: param) } func sensorStreamMagData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, paramLen: param.count, paramData: param) } func sensorStreamPressureData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamTemperatureData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamAccelGyroData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamAccelMagData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM, paramLen: param.count, paramData: param) } }
7524c91751cd3276a91923b7a352669d
25.803526
151
0.670473
false
false
false
false
magi82/MGRelativeKit
refs/heads/master
Sources/RelativeLayout+align.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2017 ByungKook Hwang (https://magi82.github.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension RelativeLayout { public func alignLeft(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.x = from.frame.origin.x + padding self.layoutChanged.insert(.alignLeft) return self } public func alignRight(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.x = (from.frame.origin.x + from.frame.size.width) - (myView.frame.size.width + padding) self.layoutChanged.insert(.alignRight) return self } public func alignTop(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.y = from.frame.origin.y + padding self.layoutChanged.insert(.alignTop) return self } public func alignBottom(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.y = (from.frame.origin.y + from.frame.size.height) - (myView.frame.size.height + padding) self.layoutChanged.insert(.alignBottom) return self } }
de30219926bfa38d5c511cfad4a8ee87
36.793651
81
0.706006
false
false
false
false
jaischeema/Twist
refs/heads/master
Source/MediaItemResourceLoader.swift
mit
1
// // AVPlayerCaching.swift // Twist // // Created by Jais Cheema on 4/04/2016. // Copyright © 2016 Needle Apps. All rights reserved. // import Foundation import AVFoundation import MobileCoreServices func replaceUrlScheme(_ url: URL, scheme: String) -> URL? { var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) urlComponents?.scheme = scheme return urlComponents?.url } class MediaItemResourceLoader: NSObject, URLSessionDataDelegate, AVAssetResourceLoaderDelegate { var pendingRequests = [AVAssetResourceLoadingRequest]() var data: NSMutableData? var response: URLResponse? var session: URLSession! var connection: URLSessionDataTask? var successfulDownloadCallback: ((URL) -> Void)? let mediaURL: URL let cachePath: String? let cachingEnabled: Bool var _asset: AVURLAsset? init(mediaURL: URL, cachePath: String?, cachingEnabled: Bool?) { self.mediaURL = mediaURL self.cachePath = cachePath self.cachingEnabled = cachingEnabled == nil ? false : cachingEnabled! super.init() let configuration = URLSessionConfiguration.default configuration.allowsCellularAccess = true configuration.timeoutIntervalForRequest = 30 self.session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main) } var asset: AVURLAsset { if self._asset == nil { self.configureAsset() } return self._asset! } var isCachingEnabled: Bool { return self.cachingEnabled && self.cachePath != nil } var hasCachedFile: Bool { guard let cachePath = self.cachePath else { return false } let fileManager = FileManager.default return fileManager.fileExists(atPath: cachePath) } func configureAsset() { if isCachingEnabled { Twist.log.twistDebug("Caching is enabled") if hasCachedFile { Twist.log.twistDebug("Local cached file is available") self._asset = AVURLAsset(url: URL(fileURLWithPath: self.cachePath!), options: [:]) } else { Twist.log.twistDebug("Local cache file is not available") let streamingURL = replaceUrlScheme(self.mediaURL, scheme: "streaming")! self._asset = AVURLAsset(url: streamingURL, options: [:]) self._asset!.resourceLoader.setDelegate(self, queue: DispatchQueue.main) } } else { Twist.log.twistDebug("Caching is not enabled") self._asset = AVURLAsset(url: self.mediaURL, options: [:]) } assert(self._asset != nil, "Asset should not be nil") } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { Twist.log.twistDebug("Received response") self.data = NSMutableData() self.response = response self.processPendingRequests() completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { print(".", terminator: "") self.data?.append(data) self.processPendingRequests() } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error != nil { Twist.log.twistError(error!.localizedDescription) } else { self.processPendingRequests() Twist.log.twistInfo("Writing data to local cached file: \(self.cachePath!)") do { try self.data?.write(toFile: self.cachePath!, options: NSData.WritingOptions.atomicWrite) self.successfulDownloadCallback?(mediaURL) } catch { Twist.log.twistError("Unable to write to original file") } } } func processPendingRequests() { self.pendingRequests = self.pendingRequests.filter { loadingRequest in self.fillInContentInformation(loadingRequest.contentInformationRequest) if self.respondWithDataForRequest(loadingRequest.dataRequest) { loadingRequest.finishLoading() return false } return true } } func fillInContentInformation(_ contentInformationRequest: AVAssetResourceLoadingContentInformationRequest?) { if(contentInformationRequest == nil || self.response == nil) { return } let mimeType = self.response!.mimeType! guard let contentType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType as CFString, nil)?.takeRetainedValue() else { return } contentInformationRequest?.isByteRangeAccessSupported = true contentInformationRequest?.contentType = contentType as String contentInformationRequest?.contentLength = self.response!.expectedContentLength } func respondWithDataForRequest(_ dataRequest: AVAssetResourceLoadingDataRequest?) -> Bool { guard let dataRequest = dataRequest else { return false } let startOffset = Int(dataRequest.currentOffset == 0 ? dataRequest.requestedOffset : dataRequest.currentOffset) if self.data!.length < startOffset { return false } let unreadBytes = self.data!.length - startOffset let numberOfBytesToRespondWith = min(Int(dataRequest.requestedLength), unreadBytes) dataRequest.respond(with: self.data!.subdata(with: NSMakeRange(startOffset, numberOfBytesToRespondWith))) return self.data!.length >= startOffset + dataRequest.requestedLength } func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { if self.connection == nil { Twist.log.twistDebug("Starting request to get media URL: \(self.mediaURL)") let request = URLRequest(url: replaceUrlScheme(loadingRequest.request.url!, scheme: "http")!) self.connection = session.dataTask(with: request) self.connection?.resume() } self.pendingRequests.append(loadingRequest) return true } func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) { self.pendingRequests = self.pendingRequests.filter { $0 != loadingRequest } } }
39ac48fa74f7dd406c1e9ebf3c3a03a7
39.193939
179
0.661037
false
false
false
false
phimage/MomXML
refs/heads/master
Sources/Model/MomUniquenessConstraints.swift
mit
1
// // MomUniquenessConstraints.swift // MomXML // // Created by Eric Marchand on 01/07/2020. // Copyright © 2020 phimage. All rights reserved. // import Foundation public struct MomUniquenessConstraints { public var constraints: [MomUniquenessConstraint] = [] public mutating func add(constraint: MomUniquenessConstraint) { self.constraints.append(constraint) } public var isEmpty: Bool { return constraints.isEmpty } public init(uniquenessConstraints: [[Any]] = []) { self.constraints = uniquenessConstraints.compactMap { MomUniquenessConstraint(constraints: $0) } } } public struct MomUniquenessConstraint { public var constraints: [MomConstraint] = [] public init() {} public init?(constraints: [Any]) { self.constraints = constraints.compactMap { MomConstraint(any: $0) } if self.constraints.isEmpty { return nil } } } public struct MomConstraint { public var value: String public init(value: String) { self.value = value } public init?(any: Any) { guard let value = any as? String else { return nil } self.value = value } }
6e6eee20c76b88f4e080239828e3f851
21.481481
104
0.640033
false
false
false
false
volodg/iAsync.async
refs/heads/master
Pods/iAsync.async/Lib/JAsyncsOwner.swift
mit
2
// // JAsyncsOwner.swift // JAsync // // Created by Vladimir Gorbenko on 19.06.14. // Copyright (c) 2014 EmbeddedSources. All rights reserved. // import Foundation import iAsync_utils public class JAsyncsOwner { private class ActiveLoaderData { var handler: JAsyncHandler? func clear() { handler = nil } } private var loaders = [ActiveLoaderData]() let task: JAsyncHandlerTask public init(task: JAsyncHandlerTask) { self.task = task } public func ownedAsync<T>(loader: JAsyncTypes<T>.JAsync) -> JAsyncTypes<T>.JAsync { return { [weak self] ( progressCallback: JAsyncProgressCallback?, stateCallback: JAsyncChangeStateCallback?, finishCallback: JAsyncTypes<T>.JDidFinishAsyncCallback?) -> JAsyncHandler in if let self_ = self { let loaderData = ActiveLoaderData() self_.loaders.append(loaderData) let finishCallbackWrapper = { (result: JResult<T>) -> () in if let self_ = self { for (index, element) in enumerate(self_.loaders) { if self_.loaders[index] === loaderData { self_.loaders.removeAtIndex(index) break } } } finishCallback?(result: result) loaderData.clear() } loaderData.handler = loader( progressCallback: progressCallback, stateCallback : stateCallback, finishCallback : finishCallbackWrapper) return { (task: JAsyncHandlerTask) -> () in if let self_ = self { var loaderIndex = Int.max for (index, element) in enumerate(self_.loaders) { if self_.loaders[index] === loaderData { loaderIndex = index break } } if loaderIndex == Int.max { return } self_.loaders.removeAtIndex(loaderIndex) loaderData.handler?(task: task) loaderData.clear() } } } else { let error = JAsyncFinishedByCancellationError() finishCallback?(result: JResult.error(error)) return jStubHandlerAsyncBlock } } } public func handleAll(task: JAsyncHandlerTask) { let tmpLoaders = loaders loaders.removeAll(keepCapacity: false) for (_, element) in enumerate(tmpLoaders) { element.handler?(task: task) } } deinit { handleAll(self.task) } }
8dbcb005bdbb51c2384a37542d38d4cb
29.93578
88
0.430012
false
false
false
false
BlakeBarrett/MettaVR-Coding-Exercise
refs/heads/master
MettaVR Coding Exercise/MettaItem.swift
mit
1
// // MetaItem.swift // MettaVR Coding Exercise // // Created by Blake Barrett on 6/4/16. // Copyright © 2016 Blake Barrett. All rights reserved. // import Foundation class MettaItem { var title: String? var description: String? var copies: [MettaVideoItem]? var previewUrl: NSURL? init(info: NSDictionary) { self.title = info["title"] as? String self.description = info["description"] as? String if let url = info["previewUrl"] as? String { self.previewUrl = NSURL(string: url) } copies = [MettaVideoItem]() if let copiesDictionary = info["copies"] as? NSDictionary { copiesDictionary.allKeys.forEach({ (key:AnyObject) in let item = copiesDictionary.valueForKey(key as! String) as! NSDictionary let video = MettaVideoItem(info: item) copies?.append(video) }) } } }
901dfb9671bbd615328684903dd9f3f7
25.540541
88
0.575943
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019-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 /// Errors that may be raised by the `HTTPClientProtocolUpgrader`. public struct NIOHTTPClientUpgradeError: Hashable, Error { // Uses the open enum style to allow additional errors to be added in future. private enum Code: Hashable { case responseProtocolNotFound case invalidHTTPOrdering case upgraderDeniedUpgrade case writingToHandlerDuringUpgrade case writingToHandlerAfterUpgradeCompleted case writingToHandlerAfterUpgradeFailed case receivedResponseBeforeRequestSent case receivedResponseAfterUpgradeCompleted } private var code: Code private init(_ code: Code) { self.code = code } public static let responseProtocolNotFound = NIOHTTPClientUpgradeError(.responseProtocolNotFound) public static let invalidHTTPOrdering = NIOHTTPClientUpgradeError(.invalidHTTPOrdering) public static let upgraderDeniedUpgrade = NIOHTTPClientUpgradeError(.upgraderDeniedUpgrade) public static let writingToHandlerDuringUpgrade = NIOHTTPClientUpgradeError(.writingToHandlerDuringUpgrade) public static let writingToHandlerAfterUpgradeCompleted = NIOHTTPClientUpgradeError(.writingToHandlerAfterUpgradeCompleted) public static let writingToHandlerAfterUpgradeFailed = NIOHTTPClientUpgradeError(.writingToHandlerAfterUpgradeFailed) public static let receivedResponseBeforeRequestSent = NIOHTTPClientUpgradeError(.receivedResponseBeforeRequestSent) public static let receivedResponseAfterUpgradeCompleted = NIOHTTPClientUpgradeError(.receivedResponseAfterUpgradeCompleted) } extension NIOHTTPClientUpgradeError: CustomStringConvertible { public var description: String { return String(describing: self.code) } } /// An object that implements `NIOHTTPClientProtocolUpgrader` knows how to handle HTTP upgrade to /// a protocol on a client-side channel. /// It has the option of denying this upgrade based upon the server response. public protocol NIOHTTPClientProtocolUpgrader { /// The protocol this upgrader knows how to support. var supportedProtocol: String { get } /// All the header fields the protocol requires in the request to successfully upgrade. /// These header fields will be added to the outbound request's "Connection" header field. /// It is the responsibility of the custom headers call to actually add these required headers. var requiredUpgradeHeaders: [String] { get } /// Additional headers to be added to the request, beyond the "Upgrade" and "Connection" headers. func addCustom(upgradeRequestHeaders: inout HTTPHeaders) /// Gives the receiving upgrader the chance to deny the upgrade based on the upgrade HTTP response. func shouldAllowUpgrade(upgradeResponse: HTTPResponseHead) -> Bool /// Called when the upgrade response has been flushed. At this time it is safe to mutate the channel /// pipeline to add whatever channel handlers are required. /// Until the returned `EventLoopFuture` succeeds, all received data will be buffered. func upgrade(context: ChannelHandlerContext, upgradeResponse: HTTPResponseHead) -> EventLoopFuture<Void> } /// A client-side channel handler that sends a HTTP upgrade handshake request to perform a HTTP-upgrade. /// When the first HTTP request is sent, this handler will add all appropriate headers to perform an upgrade to /// the a protocol. It may add headers for a set of protocols in preference order. /// If the upgrade fails (i.e. response is not 101 Switching Protocols), this handler simply /// removes itself from the pipeline. If the upgrade is successful, it upgrades the pipeline to the new protocol. /// /// The request sends an order of preference to request which protocol it would like to use for the upgrade. /// It will only upgrade to the protocol that is returned first in the list and does not currently /// have the capability to upgrade to multiple simultaneous layered protocols. public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias OutboundIn = HTTPClientRequestPart public typealias OutboundOut = HTTPClientRequestPart public typealias InboundIn = HTTPClientResponsePart public typealias InboundOut = HTTPClientResponsePart private var upgraders: [NIOHTTPClientProtocolUpgrader] private let httpHandlers: [RemovableChannelHandler] private let upgradeCompletionHandler: (ChannelHandlerContext) -> Void /// Whether we've already seen the first response from our initial upgrade request. private var seenFirstResponse = false private var upgradeState: UpgradeState = .requestRequired private var receivedMessages: CircularBuffer<NIOAny> = CircularBuffer() /// Create a `HTTPClientUpgradeHandler`. /// /// - Parameter upgraders: All `HTTPClientProtocolUpgrader` objects that will add their upgrade request /// headers and handle the upgrade if there is a response for their protocol. They should be placed in /// order of the preference for the upgrade. /// - Parameter httpHandlers: All `RemovableChannelHandler` objects which will be removed from the pipeline /// once the upgrade response is sent. This is used to ensure that the pipeline will be in a clean state /// after the upgrade. It should include any handlers that are directly related to handling HTTP. /// At the very least this should include the `HTTPEncoder` and `HTTPDecoder`, but should also include /// any other handler that cannot tolerate receiving non-HTTP data. /// - Parameter upgradeCompletionHandler: A closure that will be fired when HTTP upgrade is complete. public convenience init( upgraders: [NIOHTTPClientProtocolUpgrader], httpHandlers: [RemovableChannelHandler], upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) { self.init(_upgraders: upgraders, httpHandlers: httpHandlers, upgradeCompletionHandler: upgradeCompletionHandler) } private init( _upgraders upgraders: [NIOHTTPClientProtocolUpgrader], httpHandlers: [RemovableChannelHandler], upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) { precondition(upgraders.count > 0, "A minimum of one protocol upgrader must be specified.") self.upgraders = upgraders self.httpHandlers = httpHandlers self.upgradeCompletionHandler = upgradeCompletionHandler } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { switch self.upgradeState { case .requestRequired: let updatedData = self.addHeadersToOutboundOut(data: data) context.write(updatedData, promise: promise) case .awaitingConfirmationResponse: // Still have full http stack. context.write(data, promise: promise) case .upgraderReady, .upgrading: promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade) context.fireErrorCaught(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade) case .upgradingAddingHandlers: // These are most likely messages immediately fired by a new protocol handler. // As that is added last we can just forward them on. context.write(data, promise: promise) case .upgradeComplete: // Upgrade complete and this handler should have been removed from the pipeline. promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) context.fireErrorCaught(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) case .upgradeFailed: // Upgrade failed and this handler should have been removed from the pipeline. promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) context.fireErrorCaught(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) } } private func addHeadersToOutboundOut(data: NIOAny) -> NIOAny { let interceptedOutgoingRequest = self.unwrapOutboundIn(data) if case .head(var requestHead) = interceptedOutgoingRequest { self.upgradeState = .awaitingConfirmationResponse self.addConnectionHeaders(to: &requestHead) self.addUpgradeHeaders(to: &requestHead) return self.wrapOutboundOut(.head(requestHead)) } return data } private func addConnectionHeaders(to requestHead: inout HTTPRequestHead) { let requiredHeaders = ["upgrade"] + self.upgraders.flatMap { $0.requiredUpgradeHeaders } requestHead.headers.add(name: "Connection", value: requiredHeaders.joined(separator: ",")) } private func addUpgradeHeaders(to requestHead: inout HTTPRequestHead) { let allProtocols = self.upgraders.map { $0.supportedProtocol.lowercased() } requestHead.headers.add(name: "Upgrade", value: allProtocols.joined(separator: ",")) // Allow each upgrader the chance to add custom headers. for upgrader in self.upgraders { upgrader.addCustom(upgradeRequestHeaders: &requestHead.headers) } } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { guard !self.seenFirstResponse else { // We're waiting for upgrade to complete: buffer this data. self.receivedMessages.append(data) return } let responsePart = unwrapInboundIn(data) switch self.upgradeState { case .awaitingConfirmationResponse: self.firstResponseHeadReceived(context: context, responsePart: responsePart) case .upgrading, .upgradingAddingHandlers: if case .end = responsePart { // This is the end of the first response. Swallow it, we're buffering the rest. self.seenFirstResponse = true } case .upgraderReady(let upgrade): if case .end = responsePart { // This is the end of the first response, and we can upgrade. Time to kick it off. self.seenFirstResponse = true upgrade() } case .upgradeFailed: // We were reentrantly called while delivering the response head. We can just pass this through. context.fireChannelRead(data) case .upgradeComplete: //Upgrade has completed but we have not seen a whole response and still got reentrantly called. context.fireErrorCaught(NIOHTTPClientUpgradeError.receivedResponseAfterUpgradeCompleted) case .requestRequired: //We are receiving an upgrade response and we have not requested the upgrade. context.fireErrorCaught(NIOHTTPClientUpgradeError.receivedResponseBeforeRequestSent) } } private func firstResponseHeadReceived(context: ChannelHandlerContext, responsePart: HTTPClientResponsePart) { // We should decide if we're can upgrade based on the first response header: if we aren't upgrading, // by the time the body comes in we should be out of the pipeline. That means that if we don't think we're // upgrading, the only thing we should see is a response head. Anything else in an error. guard case .head(let response) = responsePart else { self.notUpgrading(context: context, data: responsePart, error: .invalidHTTPOrdering) return } // Assess whether the upgrade response has accepted our upgrade request. guard case .switchingProtocols = response.status else { self.notUpgrading(context: context, data: responsePart, error: nil) return } do { let callback = try self.handleUpgrade(context: context, upgradeResponse: response) self.gotUpgrader(upgrader: callback) } catch { let clientError = error as? NIOHTTPClientUpgradeError self.notUpgrading(context: context, data: responsePart, error: clientError) } } private func handleUpgrade(context: ChannelHandlerContext, upgradeResponse response: HTTPResponseHead) throws -> (() -> Void) { // Ok, we have a HTTP response. Check if it's an upgrade confirmation. // If it's not, we want to pass it on and remove ourselves from the channel pipeline. let acceptedProtocols = response.headers[canonicalForm: "upgrade"] // At the moment we only upgrade to the first protocol returned from the server. guard let protocolName = acceptedProtocols.first?.lowercased() else { // There are no upgrade protocols returned. throw NIOHTTPClientUpgradeError.responseProtocolNotFound } return try self.handleUpgradeForProtocol(context: context, protocolName: protocolName, response: response) } /// Attempt to upgrade a single protocol. private func handleUpgradeForProtocol(context: ChannelHandlerContext, protocolName: String, response: HTTPResponseHead) throws -> (() -> Void) { let matchingUpgrader = self.upgraders .first(where: { $0.supportedProtocol.lowercased() == protocolName }) guard let upgrader = matchingUpgrader else { // There is no upgrader for this protocol. throw NIOHTTPClientUpgradeError.responseProtocolNotFound } guard upgrader.shouldAllowUpgrade(upgradeResponse: response) else { // The upgrader says no. throw NIOHTTPClientUpgradeError.upgraderDeniedUpgrade } return self.performUpgrade(context: context, upgrader: upgrader, response: response) } private func performUpgrade(context: ChannelHandlerContext, upgrader: NIOHTTPClientProtocolUpgrader, response: HTTPResponseHead) -> () -> Void { // Before we start the upgrade we have to remove the HTTPEncoder and HTTPDecoder handlers from the // pipeline, to prevent them parsing any more data. We'll buffer the incoming data until that completes. // While there are a lot of Futures involved here it's quite possible that all of this code will // actually complete synchronously: we just want to program for the possibility that it won't. // Once that's done, we call the internal handler, then call the upgrader code, and then finally when the // upgrader code is done, we do our final cleanup steps, namely we replay the received data we // buffered in the meantime and then remove ourselves from the pipeline. return { self.upgradeState = .upgrading self.removeHTTPHandlers(context: context) .map { // Let the other handlers be removed before continuing with upgrade. self.upgradeCompletionHandler(context) self.upgradeState = .upgradingAddingHandlers } .flatMap { upgrader.upgrade(context: context, upgradeResponse: response) } .map { // We unbuffer any buffered data here. // If we received any, we fire readComplete. let fireReadComplete = self.receivedMessages.count > 0 while self.receivedMessages.count > 0 { let bufferedPart = self.receivedMessages.removeFirst() context.fireChannelRead(bufferedPart) } if fireReadComplete { context.fireChannelReadComplete() } // We wait with the state change until _after_ the channel reads here. // This is to prevent firing writes in response to these reads after we went to .upgradeComplete // See: https://github.com/apple/swift-nio/issues/1279 self.upgradeState = .upgradeComplete } .whenComplete { _ in context.pipeline.removeHandler(context: context, promise: nil) } } } /// Removes any extra HTTP-related handlers from the channel pipeline. private func removeHTTPHandlers(context: ChannelHandlerContext) -> EventLoopFuture<Void> { guard self.httpHandlers.count > 0 else { return context.eventLoop.makeSucceededFuture(()) } let removeFutures = self.httpHandlers.map { context.pipeline.removeHandler($0) } return .andAllSucceed(removeFutures, on: context.eventLoop) } private func gotUpgrader(upgrader: @escaping (() -> Void)) { self.upgradeState = .upgraderReady(upgrader) if self.seenFirstResponse { // Ok, we're good to go, we can upgrade. Otherwise we're waiting for .end, which // will trigger the upgrade. upgrader() } } private func notUpgrading(context: ChannelHandlerContext, data: HTTPClientResponsePart, error: NIOHTTPClientUpgradeError?) { self.upgradeState = .upgradeFailed if let error = error { context.fireErrorCaught(error) } assert(self.receivedMessages.isEmpty) context.fireChannelRead(self.wrapInboundOut(data)) // We've delivered the data. We can now remove ourselves, which should happen synchronously. context.pipeline.removeHandler(context: context, promise: nil) } } extension NIOHTTPClientUpgradeHandler: @unchecked Sendable {} extension NIOHTTPClientUpgradeHandler { /// The state of the upgrade handler. fileprivate enum UpgradeState { /// Request not sent. This will need to be sent to initiate the upgrade. case requestRequired /// Awaiting confirmation response which will allow the upgrade to zero one or more protocols. case awaitingConfirmationResponse /// The response head has been received. We have an upgrader, which means we can begin upgrade. case upgraderReady(() -> Void) /// The response head has been received. The upgrade is in process. case upgrading /// The upgrade is in process and all of the http handlers have been removed. case upgradingAddingHandlers /// The upgrade has succeeded, and we are being removed from the pipeline. case upgradeComplete /// The upgrade has failed. case upgradeFailed } }
309432e82511424d7eaae5a6e1aeaa3b
46.687961
149
0.678397
false
false
false
false
ChenJian345/realm-cocoa
refs/heads/master
Pods/RealmSwift/RealmSwift/Util.swift
apache-2.0
4
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: Internal Helpers internal func notFoundToNil(index: UInt) -> Int? { if index == UInt(NSNotFound) { return nil } return Int(index) } internal func throwRealmException(message: String, userInfo: [String:AnyObject] = [:]) { NSException(name: RLMExceptionName, reason: message, userInfo: userInfo).raise() } internal func throwForNegativeIndex(int: Int, parameterName: String = "index") { if int < 0 { throwRealmException("Cannot pass a negative value for '\(parameterName)'.") } } internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? { do { let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0)) return regex.stringByReplacingMatchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: string.utf16.count), withTemplate: template) } catch { // no-op } return nil }
90827c4ec9ebf148e8613d13c58b9f33
35.285714
183
0.651294
false
false
false
false
TrustWallet/trust-wallet-ios
refs/heads/master
Trust/Transactions/Types/LocalizedOperationObject.swift
gpl-3.0
1
// Copyright DApps Platform Inc. All rights reserved. import Foundation import RealmSwift import TrustCore final class LocalizedOperationObject: Object, Decodable { @objc dynamic var from: String = "" @objc dynamic var to: String = "" @objc dynamic var contract: String? = .none @objc dynamic var type: String = "" @objc dynamic var value: String = "" @objc dynamic var name: String? = .none @objc dynamic var symbol: String? = .none @objc dynamic var decimals: Int = 18 convenience init( from: String, to: String, contract: String?, type: String, value: String, symbol: String?, name: String?, decimals: Int ) { self.init() self.from = from self.to = to self.contract = contract self.type = type self.value = value self.symbol = symbol self.name = name self.decimals = decimals } enum LocalizedOperationObjectKeys: String, CodingKey { case from case to case type case value case contract } convenience required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: LocalizedOperationObjectKeys.self) let from = try container.decode(String.self, forKey: .from) let to = try container.decode(String.self, forKey: .to) guard let fromAddress = EthereumAddress(string: from), let toAddress = EthereumAddress(string: to) else { let context = DecodingError.Context(codingPath: [LocalizedOperationObjectKeys.from, LocalizedOperationObjectKeys.to, ], debugDescription: "Address can't be decoded as a TrustKeystore.Address") throw DecodingError.dataCorrupted(context) } let type = try container.decode(OperationType.self, forKey: .type) let value = try container.decode(String.self, forKey: .value) let contract = try container.decode(ERC20Contract.self, forKey: .contract) self.init(from: fromAddress.description, to: toAddress.description, contract: contract.address, type: type.rawValue, value: value, symbol: contract.symbol, name: contract.name, decimals: contract.decimals ) } var operationType: OperationType { return OperationType(string: type) } }
60da331df068320882511bbca78dd8f6
32.987013
124
0.584639
false
false
false
false
gkaimakas/Ion
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import Ion class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } } } } }
0818d05d1848d26a9fedbad3ba3ec442
19.138889
60
0.387586
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Eurofurence/Modules/Dealer Detail/Interactor/DefaultDealerDetailViewModel.swift
mit
1
import EurofurenceModel import Foundation private protocol DetailViewModelComponent { func describe(to visitor: DealerDetailViewModelVisitor) } struct DefaultDealerDetailViewModel: DealerDetailViewModel { struct SummaryComponent: DetailViewModelComponent { var summary: DealerDetailSummaryViewModel func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(summary) } } struct LocationAndAvailabilityComponent: DetailViewModelComponent { var locationAndAvailability: DealerDetailLocationAndAvailabilityViewModel init?(locationAndAvailability: DealerDetailLocationAndAvailabilityViewModel) { guard locationAndAvailability.mapPNGGraphicData != nil || locationAndAvailability.limitedAvailabilityWarning != nil || locationAndAvailability.locatedInAfterDarkDealersDenMessage != nil else { return nil } self.locationAndAvailability = locationAndAvailability } func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(locationAndAvailability) } } struct AboutTheArtistComponent: DetailViewModelComponent { var aboutTheArtist: DealerDetailAboutTheArtistViewModel func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(aboutTheArtist) } } struct AboutTheArtComponent: DetailViewModelComponent { var aboutTheArt: DealerDetailAboutTheArtViewModel init?(aboutTheArt: DealerDetailAboutTheArtViewModel) { guard aboutTheArt.aboutTheArt != nil || aboutTheArt.artPreviewImagePNGData != nil || aboutTheArt.artPreviewImagePNGData != nil else { return nil } self.aboutTheArt = aboutTheArt } func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(aboutTheArt) } } private var components = [DetailViewModelComponent]() private let dealer: Dealer private let dealerIdentifier: DealerIdentifier private let dealersService: DealersService private let shareService: ShareService init(dealer: Dealer, data: ExtendedDealerData, dealerIdentifier: DealerIdentifier, dealersService: DealersService, shareService: ShareService) { self.dealer = dealer self.dealerIdentifier = dealerIdentifier self.dealersService = dealersService self.shareService = shareService let summary = DealerDetailSummaryViewModel(artistImagePNGData: data.artistImagePNGData, title: data.preferredName, subtitle: data.alternateName, categories: data.categories.joined(separator: ", "), shortDescription: data.dealerShortDescription, website: data.websiteName, twitterHandle: data.twitterUsername, telegramHandle: data.telegramUsername) let summaryComponent = SummaryComponent(summary: summary) components.append(summaryComponent) var afterDarkMessage: String? if data.isAfterDark { afterDarkMessage = .locatedWithinAfterDarkDen } let limitedAvailabilityMessage = prepareLimitedAvailabilityMessage(data) let locationAndAvailability = DealerDetailLocationAndAvailabilityViewModel(title: .locationAndAvailability, mapPNGGraphicData: data.dealersDenMapLocationGraphicPNGData, limitedAvailabilityWarning: limitedAvailabilityMessage, locatedInAfterDarkDealersDenMessage: afterDarkMessage) if let locationAndAvailabilityComponent = LocationAndAvailabilityComponent(locationAndAvailability: locationAndAvailability) { components.append(locationAndAvailabilityComponent) } var aboutTheArtistText: String = .aboutTheArtistPlaceholder if let text = data.aboutTheArtist { aboutTheArtistText = text } let aboutTheArtist = DealerDetailAboutTheArtistViewModel(title: .aboutTheArtist, artistDescription: aboutTheArtistText) let aboutTheArtistComponent = AboutTheArtistComponent(aboutTheArtist: aboutTheArtist) components.append(aboutTheArtistComponent) let aboutTheArt = DealerDetailAboutTheArtViewModel(title: .aboutTheArt, aboutTheArt: data.aboutTheArt, artPreviewImagePNGData: data.artPreviewImagePNGData, artPreviewCaption: data.artPreviewCaption) if let aboutTheArtComponent = AboutTheArtComponent(aboutTheArt: aboutTheArt) { components.append(aboutTheArtComponent) } } private func prepareLimitedAvailabilityMessage(_ data: ExtendedDealerData) -> String? { var limitedAvailabilityMessage: String? if !data.isAttendingOnThursday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Friday", "Saturday"]) } if !data.isAttendingOnFriday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Thursday", "Saturday"]) } if !data.isAttendingOnSaturday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Thursday", "Friday"]) } if !data.isAttendingOnFriday && !data.isAttendingOnSaturday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Thursday"]) } if !data.isAttendingOnThursday && !data.isAttendingOnSaturday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Friday"]) } if !data.isAttendingOnThursday && !data.isAttendingOnFriday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Saturday"]) } return limitedAvailabilityMessage } var numberOfComponents: Int { return components.count } func describeComponent(at index: Int, to visitor: DealerDetailViewModelVisitor) { guard index < components.count else { return } components[index].describe(to: visitor) } func openWebsite() { dealer.openWebsite() } func openTwitter() { dealer.openTwitter() } func openTelegram() { dealer.openTelegram() } func shareDealer(_ sender: Any) { let url = dealer.makeContentURL() shareService.share(url, sender: sender) } }
34b5aa2dd3e21a495fc6c4bba26cc7d4
37.367021
143
0.626369
false
false
false
false
kenwilcox/TheForecaster
refs/heads/master
TheForecaster/ViewController.swift
mit
1
// // ViewController.swift // TheForecaster // // Created by Kenneth Wilcox on 5/12/15. // Copyright (c) 2015 Kenneth Wilcox. All rights reserved. // import UIKit import WeatherShare class ViewController: UIViewController { @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var weatherImageView: UIImageView! @IBOutlet weak var weatherConditionsLabel: UILabel! @IBOutlet weak var updateDateLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "locationDidUpdate:", name: GlobalConstants.NotificationNames.locationDidUpdate, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func refreshWeatherButtonPressed(sender: UIButton) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.locationController?.locationManager.stopUpdatingLocation() appDelegate.locationController?.locationManager.startUpdatingLocation() } func locationDidUpdate(notification: NSNotification) { println("locationAvaliable") let locationDictionary = notification.userInfo as! Dictionary<String,AnyObject> let latitude = locationDictionary[GlobalConstants.LocationDictionary.latitude] as! Double let longitude = locationDictionary[GlobalConstants.LocationDictionary.longitude] as! Double let city = locationDictionary[GlobalConstants.LocationDictionary.city] as! String let state = locationDictionary[GlobalConstants.LocationDictionary.state] as! String let country = locationDictionary[GlobalConstants.LocationDictionary.country] as! String let lastUpdatedAt = locationDictionary[GlobalConstants.LocationDictionary.timestamp] as! NSDate println(locationDictionary) //locationLabel.text = "\(city), \(state) (\(country))" ForecastNetwork.requestWeather(latitude: latitude, longitude: longitude) { (responseDictionary) -> () in println(responseDictionary) if responseDictionary != nil { dispatch_async(dispatch_get_main_queue()) { let currentConditionsDictionary = responseDictionary![GlobalConstants.ForecastNetwork.currently] as! NSDictionary let iconName = currentConditionsDictionary[GlobalConstants.ForecastNetwork.icon] as! String self.weatherImageView.image = UIImage(named: iconName) let temperature = currentConditionsDictionary[GlobalConstants.ForecastNetwork.temperature] as! Double self.temperatureLabel.text = "\(temperature) ℉" let conditions = currentConditionsDictionary[GlobalConstants.ForecastNetwork.summary] as! String self.weatherConditionsLabel.text = conditions self.locationLabel.text = "\(city), \(state), \(country)" let formattedDate = NSDateFormatter.localizedStringFromDate(lastUpdatedAt, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.MediumStyle) self.updateDateLabel.text = formattedDate } } else { println("No Response: could not update") } } } }
b55b78ed412d838f830f4893c6a70c89
42.571429
174
0.743964
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/MultiDelay Example.xcplaygroundpage/Contents.swift
mit
1
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## MultiDelay Example //: ### This is similar to the MultiDelay implemented in the Analog Synth X example project. import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("drumloop", ofType: "wav") //: Here we set up a player to the loop the file's playback var player = AKAudioPlayer(file!) player.looping = true func multitapDelay(input: AKNode, times: [Double], gains: [Double]) -> AKMixer { let mix = AKMixer(input) zip(times, gains).forEach { (time, gain) -> () in let delay = AKVariableDelay(input, time: time, feedback: 0.0) mix.connect(AKBooster(delay, gain: gain)) } return mix } // Delay Properties var delayTime = 0.2 // Seconds var delayMix = 0.4 // 0 (dry) - 1 (wet) let gains = [0.5, 0.25, 0.15].map { g -> Double in g * delayMix } let input = player // Delay Definition let leftDelay = multitapDelay(input, times: [1.5, 2.5, 3.5].map { t -> Double in t * delayTime }, gains: gains) let rightDelay = multitapDelay(input, times: [1, 2, 3].map { t -> Double in t * delayTime }, gains: gains) let delayPannedLeft = AKPanner(leftDelay, pan: -1) let delayPannedRight = AKPanner(rightDelay, pan: 1) let mix = AKMixer(delayPannedLeft, delayPannedRight) AudioKit.output = mix AudioKit.start() player.play() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
422288393bc5d62cfe832ebfc0d708f3
29.94
92
0.676794
false
false
false
false
lenssss/whereAmI
refs/heads/master
Whereami/Controller/Personal/PersonalTravelFollowViewController.swift
mit
1
// // PersonalTravelFollowViewController.swift // Whereami // // Created by A on 16/5/17. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class PersonalTravelFollowViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { typealias theCallback = ([AnyObject]) -> Void var type:String? = nil var tableView:UITableView? = nil var models:[FriendsModel]? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setConfig() self.setUI() } /* override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.backgroundColor = UIColor.getMainColor() self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default) self.navigationController?.navigationBar.barTintColor = UIColor.getMainColor() } */ func setUI(){ let backBtn = TheBackBarButton.initWithAction({ let viewControllers = self.navigationController?.viewControllers let index = (viewControllers?.count)! - 2 let viewController = viewControllers![index] self.navigationController?.popToViewController(viewController, animated: true) }) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) self.tableView = UITableView() self.tableView?.separatorStyle = .None self.tableView?.delegate = self self.tableView?.dataSource = self self.view.addSubview(self.tableView!) self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0, 0, 0, 0)) self.tableView?.registerClass(ContactItemTableViewCell.self, forCellReuseIdentifier: "ContactItemTableViewCell") } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.models != nil { return (self.models?.count)! } return 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70.0; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ContactItemTableViewCell", forIndexPath: indexPath) as! ContactItemTableViewCell cell.selectionStyle = .None let user = self.models![indexPath.row] let avatarUrl = user.headPortrait != nil ? user.headPortrait : "" cell.avatar?.kf_setImageWithURL(NSURL(string:avatarUrl!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.chatName?.text = user.nickname cell.location?.text = "chengdu,China" cell.callBack = {(button) -> Void in self.addFriend(indexPath, cell: cell) } cell.addButton?.hidden = false if user.friendId == UserModel.getCurrentUser()!.id { cell.addButton?.hidden = true } cell.addButton?.setTitle(NSLocalizedString("add",tableName:"Localizable", comment: ""), forState: .Normal) if self.models != nil { let friendModel = models![indexPath.row] let friend = CoreDataManager.sharedInstance.fetchFriendByFriendId(friendModel.accountId!, friendId: friendModel.friendId!) if friend != nil { cell.addButton?.setTitle(NSLocalizedString("added",tableName:"Localizable", comment: ""), forState: .Normal) } } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let friendModel:FriendsModel = models![indexPath.row] let personalVC = TourRecordsViewController() personalVC.userId = friendModel.friendId personalVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(personalVC, animated: true) } func addFriend(indexPath:NSIndexPath,cell:ContactItemTableViewCell){ var dict = [String: AnyObject]() dict["accountId"] = UserModel.getCurrentUser()?.id dict["friendId"] = models![indexPath.row].friendId SocketManager.sharedInstance.sendMsg("addFreind", data: dict, onProto: "addFreinded", callBack: { (code, objs) in if code == statusCode.Normal.rawValue { let friend = self.models![indexPath.row] var dic = [String:AnyObject]() dic["searchIds"] = [friend.friendId!] SocketManager.sharedInstance.sendMsg("getUserDatasByUserIds", data: dic, onProto: "getUserDatasByUserIdsed") { (code, objs) in if code == statusCode.Normal.rawValue { let userData = objs[0]["userData"] as! [AnyObject] let user = UserModel.getModelFromDictionary(userData[0] as! NSDictionary) CoreDataManager.sharedInstance.increaseOrUpdateUser(user) } } CoreDataManager.sharedInstance.increaseFriends(friend) self.runInMainQueue({ cell.addButton?.setTitle(NSLocalizedString("added",tableName:"Localizable", comment: ""), forState: .Normal) cell.addButton?.enabled = false }) } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
fa23571936c130e21314dcd0b13a8f88
42.572519
176
0.647162
false
false
false
false
zisko/swift
refs/heads/master
test/SILOptimizer/outliner.swift
apache-2.0
1
// RUN: %target-swift-frontend -Osize -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s // RUN: %target-swift-frontend -Osize -g -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s // REQUIRES: objc_interop import Foundation public class MyGizmo { private var gizmo : Gizmo private var optionalGizmo : Gizmo? init() { gizmo = Gizmo() } // CHECK-LABEL: sil @$S8outliner7MyGizmoC11usePropertyyyF // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTeab_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK-NOT: return // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK: return public func useProperty() { print(gizmo.stringProperty) print(optionalGizmo!.stringProperty) } } // CHECK-LABEL: sil @$S8outliner13testOutliningyyF // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTepb_ // CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvsToTembnn_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> () // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> () // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> // CHECK: return public func testOutlining() { let gizmo = Gizmo() let foobar = Gizmo() print(gizmo.stringProperty) print(gizmo.stringProperty) gizmo.stringProperty = "foobar" gizmo.stringProperty = "foobar2" gizmo.modifyString("hello", withNumber:1, withFoobar: foobar) gizmo.modifyString("hello", withNumber:1, withFoobar: foobar) let arr = [ "foo", "bar"] gizmo.doSomething(arr) gizmo.doSomething(arr) } // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTeab_ : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK: bb0(%0 : $*Gizmo): // CHECK: %1 = load %0 : $*Gizmo // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String? // CHECK: %3 = apply %2(%1) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString> // CHECK: switch_enum %3 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2 // CHECK: bb1(%5 : $NSString): // CHECK: %6 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %7 = metatype $@thin String.Type // CHECK: %8 = apply %6(%3, %7) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %9 = enum $Optional<String>, #Optional.some!enumelt.1, %8 : $String // CHECK: br bb3(%9 : $Optional<String>) // CHECK: bb2: // CHECK: %11 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%11 : $Optional<String>) // CHECK: bb3(%13 : $Optional<String>): // CHECK: return %13 : $Optional<String> // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTepb_ : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: bb0(%0 : $Gizmo): // CHECK: %1 = objc_method %0 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String? // CHECK: %2 = apply %1(%0) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString> // CHECK: switch_enum %2 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2 // CHECK:bb1(%4 : $NSString): // CHECK: %5 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %6 = metatype $@thin String.Type // CHECK: %7 = apply %5(%2, %6) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %8 = enum $Optional<String>, #Optional.some!enumelt.1, %7 : $String // CHECK: br bb3(%8 : $Optional<String>) // CHECK:bb2: // CHECK: %10 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%10 : $Optional<String>) // CHECK:bb3(%12 : $Optional<String>): // CHECK: return %12 : $Optional<String> // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvsToTembnn_ : $@convention(thin) (@owned String, Gizmo) -> () { // CHECK: bb0(%0 : $String, %1 : $Gizmo): // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!setter.1.foreign : (Gizmo) -> (String?) -> () // CHECK: %3 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: %4 = apply %3(%0) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: release_value %0 : $String // CHECK: %6 = enum $Optional<NSString>, #Optional.some!enumelt.1, %4 : $NSString // CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSString>, Gizmo) -> () // CHECK: strong_release %4 : $NSString // CHECK: return %7 : $() // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> { // CHECK: bb0(%0 : $String, %1 : $Int, %2 : $Optional<AnyObject>, %3 : $Gizmo): // CHECK: %4 = objc_method %3 : $Gizmo, #Gizmo.modifyString!1.foreign : (Gizmo) -> (String?, Int, Any?) -> String? // CHECK: %5 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: %6 = apply %5(%0) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: release_value %0 : $String // CHECK: %8 = enum $Optional<NSString>, #Optional.some!enumelt.1, %6 : $NSString // CHECK: %9 = apply %4(%8, %1, %2, %3) : $@convention(objc_method) (Optional<NSString>, Int, Optional<AnyObject>, Gizmo) -> @autoreleased Optional<NSString> // CHECK: strong_release %6 : $NSString // CHECK: switch_enum %9 : $Optional<NSString>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1 // // CHECK: bb1: // CHECK: %12 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%12 : $Optional<String>) // // CHECK: bb2(%14 : $NSString): // CHECK: %15 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %16 = metatype $@thin String.Type // CHECK: %17 = apply %15(%9, %16) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %18 = enum $Optional<String>, #Optional.some!enumelt.1, %17 : $String // CHECK: br bb3(%18 : $Optional<String>) // // CHECK: bb3(%20 : $Optional<String>): // CHECK: return %20 : $Optional<String> // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_ : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> { // CHECK: bb0(%0 : $Array<String>, %1 : $Gizmo): // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.doSomething!1.foreign : (Gizmo) -> ([String]?) -> Any? // CHECK: %3 = function_ref @$SSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray // CHECK: %4 = apply %3<String>(%0) : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray // CHECK: release_value %0 : $Array<String> // CHECK: %6 = enum $Optional<NSArray>, #Optional.some!enumelt.1, %4 : $NSArray // CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSArray>, Gizmo) -> @autoreleased Optional<AnyObject> // CHECK: strong_release %4 : $NSArray // CHECK: return %7 : $Optional<AnyObject> public func dontCrash<T: Proto>(x : Gizmo2<T>) { let s = x.doSomething() print(s) } public func dontCrash2(_ c: SomeGenericClass) -> Bool { guard let str = c.version else { return false } guard let str2 = c.doSomething() else { return false } let arr = [ "foo", "bar"] c.doSomething2(arr) return true }
b0416e7f2815356a80a306f29f325d16
56.5
211
0.661315
false
false
false
false
spritesun/MeditationHelper
refs/heads/master
MeditationHelper/MeditationHelper/MHMigrator.swift
mit
1
// // MHMigrator.swift // MeditationHelper // // Created by Long Sun on 22/01/2015. // Copyright (c) 2015 Sunlong. All rights reserved. // struct MHMigrator { private init () {} static func migrate () { // migrateMeditationCommentToCommentRaw() } // static func migrateMeditationCommentToCommentRaw() { // let query = MHMeditation.query() // query.findObjectsInBackgroundWithBlock({ (meditations, error) -> Void in // if error == nil { // for meditation in meditations as [MHMeditation] { // meditation.commentRaw = meditation.comment?.dataUsingEncoding(NSUTF8StringEncoding) // meditation.comment = nil // println("\(meditation) migrated") // meditation.saveInBackground() // } // } // }) // } }
1c229370ee9295b8c558aee01bbef5a9
25.3
95
0.633714
false
false
false
false
OEASLAN/OEANotification
refs/heads/master
Classes/OEANotification.swift
mit
1
// // OEANotification.swift // OEANotification // // Created by Ömer Emre Aslan on 15/11/15. // Copyright © 2015 omer. All rights reserved. // import UIKit public class OEANotification : UIView { static let constant = Constants() static var rect = CGRectMake(constant.nvMarginLeft, constant.nvStartYPoint, OEANotification.viewController.view.frame.width - constant.nvMarginLeft - constant.nvMarginRight, constant.nvHeight) static var viewController: UIViewController! static var notificationCount = 0 static var rotated:Bool = false // MARK: - Initial notification methods /** Initial static method of creating notification. - since: 0.1.0 - author: @OEASLAN - [email protected] - parameter title: The title of notification. - parameter subTitle: The subtitle of notification. - parameter type: The type of notification which are Success, Warning, and Info. - parameter isDismissable: The notification center from which the notification should be dispatched. - return: void */ static public func notify( title: String, subTitle: String, type: NotificationType, isDismissable: Bool ){ self.notify(title, subTitle: subTitle, image: nil, type: type, isDismissable: isDismissable) } /** Initial static method of creating notification. - since: 0.1.0 - author: @OEASLAN - [email protected] - parameter title: The title of notification. - parameter subTitle: The subtitle of notification. - parameter type: The type of notification which are Success, Warning, and Info. - parameter image: The main icon image of notification like avatar, success, warning etc. icons - parameter isDismissable: The notification center from which the notification should be dispatched. - return: void */ static public func notify( title: String, subTitle: String, image: UIImage?, type: NotificationType, isDismissable: Bool ) { self.notify(title, subTitle: subTitle, image: image, type: type, isDismissable: isDismissable, completion: nil, touchHandler: nil) } /** Initial static method of creating notification. - since: 0.1.0 - author: @OEASLAN - [email protected] - parameter title: The title of notification. - parameter subTitle: The subtitle of notification. - parameter type: The type of notification which are Success, Warning, and Info. - parameter image: The main icon image of notification like avatar, success, warning etc. icons - parameter completion: The main icon image of notification like avatar, success, warning etc. icons - parameter isDismissable: The notification center from which the notification should be dispatched. - return: void */ static public func notify( title: String, subTitle: String, image: UIImage?, type: NotificationType, isDismissable: Bool, completion: (() -> Void)?, touchHandler: (() ->Void)? ) { let notificationView: NotificationView = NotificationView( frame: rect, title: title, subTitle: subTitle, image: image, type: type, completionHandler: completion, touchHandler: touchHandler, isDismissable: isDismissable ) OEANotification.notificationCount++ OEANotification.removeOldNotifications() print(OEANotification.viewController.view.frame) if OEANotification.viewController.navigationController != nil { OEANotification.viewController.navigationController!.view.addSubview(notificationView) } else { OEANotification.viewController.view.addSubview(notificationView) } } /** Sets the default view controller as a main view controller. - since: 0.1.0 - author: @OEASLAN - [email protected] - parameter viewController: The main controller which shows the notification. - return: void */ static public func setDefaultViewController (viewController: UIViewController) { self.viewController = viewController NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotateRecognizer", name: UIDeviceOrientationDidChangeNotification, object: nil) } // MARK: - Helper methods static public func removeOldNotifications() { if OEANotification.viewController.navigationController != nil { for subUIView in OEANotification.viewController.navigationController!.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.notificationTimer.invalidate() subUIView.removeFromSuperview() OEANotification.notificationCount-- } } } else { for subUIView in OEANotification.viewController.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.notificationTimer.invalidate() subUIView.removeFromSuperview() OEANotification.notificationCount-- } } } } // Close active notification static public func closeNotification() { if OEANotification.viewController.navigationController != nil { for subUIView in OEANotification.viewController.navigationController!.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.close() } } } else { for subUIView in OEANotification.viewController.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.close() } } } } // Checking device's rotation process and remove notifications to handle UI conflicts. static public func rotateRecognizer() { removeOldNotifications() UIApplication.sharedApplication().delegate?.window??.windowLevel = UIWindowLevelNormal self.rect = CGRectMake(constant.nvMarginLeft, constant.nvStartYPoint, OEANotification.viewController.view.frame.width - constant.nvMarginLeft - constant.nvMarginRight, constant.nvHeight) } } public enum NotificationType { case Warning case Success case Info }
8255ec88fbf554bf0cb62096ef6443b1
39.10929
196
0.613079
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
Pods/QRCodeReader.swift/Sources/QRCodeReaderView.swift
mit
1
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.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 UIKit final public class QRCodeReaderView: UIView, QRCodeReaderDisplayable { public lazy var overlayView: UIView? = { let ov = ReaderOverlayView() ov.backgroundColor = .clear ov.clipsToBounds = true ov.translatesAutoresizingMaskIntoConstraints = false return ov }() public let cameraView: UIView = { let cv = UIView() cv.clipsToBounds = true cv.translatesAutoresizingMaskIntoConstraints = false return cv }() public lazy var cancelButton: UIButton? = { let cb = UIButton() cb.translatesAutoresizingMaskIntoConstraints = false cb.setTitleColor(.gray, for: .highlighted) return cb }() public lazy var switchCameraButton: UIButton? = { let scb = SwitchCameraButton() scb.translatesAutoresizingMaskIntoConstraints = false return scb }() public lazy var toggleTorchButton: UIButton? = { let ttb = ToggleTorchButton() ttb.translatesAutoresizingMaskIntoConstraints = false return ttb }() private weak var reader: QRCodeReader? public func setupComponents(showCancelButton: Bool, showSwitchCameraButton: Bool, showTorchButton: Bool, showOverlayView: Bool, reader: QRCodeReader?) { self.reader = reader reader?.lifeCycleDelegate = self addComponents() cancelButton?.isHidden = !showCancelButton switchCameraButton?.isHidden = !showSwitchCameraButton toggleTorchButton?.isHidden = !showTorchButton overlayView?.isHidden = !showOverlayView guard let cb = cancelButton, let scb = switchCameraButton, let ttb = toggleTorchButton, let ov = overlayView else { return } let views = ["cv": cameraView, "ov": ov, "cb": cb, "scb": scb, "ttb": ttb] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: [], metrics: nil, views: views)) if showCancelButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv][cb(40)]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cb]-|", options: [], metrics: nil, views: views)) } else { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv]|", options: [], metrics: nil, views: views)) } if showSwitchCameraButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[scb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[scb(70)]|", options: [], metrics: nil, views: views)) } if showTorchButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[ttb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[ttb(70)]", options: [], metrics: nil, views: views)) } for attribute in Array<NSLayoutAttribute>([.left, .top, .right, .bottom]) { addConstraint(NSLayoutConstraint(item: ov, attribute: attribute, relatedBy: .equal, toItem: cameraView, attribute: attribute, multiplier: 1, constant: 0)) } } public override func layoutSubviews() { super.layoutSubviews() reader?.previewLayer.frame = bounds } // MARK: - Scan Result Indication func startTimerForBorderReset() { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) { if let ovl = self.overlayView as? ReaderOverlayView { ovl.overlayColor = .white } } } func addRedBorder() { self.startTimerForBorderReset() if let ovl = self.overlayView as? ReaderOverlayView { ovl.overlayColor = .red } } func addGreenBorder() { self.startTimerForBorderReset() if let ovl = self.overlayView as? ReaderOverlayView { ovl.overlayColor = .green } } @objc public func setNeedsUpdateOrientation() { setNeedsDisplay() overlayView?.setNeedsDisplay() if let connection = reader?.previewLayer.connection, connection.isVideoOrientationSupported { let application = UIApplication.shared let orientation = UIDevice.current.orientation let supportedInterfaceOrientations = application.supportedInterfaceOrientations(for: application.keyWindow) connection.videoOrientation = QRCodeReader.videoOrientation(deviceOrientation: orientation, withSupportedOrientations: supportedInterfaceOrientations, fallbackOrientation: connection.videoOrientation) } } // MARK: - Convenience Methods private func addComponents() { NotificationCenter.default.addObserver(self, selector: #selector(self.setNeedsUpdateOrientation), name: .UIDeviceOrientationDidChange, object: nil) addSubview(cameraView) if let ov = overlayView { addSubview(ov) } if let scb = switchCameraButton { addSubview(scb) } if let ttb = toggleTorchButton { addSubview(ttb) } if let cb = cancelButton { addSubview(cb) } if let reader = reader { cameraView.layer.insertSublayer(reader.previewLayer, at: 0) setNeedsUpdateOrientation() } } } extension QRCodeReaderView: QRCodeReaderLifeCycleDelegate { func readerDidStartScanning() { setNeedsUpdateOrientation() } func readerDidStopScanning() {} }
4ac81615ed93d2703bc1a8045c716033
32.065327
206
0.700152
false
false
false
false
Nimbow/Client-iOS
refs/heads/master
client/client/NimbowApiClientAsync.swift
mit
1
// // NimbowApiClientAsync.swift // client // // Created by Awesome Developer on 17/01/16. // Copyright © 2015 Nimbow. All rights reserved. // public class NimbowApiClientAsync { public static let SharedInstance = NimbowApiClientAsync() private var infoValues: NSDictionary! private init() { let filePath = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")! self.infoValues = NSDictionary(contentsOfFile:filePath) } var baseUrl: String { return infoValues["Nimbow.Api.Url"] as! String } var apiKey: String { return infoValues["Nimbow.Api.Key"] as! String } public func SendSmsAsync(request: Sms, completitionHandler: (response: SendSmsResponse) -> ()) throws { let url = NSURL(string: baseUrl + "sms.json") let session = NSURLSession.sharedSession() let mutableRequest = NSMutableURLRequest(URL: url!) mutableRequest.setValue(apiKey, forHTTPHeaderField: "X-Nimbow-API-Key") mutableRequest.HTTPMethod = "POST" mutableRequest.HTTPBody = try request.ToSendSmsRequest().ToQueryParameterString().dataUsingEncoding(NSUTF8StringEncoding) let task = session.dataTaskWithRequest(mutableRequest, completionHandler: {(data, response, error) in let responseStr = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String let response = SendSmsResponse.FromString(responseStr) completitionHandler(response: response) }) task.resume() } public func GetBalanceAsync(completitionHandler: (response: GetBalanceResponse) -> ()) throws { let url = NSURL(string: baseUrl + "balance.json") let session = NSURLSession.sharedSession() let mutableRequest = NSMutableURLRequest(URL: url!) mutableRequest.setValue(apiKey, forHTTPHeaderField: "X-Nimbow-API-Key") mutableRequest.HTTPMethod = "POST" mutableRequest.HTTPBody = try GetBalanceRequest(getDT: true, getTS: true, getFMC: true).ToQueryParameterString().dataUsingEncoding(NSUTF8StringEncoding) let task = session.dataTaskWithRequest(mutableRequest, completionHandler: {(data, response, error) in let responseStr = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String let response = GetBalanceResponse.FromString(responseStr) completitionHandler(response: response) }) task.resume() } }
025f05c4eb200f070012256806d02bdd
40.766667
160
0.68024
false
false
false
false
dukemedicine/Duke-Medicine-Mobile-Companion
refs/heads/master
Classes/Utilities/MCHaikuOrCanto.swift
mit
1
// // MCHaikuOrCanto.swift // Duke Medicine Mobile Companion // // Created by Ricky Bloomfield on 7/7/14. // Copyright (c) 2014 Duke Medicine // // 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 /** Opens the Canto app */ func openCanto() { UIApplication.sharedApplication().openURL(NSURL(string: "epiccanto://")!) } /** Opens the Haiku app */ func openHaiku() { UIApplication.sharedApplication().openURL(NSURL(string: "epichaiku://")!) } /** Opens the App Store to the Canto app */ func downloadCanto() { UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/us/app/epic-canto/id395395172?mt=8")!) } /** Opens the App Store to the Haiku app */ func downloadHaiku() { UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/us/app/epic-haiku/id348308661?mt=8")!) } /** Returns the string "Haiku" or "Canto" based on whether each is installed. If on iPad and both are installed, returns the preference in settings */ func HaikuOrCanto() -> String! { let HaikuInstalled: Bool = UIApplication.sharedApplication().canOpenURL(NSURL(string: "epichaiku://")!) let CantoInstalled: Bool = UIApplication.sharedApplication().canOpenURL(NSURL(string: "epiccanto://")!) if IPAD() { if HaikuInstalled && CantoInstalled { return USER_DEFAULTS().objectForKey("returnTo") as String } else if (HaikuInstalled) { return "Haiku" } else if (CantoInstalled) { return "Canto" } } else if (HaikuInstalled) { return "Haiku" } return nil } /** Opens the appropriate app based on app availability and preference (per HaikuOrCanto() function above) */ func openHaikuOrCanto() { if HaikuOrCanto()? == "Haiku" {openHaiku()} else if HaikuOrCanto()? == "Canto" {openCanto()} }
2e2ad6fb019361246cafe33cba58a0f0
33.247059
144
0.704811
false
false
false
false
bravelocation/yeltzland-ios
refs/heads/main
watchkitapp Extension/Views/GamesListView.swift
mit
1
// // FixtureListView.swift // watchkitapp Extension // // Created by John Pollard on 25/10/2019. // Copyright © 2019 John Pollard. All rights reserved. // import SwiftUI struct GamesListView: View { @ObservedObject var fixtureData: FixtureData var selection: FixtureData.FixtureSelection var body: some View { VStack { if self.fixtureData.state != .isLoading && self.fixtureData.fixturesAvailable(selection: self.selection) == false { Text("No games").padding() } List(self.fixtureData.allFixtures(selection: self.selection, reverseOrder: selection == .resultsOnly), id: \.self) { fixture in HStack { Group { if fixture.status == .fixture || fixture.status == .inProgress { FixtureView(fixture: fixture, teamImage: self.fixtureData.teamImage(fixture)) } else { ResultView(fixture: fixture, teamImage: self.fixtureData.teamImage(fixture), resultColor: self.resultColor(fixture)) } } Spacer() } .listRowPlatterColor(Color("dark-blue")) } .listStyle(CarouselListStyle()) } .overlay( Button(action: { self.fixtureData.refreshData() }, label: { Image(systemName: "arrow.clockwise") .font(.footnote) .padding() }) .frame(width: 24.0, height: 24.0, alignment: .center) .background(Color.gray.opacity(0.5)) .cornerRadius(12), alignment: .topTrailing ) .foregroundColor(Color("light-blue")) .onAppear { self.fixtureData.refreshData() } .navigationBarTitle(Text(self.fixtureData.state == .isLoading ? "Loading ..." : self.navTitle)) } var navTitle: String { switch self.selection { case .resultsOnly: return "Results" case .fixturesOnly: return "Fixtures" default: return "" } } func resultColor(_ fixture: TimelineFixture) -> Color { switch fixture.result { case .win: return Color("watch-fixture-win") case .lose: return Color("watch-fixture-lose") default: return Color("watch-fixture-draw") } } } #if DEBUG struct GamesListView_Previews: PreviewProvider { static var previews: some View { Group { GamesListView( fixtureData: AllGamesData(fixtureManager: PreviewFixtureManager(), gameScoreManager: PreviewGameScoreManager(), useResults: false) ) GamesListView( fixtureData: AllGamesData(fixtureManager: PreviewFixtureManager(), gameScoreManager: PreviewGameScoreManager(), useResults: true) ) } } } #endif
4b95bbe627d2d49259534ae9a88e97a7
31.571429
146
0.52381
false
false
false
false
BrandonMA/SwifterUI
refs/heads/master
Pods/DeepDiff/Sources/Shared/DiffAware.swift
mit
1
// // DiffAware.swift // DeepDiff // // Created by khoa on 22/02/2019. // Copyright © 2019 Khoa Pham. All rights reserved. // import Foundation /// Model must conform to DiffAware for diffing to work properly /// diffId: Each object must be uniquely identified by id. This is to tell if there is deletion or insertion /// compareContent: An object can change some properties but having its id intact. This is to tell if there is replacement public protocol DiffAware { var diffId: Int { get } static func compareContent(_ a: Self, _ b: Self) -> Bool } extension String: DiffAware { public var diffId: Int { return hashValue } public static func compareContent(_ a: String, _ b: String) -> Bool { return a == b } } extension Character: DiffAware { public var diffId: Int { return hashValue } public static func compareContent(_ a: Character, _ b: Character) -> Bool { return a == b } } extension Int: DiffAware { public var diffId: Int { return hashValue } public static func compareContent(_ a: Int, _ b: Int) -> Bool { return a == b } }
149b21b373322bfa508ba9b38a5998bd
22.446809
122
0.676951
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Media/CameraCaptureCoordinator.swift
gpl-2.0
1
import MobileCoreServices /// Encapsulates capturing media from a device camera final class CameraCaptureCoordinator { private var capturePresenter: WPMediaCapturePresenter? private weak var origin: UIViewController? func presentMediaCapture(origin: UIViewController, blog: Blog) { self.origin = origin capturePresenter = WPMediaCapturePresenter(presenting: origin) capturePresenter!.completionBlock = { [weak self] mediaInfo in if let mediaInfo = mediaInfo as NSDictionary? { self?.processMediaCaptured(mediaInfo, blog: blog) } self?.capturePresenter = nil } capturePresenter!.presentCapture() } private func processMediaCaptured(_ mediaInfo: NSDictionary, blog: Blog, origin: UIViewController? = nil) { let completionBlock: WPMediaAddedBlock = { media, error in if error != nil || media == nil { print("Adding media failed: ", error?.localizedDescription ?? "no media") return } guard let media = media as? PHAsset, blog.canUploadAsset(media) else { if let origin = origin ?? self.origin { self.presentVideoLimitExceededAfterCapture(on: origin) } return } let info = MediaAnalyticsInfo(origin: .mediaLibrary(.camera), selectionMethod: .fullScreenPicker) MediaCoordinator.shared.addMedia(from: media, to: blog, analyticsInfo: info) } guard let mediaType = mediaInfo[UIImagePickerController.InfoKey.mediaType.rawValue] as? String else { return } switch mediaType { case String(kUTTypeImage): if let image = mediaInfo[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage, let metadata = mediaInfo[UIImagePickerController.InfoKey.mediaMetadata.rawValue] as? [AnyHashable: Any] { WPPHAssetDataSource().add(image, metadata: metadata, completionBlock: completionBlock) } case String(kUTTypeMovie): if let mediaURL = mediaInfo[UIImagePickerController.InfoKey.mediaURL.rawValue] as? URL { WPPHAssetDataSource().addVideo(from: mediaURL, completionBlock: completionBlock) } default: break } } } /// User messages for video limits allowances extension CameraCaptureCoordinator: VideoLimitsAlertPresenter {}
7a9247473e3cd108ec66f618ba88f5bf
41.898305
121
0.638483
false
false
false
false
MChainZhou/DesignPatterns
refs/heads/master
Birdge/Birdge/Bridge/Simple_4_优化代码/VerticalProgress.swift
mit
1
// // VerticalProgress.swift // Birdge // // Created by apple on 2017/8/29. // Copyright © 2017年 apple. All rights reserved. // import UIKit class VerticalProgress: BaseProgress { override func getRect() -> CGRect { return CGRect(x: 100, y: 100, width: 50, height: 20) } override func draw(view: UIView) { for index in 0..<self.sportCount { let layer = CAShapeLayer() layer.fillColor = UIColor.black.cgColor layer.strokeColor = UIColor.black.cgColor layer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 4, height: 4)).cgPath let y = CGFloat(index) * view.bounds.width / CGFloat(sportCount - 1) let x = view.bounds.height / 2.0 layer.position = CGPoint(x: x, y: y) } } }
c8a8f1a49ff5a6ae21c46c488e0125f0
28.464286
93
0.581818
false
false
false
false
Keenan144/SpaceKase
refs/heads/master
SpaceKase/Booster.swift
mit
1
// // Booster.swift // SpaceKase // // Created by Keenan Sturtevant on 6/22/16. // Copyright © 2016 Keenan Sturtevant. All rights reserved. // import SpriteKit class Boost: SKSpriteNode { static var canSpawn:Bool! static var timer:NSTimer! class func spawnInvincibility() -> SKSpriteNode { if canSpawn == nil || canSpawn == true { let boostColor = UIColor.yellowColor() let boostSize = CGSize(width: 20, height: 20) let boost = SKSpriteNode(color: boostColor, size: boostSize) boost.texture = SKTexture(imageNamed: "Shield") boost.physicsBody = SKPhysicsBody(rectangleOfSize: boostSize) boost.physicsBody?.dynamic = true boost.physicsBody?.usesPreciseCollisionDetection = true boost.physicsBody?.affectedByGravity = false boost.physicsBody?.velocity.dy = -250 boost.name = "Invincibility" canSpawn = false print("BOOST: spawnInvincibility") return boost } print("BOOST: spawnScoreBump()") return Boost.spawnScoreBump() } class func spawnScoreBump() -> SKSpriteNode { let boostColor = UIColor.cyanColor() let boostSize = CGSize(width: 20, height: 20) let boost = SKSpriteNode(color: boostColor, size: boostSize) boost.texture = SKTexture(imageNamed: "Point") boost.physicsBody = SKPhysicsBody(rectangleOfSize: boostSize) boost.physicsBody?.dynamic = true boost.physicsBody?.usesPreciseCollisionDetection = true boost.physicsBody?.affectedByGravity = false boost.physicsBody?.velocity.dy = -250 boost.name = "ScoreBump" print("BOOST: spawnScoreBump") return boost } }
c27f67b1a5ae40c087c22e8d8b8c7082
31.754386
73
0.610932
false
false
false
false
leoneparise/iLog
refs/heads/master
iLogUI/TimelineTableViewHeader.swift
mit
1
// // TimleineTableViewHeader.swift // StumpExample // // Created by Leone Parise Vieira da Silva on 06/05/17. // Copyright © 2017 com.leoneparise. All rights reserved. // import UIKit public class TimelineTableViewHeader: UIVisualEffectView { @IBOutlet weak var bulletView:TimelineBulletView! @IBOutlet weak var titleLabel:UILabel! var dateFormatter:DateFormatter = { let df = DateFormatter() df.doesRelativeDateFormatting = true df.dateStyle = .medium df.timeStyle = .short return df }() static func fromNib() -> TimelineTableViewHeader { let bundle = Bundle(for: TimelineTableViewHeader.self) let nib = UINib(nibName: "TimelineTableViewHeader", bundle: bundle) return nib.instantiate(withOwner: nil, options: nil).first as! TimelineTableViewHeader } var date:Date? { didSet { titleLabel.text = date != nil ? dateFormatter.string(from: date!) : "" } } var title:String? { didSet { titleLabel.text = title } } var isFirst:Bool = false { didSet { bulletView.isFirst = isFirst bulletView.isLast = false } } }
52401d17df65f10aa55662e56ee2817f
27.069767
94
0.63546
false
false
false
false
cocoascientist/Passengr
refs/heads/master
Passengr/HTML.swift
mit
1
// // HTML.swift // Passengr // // Created by Andrew Shepard on 11/17/15. // Copyright © 2015 Andrew Shepard. All rights reserved. // import Foundation final class HTMLNode { internal let nodePtr: xmlNodePtr private let node: xmlNode init(node nodePtr: xmlNodePtr) { self.nodePtr = nodePtr self.node = nodePtr.pointee } lazy var nodeValue: String = { let document = self.nodePtr.pointee.doc let children = self.nodePtr.pointee.children guard let textValue = xmlNodeListGetString(document, children, 1) else { return "" } defer { free(textValue) } let value = textValue.withMemoryRebound(to: CChar.self, capacity: 1) { return String(validatingUTF8: $0) } guard value != nil else { return "" } return value! }() } extension HTMLNode { func evaluate(xpath: String) -> [HTMLNode] { let document = nodePtr.pointee.doc guard let context = xmlXPathNewContext(document) else { return [] } defer { xmlXPathFreeContext(context) } context.pointee.node = nodePtr guard let result = xmlXPathEvalExpression(xpath, context) else { return [] } defer { xmlXPathFreeObject(result) } guard let nodeSet = result.pointee.nodesetval else { return [] } if nodeSet.pointee.nodeNr == 0 || nodeSet.pointee.nodeTab == nil { return [] } let size = Int(nodeSet.pointee.nodeNr) let nodes: [HTMLNode] = [Int](0..<size).compactMap { guard let node = nodeSet.pointee.nodeTab[$0] else { return nil } return HTMLNode(node: node) } return nodes } } final class HTMLDoc { final let documentPtr: htmlDocPtr init?(data: Data) { let cfEncoding = CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue) let cfEncodingAsString = CFStringConvertEncodingToIANACharSetName(cfEncoding) let cEncoding = CFStringGetCStringPtr(cfEncodingAsString, 0) // HTML_PARSE_RECOVER | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING let htmlParseOptions: CInt = 1 << 0 | 1 << 5 | 1 << 6 var ptr: htmlDocPtr? = nil data.withUnsafeBytes { result -> Void in guard let bytes = result.baseAddress?.assumingMemoryBound(to: Int8.self) else { return } ptr = htmlReadMemory(bytes, CInt(data.count), nil, cEncoding, htmlParseOptions) } guard let _ = ptr else { return nil } self.documentPtr = ptr! } deinit { xmlFreeDoc(documentPtr) self._root = nil } private weak var _root: HTMLNode? var root: HTMLNode? { if let root = _root { return root } else { guard let root = xmlDocGetRootElement(documentPtr) else { return nil } let node = HTMLNode(node: root) self._root = node return node } } }
26106caeb3317a9bb975e9e65de01964
29.949495
100
0.591384
false
false
false
false
linbin00303/Dotadog
refs/heads/master
DotaDog/DotaDog/Classes/LeftView/Controller/DDogMatchTableViewController.swift
mit
1
// // DDogMatchTableViewController.swift // DotaDog // // Created by 林彬 on 16/5/25. // Copyright © 2016年 linbin. All rights reserved. // import UIKit import MJExtension import SVProgressHUD class DDogMatchTableViewController: UITableViewController { var j = 0 private lazy var playerNames : [String:String]? = { let playerNames = [String:String]() return playerNames }() var match : DDogMatchListModel? let MatchHero = "DDogMatchCell" // 懒加载本场比赛模型 private lazy var matchModel : DDogMatchModel = { let matchModel:DDogMatchModel = DDogMatchModel() return matchModel }() // // 懒加载本场比赛英雄模型 // private lazy var heros : [DDogMatchHeroModel] = { // let heros:[DDogMatchHeroModel] = [DDogMatchHeroModel]() // return heros // }() // 懒加载本场比赛英雄模型 private lazy var heros : NSMutableArray = { let heros:NSMutableArray = NSMutableArray() return heros }() override func viewDidLoad() { super.viewDidLoad() setUpTableView() getNetData() } private func setUpTableView() { view.backgroundColor = UIColor.blackColor() title = "比赛详情" // 去掉Cell的间隔线 self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None // 注册cell tableView.registerNib(UINib(nibName: "DDogMatchCell", bundle: nil), forCellReuseIdentifier: MatchHero) } } // MARK:- 获取网络数据 extension DDogMatchTableViewController{ private func getNetData() { SVProgressHUD.setMinimumDismissTimeInterval(2) SVProgressHUD.show() let matchID = String(format: "%@" , (match?.match_id)!) let parameters = ["key":"75571F3D1597EA1E8E287E127F7C563F" , "match_id" : matchID] DDogLeftViewHttp.getMatchDataByUrl(parameters) { [weak self](resultMs,heroModels,error) -> () in if resultMs == nil { // 服务器大姨妈 SVProgressHUD.showErrorWithStatus("Steam服务器无法连接") return }else if resultMs! == []{ SVProgressHUD.showErrorWithStatus("该用户未公开数据") return }else if error != nil { SVProgressHUD.showErrorWithStatus("网络错误") } self?.matchModel = resultMs! // 设置headerView let headerV = DDogMatchHeader.showMatchHeadFromNib() headerV.matchModle = self?.matchModel self?.tableView.tableHeaderView = headerV self?.heros = heroModels! // 获取10个玩家姓名的字典 let count = heroModels!.count var hero : DDogMatchHeroModel? for i in 0..<count { hero = heroModels![i] as? DDogMatchHeroModel self?.getPlayerName(hero!.account_id) } self?.tableView.reloadData() } } } extension DDogMatchTableViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let _ = heros.count if heros == [] { return 0 } return 5 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MatchHero, forIndexPath: indexPath) as! DDogMatchCell cell.selectionStyle = .None var accountID : NSNumber = 0 if indexPath.section == 0 { accountID = (self.heros[indexPath.row] as? DDogMatchHeroModel)!.account_id cell.name = playerNames![accountID.stringValue] cell.hero = self.heros[indexPath.row] as? DDogMatchHeroModel }else { accountID = (self.heros[indexPath.row + 5 ] as? DDogMatchHeroModel)!.account_id cell.name = playerNames![accountID.stringValue] cell.hero = self.heros[indexPath.row + 5 ] as? DDogMatchHeroModel } return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 194 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 25 } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 40 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let text : UILabel = UILabel() text.textAlignment = .Center text.backgroundColor = UIColor.whiteColor() text.textColor = mainColor if section == 0 { text.text = "天辉" return text }else { text.text = "夜魇" return text } } func getPlayerName(accountID:NSNumber) { let tempID = Int64(accountID.intValue) + 76561197960265728 let stringTemp = String(format: "\(tempID)") var namedic = [String:String]() // 直接用ID查 let parameters = ["key":"75571F3D1597EA1E8E287E127F7C563F" , "steamids" : stringTemp] DDogLeftViewHttp.getPlayerNameByID(parameters) { [weak self](playerNameDic,model,error) in if error != nil { SVProgressHUD.showErrorWithStatus("网络错误") return } if playerNameDic != nil { namedic = playerNameDic! }else { namedic = [accountID.stringValue : "匿名玩家"] } self?.playerNames?.updateValue(namedic[accountID.stringValue]!, forKey:accountID.stringValue ) self?.j = self!.j + 1 if self?.j == 10 { SVProgressHUD.dismiss() self?.tableView.reloadData() self?.j = 0 } } } }
bd6323589764feb5984e869684b175ce
29.683168
119
0.57696
false
false
false
false
intellum/neeman
refs/heads/master
Tests/WebViewNavigationDelegateTests.swift
mit
1
import XCTest import WebKit @testable import Neeman class WebViewNavigationDelegateTests: XCTestCase { func testInitialRequest() { let url = URL(string: "http://example.com/") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) let request = URLRequest(url: url!) let webView = WKWebView() let navigationAction = NavigationAction(request: request) XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "The initial request should not be pushed") } func testFaultyURLNavigation() { let url = URL(string: "http://example.com/") let urlFaulty = URL(string: "#hi") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) var request = URLRequest(url: urlFaulty!) request.url = nil let navigationAction = NavigationAction(request: request) let webView = WKWebView() XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "Faulty URLs should not be pushed") } func testHashNavigation() { let url = URL(string: "http://example.com/#hash") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) let request = URLRequest(url: url!) let navigationAction = NavigationAction(request: request) let webView = WKWebView() XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "Hash navigation should not be pushed") } func testNavigateForward() { let url1 = URL(string: "http://example.com/") let url2 = URL(string: "http://example.com/user/profile/me") let navigationDelegate = WebViewNavigationDelegate(rootURL: url1!, delegate: nil) let request = URLRequest(url: url2!) let navigationAction = NavigationAction(request: request) let webView = WKWebView() XCTAssertTrue(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "New URLs should not be pushed") } // MARK: Delegation func testPreventPush() { class NeemanWebViewController: TestNeemanNavigationDelegate { override func shouldPreventPushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return true } } let url = URL(string: "https://groupdock.com/a/Level") let request = URLRequest(url: url!) let navigationAction = NavigationAction(request: request) let delegate = NeemanWebViewController() let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: delegate) let webView = WKWebView() XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "The delegate should prevent the URL being pushed") } func testErrorPassedToDelegate() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func webView(_ webView: WKWebView, didFinishLoadingWithError error: NSError) { XCTAssertNotNil(error, "The delegate should be passed a non nil error") expectation?.fulfill() } } let url = URL(string: "https://groupdock.com/a/Level") let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: delegate) let error = NSError(domain: "", code: 1, userInfo: nil) navigationDelegate.webView(WKWebView(), didFailProvisionalNavigation: nil, withError: error) waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testDecidePolicyForNavigationAction() { let expectation = self.expectation(description: "Call Callback") let url = URL(string: "https://groupdock.com/a/Level") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) let request = URLRequest(url: url!) let navigationAction = NavigationAction(request: request) navigationDelegate.webView(WKWebView(), decidePolicyFor: navigationAction) { (policy: WKNavigationActionPolicy) -> Void in expectation.fulfill() } waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testShouldPreventPushOfNewWebView() { class MyWKNavigation: NSObject { } class MyNeemanWebViewController: TestNeemanNavigationDelegate { override func shouldPreventPushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return true } } let url = URL(string: "https://groupdock.com/a/Level") let delegate = MyNeemanWebViewController() let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: delegate) let webView = WKWebView() let navigationAction = NavigationAction(request: URLRequest(url:url!)) XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "The delegate should prevent the URL being pushed") } func testDelegateDefaultImplementations() { class MyNeemanWebViewController: TestNeemanNavigationDelegate { } let webView = WKWebView() let navigationAction = NavigationAction(request: URLRequest(url: URL(string: "#hi")!)) let delegate = MyNeemanWebViewController() delegate.webView(webView, didFinishNavigationWithURL:nil) delegate.webView(webView, didFinishLoadingWithError: NSError(domain: "", code: 1, userInfo: nil)) delegate.webView(webView, didReceiveServerRedirectToURL: nil) let _ = delegate.shouldForcePushOfNavigationAction(navigationAction) delegate.pushNewWebViewControllerWithURL(URL(string: "#ho")!) let _ = delegate.shouldPreventPushOfNavigationAction(navigationAction) } func testDelegateMethodsCalled() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func webView(_ webView: WKWebView, didFinishNavigationWithURL: URL?) { expectation?.fulfill() } } let url = URL(string: "https://intellum.com/cool/new/link")! let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url, delegate: delegate) navigationDelegate.webView(WKWebView(), didFinish: nil) waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testDelegateRedirectMethodsCalled() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func webView(_ webView: WKWebView, didReceiveServerRedirectToURL: URL?) { expectation?.fulfill() } } let url = URL(string: "https://intellum.com/cool/new/link")! let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url, delegate: delegate) navigationDelegate.webView(WKWebView(), didReceiveServerRedirectForProvisionalNavigation: nil) waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testPushIsCalled() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func shouldForcePushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return true } override func pushNewWebViewControllerWithURL(_ url: URL) { expectation?.fulfill() } } class MyWKNavigationAction: NavigationAction { override var navigationType: WKNavigationType { get { return .linkActivated } } } let url = URL(string: "https://intellum.com/cool/new/link")! let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url, delegate: delegate) let action = MyWKNavigationAction(request: URLRequest(url: url)) navigationDelegate.webView(WKWebView(), decidePolicyFor: action) { (WKNavigationActionPolicy) -> Void in } waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } }
fe8e62b5aefdbabd2f273a972b229019
43.059091
130
0.644176
false
true
false
false
carabina/DDMathParser
refs/heads/master
MathParser/Function.swift
mit
2
// // Function.swift // DDMathParser // // Created by Dave DeLong on 9/17/15. // // import Foundation public typealias FunctionEvaluator = (Array<Expression>, Substitutions, Evaluator) throws -> Double public struct Function { public let names: Set<String> public let evaluator: FunctionEvaluator public init(name: String, evaluator: FunctionEvaluator) { self.names = [name] self.evaluator = evaluator } public init(names: Set<String>, evaluator: FunctionEvaluator) { self.names = names self.evaluator = evaluator } }
169e5b9169bacc4b9ab01a3200212d79
21.037037
99
0.660504
false
false
false
false
akhilstanislavose/echo
refs/heads/master
Echo/EventMonitor.swift
mit
1
// // EventMonitor.swift // Echo // // Created by Akhil Stanislavose on 08/10/15. // Copyright (c) 2015 Akhil Stanislavose. All rights reserved. // import Cocoa public class EventMonitor { private var monitor: AnyObject? private let mask: NSEventMask private let handler: NSEvent? -> () public init(mask: NSEventMask, handler: NSEvent? -> ()) { self.mask = mask self.handler = handler } deinit { stop() } public func start() { monitor = NSEvent.addGlobalMonitorForEventsMatchingMask(mask, handler: handler) } public func stop() { if monitor != nil { NSEvent.removeMonitor(monitor!) monitor = nil } } }
ed0b3405cce1d2cca6a2c1f787cf2e4b
19.8
87
0.601648
false
false
false
false
wujianguo/GitHubKit
refs/heads/master
GitHubApp/Classes/Profile/OrganizationTableViewController.swift
mit
1
// // OrganizationTableViewController.swift // GitHubKit // // Created by wujianguo on 16/8/24. // // import UIKit import GitHubKit import ObjectMapper import Alamofire class OrganizationTableViewController: ProfileTableViewController { override var profile: Profile? { return org } var org: Organization! = nil init(org: Organization) { super.init(style: .Grouped) self.org = org } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = org.name refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refresh), forControlEvents: .ValueChanged) refreshControl?.beginRefreshing() tableView.dataSource = dataSource tableView.registerClass(RepositoryTableViewCell.self, forCellReuseIdentifier: RepositoryTableViewCell.cellIdentifier) // tableView.registerClass(PersonTableViewCell.self, forCellReuseIdentifier: PersonTableViewCell.cellIdentifier) dataSource.refresh(tableView) if let name = org.name { title = name } else { org.updateSelfRequest().responseObject { (response: Response<Organization, NSError>) in guard response.result.isSuccess else { return } self.org.eTag = response.result.value?.eTag self.org.lastModified = response.result.value?.lastModified if let json = response.result.value?.toJSON() { self.org.mapping(Map(mappingType: .FromJSON, JSONDictionary: json)) self.profileView.updateUI(self.org) self.title = self.org.name } } } profileView.updateUI(org) } lazy var dataSource: RepositoriesTableViewDataSource = { let ds = RepositoriesTableViewDataSource(cellIdentifier: RepositoryTableViewCell.cellIdentifier, refreshable: self.refreshControl!, firstRequest: GitHubKit.orgReposRequest(self.org.login!)) return ds }() func refresh() { dataSource.refresh(tableView) } }
4d55f709f58dae8fff7a9e0c8fcc9f0c
32.074627
197
0.65704
false
false
false
false
JaSpa/swift
refs/heads/master
test/SILGen/complete_object_init.swift
apache-2.0
2
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-silgen | %FileCheck %s struct X { } class A { // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $A): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A } // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*A // CHECK: store [[SELF_PARAM]] to [init] [[SELF]] : $*A // CHECK: [[SELFP:%[0-9]+]] = load_borrow [[SELF]] : $*A // CHECK: [[INIT:%[0-9]+]] = class_method [[SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A , $@convention(method) (X, @owned A) -> @owned A // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A // CHECK: store [[INIT_RESULT]] to [init] [[SELF]] : $*A // CHECK: [[RESULT:%[0-9]+]] = load [copy] [[SELF]] : $*A // CHECK: destroy_value [[SELF_BOX]] : ${ var A } // CHECK: return [[RESULT]] : $A // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A convenience init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick A.Type): // CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A // CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A // CHECK: return [[RESULT]] : $A self.init(x: X()) } init(x: X) { } }
151903e6e82c7ed721a83df7c147470f
56.514286
153
0.54148
false
false
false
false
grandiere/box
refs/heads/master
box/Model/Store/Base/MStoreItem.swift
mit
1
import Foundation import StoreKit class MStoreItem { let purchaseId:String let title:String let descr:String var skProduct:SKProduct? private(set) var price:String? private(set) var status:MStoreStatusProtocol? init( purchaseId:String, title:String, descr:String) { self.purchaseId = purchaseId self.title = title self.descr = descr status = MStoreStatusNotAvailable() } //MARK: public func purchaseAction() { } func buyingError() -> String? { return nil } func validatePurchase() -> Bool { return false } //MARK: final final func foundPurchase(price:String) { self.price = price let isPurchased:Bool = validatePurchase() if isPurchased { statusPurchased(callAction:false) } else { statusNew() } } final func statusNew() { status = MStoreStatusNew() } final func statusDeferred() { status = MStoreStatusDeferred() } final func statusPurchasing() { status = MStoreStatusPurchasing() } final func statusPurchased(callAction:Bool) { status = MStoreStatusPurchased() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in if callAction { self?.purchaseAction() } } } }
9b2f1c0fdd3cf786825dfe06e5c5ebe0
17.546512
71
0.527273
false
false
false
false
ben-ng/swift
refs/heads/master
test/SILGen/auto_generated_super_init_call.swift
apache-2.0
4
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s // Test that we emit a call to super.init at the end of the initializer, when none has been previously added. class Parent { init() {} } class SomeDerivedClass : Parent { var y: Int func foo() {} override init() { y = 42 // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (@owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: integer_literal $Builtin.Int2048, 42 // CHECK: [[SELFLOAD:%[0-9]+]] = load_borrow [[SELF:%[0-9]+]] : $*SomeDerivedClass // CHECK-NEXT: [[PARENT:%[0-9]+]] = upcast [[SELFLOAD]] : $SomeDerivedClass to $Parent // CHECK: [[INITCALL1:%[0-9]+]] = function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent // CHECK-NEXT: [[RES1:%[0-9]+]] = apply [[INITCALL1]]([[PARENT]]) // CHECK-NEXT: [[DOWNCAST:%[0-9]+]] = unchecked_ref_cast [[RES1]] : $Parent to $SomeDerivedClass // CHECK-NEXT: store [[DOWNCAST]] to [init] [[SELF]] : $*SomeDerivedClass } init(x: Int) { y = x // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent } init(b: Bool) { if b { y = 0 return } else { y = 10 } return // Check that we are emitting the super.init expr into the epilog block. // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (Bool, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: bb4: // SEMANTIC ARC TODO: Another case of needing a mutable load_borrow. // CHECK: [[SELFLOAD:%[0-9]+]] = load_borrow [[SELF:%[0-9]+]] : $*SomeDerivedClass // CHECK: [[SELFLOAD_PARENT_CAST:%.*]] = upcast [[SELFLOAD]] // CHECK: [[PARENT_INIT:%.*]] = function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent, // CHECK: [[PARENT:%.*]] = apply [[PARENT_INIT]]([[SELFLOAD_PARENT_CAST]]) // CHECK: [[SELFAGAIN:%.*]] = unchecked_ref_cast [[PARENT]] // CHECK: store [[SELFAGAIN]] to [init] [[SELF]] // CHECK: [[SELFLOAD:%.*]] = load [copy] [[SELF]] // CHECK: destroy_value // CHECK: return [[SELFLOAD]] } // CHECK: } // end sil function '_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}}' // One init has a call to super init. Make sure we don't insert more than one. init(b: Bool, i: Int) { if (b) { y = i } else { y = 0 } super.init() // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (Bool, Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent // CHECK: return } } // Check that we do call super.init. class HasNoIVars : Parent { override init() { // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call10HasNoIVarsc{{.*}} : $@convention(method) (@owned HasNoIVars) -> @owned HasNoIVars // CHECK: function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent } } // Check that we don't call super.init. class ParentLess { var y: Int init() { y = 0 } } class Grandparent { init() {} } // This should have auto-generated default initializer. class ParentWithNoExplicitInit : Grandparent { } // Check that we add a call to super.init. class ChildOfParentWithNoExplicitInit : ParentWithNoExplicitInit { var y: Int override init() { y = 10 // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call31ChildOfParentWithNoExplicitInitc // CHECK: function_ref @_TFC30auto_generated_super_init_call24ParentWithNoExplicitInitcfT_S0_ : $@convention(method) (@owned ParentWithNoExplicitInit) -> @owned ParentWithNoExplicitInit } } // This should have auto-generated default initializer. class ParentWithNoExplicitInit2 : Grandparent { var i: Int = 0 } // Check that we add a call to super.init. class ChildOfParentWithNoExplicitInit2 : ParentWithNoExplicitInit2 { var y: Int override init() { y = 10 // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call32ChildOfParentWithNoExplicitInit2c // CHECK: function_ref @_TFC30auto_generated_super_init_call25ParentWithNoExplicitInit2cfT_S0_ : $@convention(method) (@owned ParentWithNoExplicitInit2) -> @owned ParentWithNoExplicitInit2 } } // Do not insert the call nor warn - the user should call init(5). class ParentWithNoDefaultInit { var i: Int init(x: Int) { i = x } } class ChildOfParentWithNoDefaultInit : ParentWithNoDefaultInit { var y: Int init() { // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call30ChildOfParentWithNoDefaultInitc{{.*}} : $@convention(method) (@owned ChildOfParentWithNoDefaultInit) -> @owned ChildOfParentWithNoDefaultInit // CHECK: bb0 // CHECK-NOT: apply // CHECK: return } }
60129c9a623eb1628a164702fa4e8448
38.340909
207
0.68939
false
false
false
false
Crowdmix/Buildasaur
refs/heads/master
Buildasaur/UIUtils.swift
mit
4
// // UIUtils.swift // Buildasaur // // Created by Honza Dvorsky on 07/03/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import AppKit import BuildaUtils public class UIUtils { public class func showAlertWithError(error: NSError) { let alert = self.createErrorAlert(error) self.presentAlert(alert, completion: { (resp) -> () in // }) } public class func showAlertAskingForRemoval(text: String, completion: (remove: Bool) -> ()) { let removeText = "Remove" let buttons = ["Cancel", removeText] self.showAlertWithButtons(text, buttons: buttons) { (tappedButton) -> () in completion(remove: removeText == tappedButton) } } public class func showAlertWithButtons(text: String, buttons: [String], completion: (tappedButton: String) -> ()) { let alert = self.createAlert(text, style: nil) buttons.forEach { alert.addButtonWithTitle($0) } self.presentAlert(alert, completion: { (resp) -> () in //some magic where indices are starting at 1000... so subtract 1000 to get the array index of tapped button let idx = resp - NSAlertFirstButtonReturn let buttonText = buttons[idx] completion(tappedButton: buttonText) }) } public class func showAlertWithText(text: String, style: NSAlertStyle? = nil, completion: ((NSModalResponse) -> ())? = nil) { let alert = self.createAlert(text, style: style) self.presentAlert(alert, completion: completion) } private class func createErrorAlert(error: NSError) -> NSAlert { return NSAlert(error: error) } private class func createAlert(text: String, style: NSAlertStyle?) -> NSAlert { let alert = NSAlert() alert.alertStyle = style ?? .InformationalAlertStyle alert.messageText = text return alert } private class func presentAlert(alert: NSAlert, completion: ((NSModalResponse) -> ())?) { if let _ = NSApp.windows.first { let resp = alert.runModal() completion?(resp) // alert.beginSheetModalForWindow(window, completionHandler: completion) } else { //no window to present in, at least print Log.info("Alert: \(alert.messageText)") } } }
3301f335e595decdad819dda6d86051e
30.974359
129
0.597434
false
false
false
false
thisfin/HostsManager
refs/heads/develop
HostsManager/AlertPanel.swift
mit
1
// // AlertPanel.swift // HostsManager // // Created by wenyou on 2017/7/1. // Copyright © 2017年 wenyou. All rights reserved. // import AppKit import SnapKit class AlertPanel { static func show(_ content: String, fontSize: CGFloat = 32) { let font = NSFont.systemFont(ofSize: fontSize) let size = (content as NSString).size(withAttributes: [NSFontAttributeName: font]) let panel = NSPanel(contentRect: NSMakeRect(0, 0, size.width + 100, size.height + 40), styleMask: [.borderless, .hudWindow], backing: .buffered, defer: true) let textField = NSTextField.init(frame: panel.contentLayoutRect) textField.cell = WYVerticalCenterTextFieldCell() textField.isEditable = false textField.isSelectable = false textField.isBordered = false textField.alignment = .center textField.textColor = .white textField.font = font textField.stringValue = content if let contentView = panel.contentView { // 此处做颜色和圆角的处理 contentView.addSubview(textField) contentView.wantsLayer = true contentView.layer?.cornerRadius = 5 contentView.layer?.backgroundColor = panel.backgroundColor.cgColor // 使用默认 hudWindow 的颜色 panel.backgroundColor = .clear } panel.center() panel.orderFront(self) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8, execute: { // 自动关闭 panel.orderOut(self) panel.close() }) } }
63858cac35246bf919d86411f11a72d4
37.225
165
0.650098
false
false
false
false
jaouahbi/OMCircularProgress
refs/heads/master
Example/Example/OMShadingGradientLayer/Classes/OMGradientLayer.swift
apache-2.0
2
// // OMGradientLayer.swift // // Created by Jorge Ouahbi on 19/8/16. // Copyright © 2016 Jorge Ouahbi. All rights reserved. // // // Copyright 2015 - Jorge Ouahbi // // 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 public typealias GradientColors = (UIColor,UIColor) typealias TransformContextClosure = (_ ctx:CGContext, _ startPoint:CGPoint, _ endPoint:CGPoint, _ startRadius:CGFloat, _ endRadius:CGFloat) -> (Void) open class OMGradientLayer : CALayer, OMGradientLayerProtocol { // MARK: - OMColorsAndLocationsProtocol @objc open var colors: [UIColor] = [] { didSet { // if only exist one color, duplicate it. if (colors.count == 1) { let color = colors.first! colors = [color, color]; } // map monochrome colors to rgba colors colors = colors.map({ return ($0.colorSpace?.model == .monochrome) ? UIColor(red: $0.components[0], green : $0.components[0], blue : $0.components[0], alpha : $0.components[1]) : $0 }) self.setNeedsDisplay() } } @objc open var locations : [CGFloat]? = nil { didSet { if locations != nil{ locations!.sort { $0 < $1 } } self.setNeedsDisplay() } } open var isAxial : Bool { return (gradientType == .axial) } open var isRadial : Bool { return (gradientType == .radial) } // MARK: - OMAxialGradientLayerProtocol open var gradientType :OMGradientType = .axial { didSet { self.setNeedsDisplay(); } } @objc open var startPoint: CGPoint = CGPoint(x: 0.0, y: 0.5) { didSet { self.setNeedsDisplay(); } } @objc open var endPoint: CGPoint = CGPoint(x: 1.0, y: 0.5) { didSet{ self.setNeedsDisplay(); } } open var extendsBeforeStart : Bool = false { didSet { self.setNeedsDisplay() } } open var extendsPastEnd : Bool = false { didSet { self.setNeedsDisplay() } } // MARK: - OMRadialGradientLayerProtocol @objc open var startRadius: CGFloat = 0 { didSet { startRadius = clamp(startRadius, lower: 0, upper: 1.0) self.setNeedsDisplay(); } } @objc open var endRadius: CGFloat = 0 { didSet { endRadius = clamp(endRadius, lower: 0, upper: 1.0) self.setNeedsDisplay(); } } // MARK: OMMaskeableLayerProtocol open var lineWidth : CGFloat = 1.0 { didSet { self.setNeedsDisplay() } } open var stroke : Bool = false { didSet { self.setNeedsDisplay() } } open var path: CGPath? { didSet { self.setNeedsDisplay() } } /// Transform the radial gradient /// example: oval gradient = CGAffineTransform(scaleX: 2, y: 1.0); open var radialTransform: CGAffineTransform = CGAffineTransform.identity { didSet { self.setNeedsDisplay() } } // Some predefined Gradients (from WebKit) public lazy var insetGradient:GradientColors = { return (UIColor(red:0 / 255.0, green:0 / 255.0,blue: 0 / 255.0,alpha: 0 ), UIColor(red: 0 / 255.0, green:0 / 255.0,blue: 0 / 255.0,alpha: 0.2 )) }() public lazy var shineGradient:GradientColors = { return (UIColor(red:1, green:1,blue: 1,alpha: 0 ), UIColor(red: 1, green:1,blue:1,alpha: 0.8 )) }() public lazy var shadeGradient:GradientColors = { return (UIColor(red: 252 / 255.0, green: 252 / 255.0,blue: 252 / 255.0,alpha: 0.65 ), UIColor(red: 178 / 255.0, green:178 / 255.0,blue: 178 / 255.0,alpha: 0.65 )) }() public lazy var convexGradient:GradientColors = { return (UIColor(red:1,green:1,blue:1,alpha: 0.43 ), UIColor(red:1,green:1,blue:1,alpha: 0.5 )) }() public lazy var concaveGradient:GradientColors = { return (UIColor(red:1,green:1,blue:1,alpha: 0.0 ), UIColor(red:1,green:1,blue:1,alpha: 0.46 )) }() // Here's a method that creates a view that allows 360 degree rotation of its two-colour // gradient based upon input from a slider (or anything). The incoming slider value // ("x" variable below) is between 0.0 and 1.0. // // At 0.0 the gradient is horizontal (with colour A on top, and colour B below), rotating // through 360 degrees to value 1.0 (identical to value 0.0 - or a full rotation). // // E.g. when x = 0.25, colour A is left and colour B is right. At 0.5, colour A is below // and colour B is above, 0.75 colour A is right and colour B is left. It rotates anti-clockwise // from right to left. // // It takes four arguments: frame, colourA, colourB and the input value (0-1). // // from: http://stackoverflow.com/a/29168654/6387073 public class func pointsFromNormalizedAngle(_ normalizedAngle:Double) -> (CGPoint,CGPoint) { //x is between 0 and 1, eg. from a slider, representing 0 - 360 degrees //colour A starts on top, with colour B below //rotations move anti-clockwise //create coordinates let r = 2.0 * .pi; let a = pow(sin((r*((normalizedAngle+0.75)/2))),2); let b = pow(sin((r*((normalizedAngle+0.0)/2))),2); let c = pow(sin((r*((normalizedAngle+0.25)/2))),2); let d = pow(sin((r*((normalizedAngle+0.5)/2))),2); //set the gradient direction return (CGPoint(x: a, y: b),CGPoint(x: c, y: d)) } // MARK: - Object constructors required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } convenience public init(type:OMGradientType) { self.init() self.gradientType = type } // MARK: - Object Overrides override public init() { super.init() self.allowsEdgeAntialiasing = true self.contentsScale = UIScreen.main.scale self.needsDisplayOnBoundsChange = true; self.drawsAsynchronously = true; } override public init(layer: Any) { super.init(layer: layer) if let other = layer as? OMGradientLayer { // common self.colors = other.colors self.locations = other.locations self.gradientType = other.gradientType // axial gradient properties self.startPoint = other.startPoint self.endPoint = other.endPoint self.extendsBeforeStart = other.extendsBeforeStart self.extendsPastEnd = other.extendsPastEnd // radial gradient properties self.startRadius = other.startRadius self.endRadius = other.endRadius // OMMaskeableLayerProtocol self.path = other.path self.stroke = other.stroke self.lineWidth = other.lineWidth self.radialTransform = other.radialTransform } } // MARK: - Functions override open class func needsDisplay(forKey event: String) -> Bool { if (event == OMGradientLayerProperties.startPoint || event == OMGradientLayerProperties.locations || event == OMGradientLayerProperties.colors || event == OMGradientLayerProperties.endPoint || event == OMGradientLayerProperties.startRadius || event == OMGradientLayerProperties.endRadius) { return true } return super.needsDisplay(forKey: event) } override open func action(forKey event: String) -> CAAction? { if (event == OMGradientLayerProperties.startPoint || event == OMGradientLayerProperties.locations || event == OMGradientLayerProperties.colors || event == OMGradientLayerProperties.endPoint || event == OMGradientLayerProperties.startRadius || event == OMGradientLayerProperties.endRadius) { return animationActionForKey(event); } return super.action(forKey: event) } override open func draw(in ctx: CGContext) { // super.drawInContext(ctx) do nothing let clipBoundingBox = ctx.boundingBoxOfClipPath ctx.clear(clipBoundingBox); ctx.clip(to: clipBoundingBox) } func prepareContextIfNeeds(_ ctx:CGContext, scale:CGAffineTransform, closure:TransformContextClosure) { let sp = self.startPoint * self.bounds.size let ep = self.endPoint * self.bounds.size let mr = minRadius(self.bounds.size) // Scaling transformation and keeping track of the inverse let invScaleT = scale.inverted(); // Extract the Sx and Sy elements from the inverse matrix (See the Quartz documentation for the math behind the matrices) let invS = CGPoint(x:invScaleT.a, y:invScaleT.d); // Transform center and radius of gradient with the inverse let startPointAffined = CGPoint(x:sp.x * invS.x, y:sp.y * invS.y); let endPointAffined = CGPoint(x:ep.x * invS.x, y:ep.y * invS.y); let startRadiusAffined = mr * startRadius * invS.x; let endRadiusAffined = mr * endRadius * invS.x; // Draw the gradient with the scale transform on the context ctx.scaleBy(x: scale.a, y: scale.d); closure(ctx, startPointAffined, endPointAffined, startRadiusAffined, endRadiusAffined) // Reset the context ctx.scaleBy(x: invS.x, y: invS.y); } func addPathAndClipIfNeeded(_ ctx:CGContext) { if (self.path != nil) { ctx.addPath(self.path!); if (self.stroke) { ctx.setLineWidth(self.lineWidth); ctx.replacePathWithStrokedPath(); } ctx.clip(); } } func isDrawable() -> Bool { if (colors.count == 0) { // nothing to do Log.v("\(self.name ?? "") Unable to do the shading without colors.") return false } if (startPoint.isZero && endPoint.isZero) { // nothing to do Log.v("\(self.name ?? "") Start point and end point are {x:0, y:0}.") return false } if (startRadius == endRadius && self.isRadial) { // nothing to do Log.v("\(self.name ?? "") Start radius and end radius are equal. \(startRadius) \(endRadius)") return false } return true; } override open var description:String { get { var currentDescription:String = "type: \((self.isAxial ? "Axial" : "Radial")) " if let locations = locations { if(locations.count == colors.count) { _ = zip(colors,locations).compactMap { currentDescription += "color: \($0.0.shortDescription) location: \($0.1) " } } else { if (locations.count > 0) { _ = locations.map({currentDescription += "\($0) "}) } if (colors.count > 0) { _ = colors.map({currentDescription += "\($0.shortDescription) "}) } } } if (self.isRadial) { currentDescription += "center from : \(startPoint) to \(endPoint), radius from : \(startRadius) to \(endRadius)" } else if (self.isAxial) { currentDescription += "from : \(startPoint) to \(endPoint)" } if (self.extendsPastEnd) { currentDescription += " draws after end location " } if (self.extendsBeforeStart) { currentDescription += " draws before start location " } return currentDescription } } }
881085b8673b011e54ae4b55b6cf75c8
34.091153
150
0.551455
false
false
false
false
hsavit1/LeetCode-Solutions-in-Swift
refs/heads/master
Solutions/Solutions/Medium/Medium_059_Spiral_Matrix_II.swift
mit
4
/* https://leetcode.com/problems/spiral-matrix-ii/ #59 Spiral Matrix II Level: medium Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] Inspired by @yike at https://leetcode.com/discuss/21677/simple-c-solution-with-explaination */ import Foundation struct Medium_059_Spiral_Matrix_II { static func generateMatrix(n: Int) -> [[Int]] { var res = Array<[Int]>(count: n, repeatedValue: Array<Int>(count: n, repeatedValue: 0)) var k = 1 var i = 0 while k <= n * n { var j = i while j < n - i { res[i][j++] = k++ } j = i + 1 while j < n - i { res[j++][n-i-1] = k++ } j = n - i - 2 while j > i { res[n-i-1][j--] = k++ } j = n - i - 1 while j > i { res[j--][i] = k++ } i++ } return res } }
b62d35dc5f63a4fd90fabdb09e2af304
20.169811
95
0.458519
false
false
false
false
ianyh/Amethyst
refs/heads/development
Amethyst/Managers/WindowTransitionCoordinator.swift
mit
1
// // WindowTransitionCoordinator.swift // Amethyst // // Created by Ian Ynda-Hummel on 3/24/19. // Copyright © 2019 Ian Ynda-Hummel. All rights reserved. // import Cocoa import Foundation import Silica enum WindowTransition<Window: WindowType> { typealias Screen = Window.Screen case switchWindows(_ window1: Window, _ window2: Window) case moveWindowToScreen(_ window: Window, screen: Screen) case moveWindowToSpaceAtIndex(_ window: Window, spaceIndex: Int) case resetFocus } protocol WindowTransitionTarget: class { associatedtype Application: ApplicationType typealias Window = Application.Window typealias Screen = Window.Screen func executeTransition(_ transition: WindowTransition<Window>) func isWindowFloating(_ window: Window) -> Bool func currentLayout() -> Layout<Application.Window>? func screen(at index: Int) -> Screen? func activeWindows(on screen: Screen) -> [Window] func nextScreenIndexClockwise(from screen: Screen) -> Int func nextScreenIndexCounterClockwise(from screen: Screen) -> Int } class WindowTransitionCoordinator<Target: WindowTransitionTarget> { typealias Window = Target.Window typealias Screen = Window.Screen weak var target: Target? init() {} func swapFocusedWindowToMain() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false, let screen = focusedWindow.screen() else { return } guard let windows = target?.activeWindows(on: screen), let focusedIndex = windows.index(of: focusedWindow) else { return } if windows.count <= 1 { return } if focusedIndex == 0 && target?.currentLayout()?.layoutKey == TwoPaneLayout<Window>.layoutKey { // If main window is focused and layout is two-pane - swap the two top-most windows, keep focus on the main window target?.executeTransition(.switchWindows(focusedWindow, windows[1])) windows[1].focus() return } if focusedIndex != 0 { // Swap focused window with main window if other window is focused target?.executeTransition(.switchWindows(focusedWindow, windows[0])) } } func swapFocusedWindowCounterClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let windows = target?.activeWindows(on: screen), let focusedWindowIndex = windows.index(of: focusedWindow) else { return } let windowToSwapWith = windows[(focusedWindowIndex == 0 ? windows.count - 1 : focusedWindowIndex - 1)] target?.executeTransition(.switchWindows(focusedWindow, windowToSwapWith)) } func swapFocusedWindowClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let windows = target?.activeWindows(on: screen), let focusedWindowIndex = windows.index(of: focusedWindow) else { return } let windowToSwapWith = windows[(focusedWindowIndex + 1) % windows.count] target?.executeTransition(.switchWindows(focusedWindow, windowToSwapWith)) } func throwToScreenAtIndex(_ screenIndex: Int) { guard let screen = target?.screen(at: screenIndex), let focusedWindow = Window.currentlyFocused() else { return } // If the window is already on the screen do nothing. guard let focusedScreen = focusedWindow.screen(), focusedScreen.screenID() != screen.screenID() else { return } target?.executeTransition(.moveWindowToScreen(focusedWindow, screen: screen)) } func swapFocusedWindowScreenClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let nextScreenIndex = target?.nextScreenIndexClockwise(from: screen), let nextScreen = target?.screen(at: nextScreenIndex) else { return } target?.executeTransition(.moveWindowToScreen(focusedWindow, screen: nextScreen)) } func swapFocusedWindowScreenCounterClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let nextScreenIndex = target?.nextScreenIndexCounterClockwise(from: screen), let nextScreen = target?.screen(at: nextScreenIndex) else { return } target?.executeTransition(.moveWindowToScreen(focusedWindow, screen: nextScreen)) } func pushFocusedWindowToSpace(_ space: Int) { guard let focusedWindow = Window.currentlyFocused(), focusedWindow.screen() != nil else { return } target?.executeTransition(.moveWindowToSpaceAtIndex(focusedWindow, spaceIndex: space)) } func pushFocusedWindowToSpaceLeft() { guard let currentFocusedSpace = CGSpacesInfo<Window>.currentFocusedSpace(), let spaces = CGSpacesInfo<Window>.spacesForFocusedScreen() else { return } guard let index = spaces.index(of: currentFocusedSpace), index > 0 else { return } pushFocusedWindowToSpace(index - 1) } func pushFocusedWindowToSpaceRight() { guard let currentFocusedSpace = CGSpacesInfo<Window>.currentFocusedSpace(), let spaces = CGSpacesInfo<Window>.spacesForFocusedScreen() else { return } guard let index = spaces.index(of: currentFocusedSpace), index + 1 < spaces.count else { return } pushFocusedWindowToSpace(index + 1) } }
888559eeccc89b52929e7f8ee57e486f
33.446237
153
0.659435
false
false
false
false
CallMeMrAlex/DYTV
refs/heads/master
DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Home(首页)/View/AmuseMenuView.swift
mit
1
// // AmuseMenuView.swift // DYTV-AlexanderZ-Swift // // Created by Alexander Zou on 2016/10/17. // Copyright © 2016年 Alexander Zou. All rights reserved. // import UIKit private let kMenuCellID = "kMenuCellID" class AmuseMenuView: UIView { var groups : [AnchorGroupModel]? { didSet { collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } extension AmuseMenuView { class func amuseMenuView() -> AmuseMenuView { return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView } } extension AmuseMenuView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if groups == nil { return 0 } let pageNum = (groups!.count - 1) / 8 + 1 pageControl.numberOfPages = pageNum return pageNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell setupCellDataWithCell(cell, indexPath: indexPath) return cell } fileprivate func setupCellDataWithCell(_ cell : AmuseMenuViewCell, indexPath : IndexPath) { // 0页: 0 ~ 7 // 1页: 8 ~ 15 // 2页: 16 ~ 23 // 取出起始位置&终点位置 let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 // 判断越界问题 if endIndex > groups!.count - 1 { endIndex = groups!.count - 1 } cell.groups = Array(groups![startIndex...endIndex]) } } extension AmuseMenuView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width) } }
9352400e26d63b53569e3c552d5020d0
25.670213
125
0.644994
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/ShadowboxViewController.swift
apache-2.0
1
// // ShadowboxViewController.swift // Slide for Reddit // // Created by Carlos Crane on 8/5/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import Anchorage import AVKit import reddift import UIKit class ShadowboxViewController: SwipeDownModalVC, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var submissionDataSource: SubmissionsDataSource var index: Int func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { color2 = (pendingViewControllers[0] as! ShadowboxLinkViewController).backgroundColor color1 = (currentVc as! ShadowboxLinkViewController).backgroundColor } func getURLToLoad(_ submission: RSubmission) -> URL? { let url = submission.url if url != nil && ContentType.isGif(uri: url!) { if !submission.videoPreview.isEmpty() && !ContentType.isGfycat(uri: url!) { return URL.init(string: submission.videoPreview)! } else { return url! } } else { return url } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) DispatchQueue.global(qos: .background).async { do { try AVAudioSession.sharedInstance().setCategory(.ambient, options: [.mixWithOthers]) try AVAudioSession.sharedInstance().setActive(false, options: AVAudioSession.SetActiveOptions.notifyOthersOnDeactivation) } catch { NSLog(error.localizedDescription) } } } public init(index: Int, submissionDataSource: SubmissionsDataSource) { self.submissionDataSource = submissionDataSource self.index = index super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge.all self.extendedLayoutIncludesOpaqueBars = true submissionDataSource.delegate = self } var navItem: UINavigationItem? @objc func exit() { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.dataSource = self self.delegate = self view.backgroundColor = UIColor.black.withAlphaComponent(0.7) self.navigationController?.view.backgroundColor = UIColor.clear viewToMux = self.background let s = submissionDataSource.content[index] let firstViewController = ShadowboxLinkViewController(url: self.getURLToLoad(s), content: s, parent: self) currentVc = firstViewController (currentVc as! ShadowboxLinkViewController).populateContent() self.setViewControllers([firstViewController], direction: .forward, animated: true, completion: { [weak self](_) in guard let self = self else { return } if (self.currentVc as! ShadowboxLinkViewController).embeddedVC == nil { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).thumbImageContainer.superview } else { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).embeddedVC.view } }) } @objc func color() { SettingValues.blackShadowbox = !SettingValues.blackShadowbox UserDefaults.standard.set(SettingValues.blackShadowbox, forKey: SettingValues.pref_blackShadowbox) UserDefaults.standard.synchronize() if SettingValues.blackShadowbox { UIView.animate(withDuration: 0.25) { self.background?.backgroundColor = .black } } else { (currentVc as! ShadowboxLinkViewController).doBackground() } } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool) { guard didFinishAnimating else { return } currentVc = self.viewControllers!.first! if (self.currentVc as! ShadowboxLinkViewController).embeddedVC == nil { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).topBody } else { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).embeddedVC.view } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let id = (viewController as! ShadowboxLinkViewController).submission.getId() var viewControllerIndex = -1 for item in submissionDataSource.content { viewControllerIndex += 1 if item.getId() == id { break } } if viewControllerIndex < 0 || viewControllerIndex > submissionDataSource.content.count { return nil } var previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return nil } guard submissionDataSource.content.count > previousIndex else { return nil } if submissionDataSource.content[previousIndex].author == "PAGE_SEPARATOR" { previousIndex -= 1 } let s = submissionDataSource.content[previousIndex] let shadowbox = ShadowboxLinkViewController(url: self.getURLToLoad(s), content: s, parent: self) if !shadowbox.populated { shadowbox.populated = true shadowbox.populateContent() } return shadowbox } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let id = (viewController as! ShadowboxLinkViewController).submission.getId() var viewControllerIndex = -1 for item in submissionDataSource.content { viewControllerIndex += 1 if item.getId() == id { break } } if viewControllerIndex < 0 || viewControllerIndex > submissionDataSource.content.count { return nil } var nextIndex = viewControllerIndex + 1 let orderedViewControllersCount = submissionDataSource.content.count guard orderedViewControllersCount != nextIndex else { return nil } guard orderedViewControllersCount > nextIndex else { return nil } if submissionDataSource.content[nextIndex].author == "PAGE_SEPARATOR" { nextIndex += 1 } if nextIndex == submissionDataSource.content.count - 2 && !submissionDataSource.loading { DispatchQueue.main.async { self.submissionDataSource.getData(reload: false) } } let s = submissionDataSource.content[nextIndex] let shadowbox = ShadowboxLinkViewController(url: self.getURLToLoad(s), content: s, parent: self) if !shadowbox.populated { shadowbox.populated = true shadowbox.populateContent() } return shadowbox } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } var selected = false var currentVc = UIViewController() override var prefersHomeIndicatorAutoHidden: Bool { return true } } extension ShadowboxViewController: SubmissionDataSouceDelegate { func showIndicator() { } func generalError(title: String, message: String) { } func loadSuccess(before: Int, count: Int) { DispatchQueue.main.async { self.setViewControllers([self.currentVc], direction: .forward, animated: false, completion: nil) } } func preLoadItems() { } func doPreloadImages(values: [RSubmission]) { } func loadOffline() { } func emptyState(_ listing: Listing) { } func vcIsGallery() -> Bool { return false } } private var hasSwizzled = false extension UIPanGestureRecognizer { final public class func swizzle() { guard !hasSwizzled else { return } hasSwizzled = true guard self === UIPanGestureRecognizer.self else { return } func replace(_ method: Selector, with anotherMethod: Selector, for clаss: AnyClass) { let original = class_getInstanceMethod(clаss, method) let swizzled = class_getInstanceMethod(clаss, anotherMethod) switch class_addMethod(clаss, method, method_getImplementation(swizzled!), method_getTypeEncoding(swizzled!)) { case true: class_replaceMethod(clаss, anotherMethod, method_getImplementation(original!), method_getTypeEncoding(original!)) case false: method_exchangeImplementations(original!, swizzled!) } } let selector1 = #selector(UIPanGestureRecognizer.touchesBegan(_:with:)) let selector2 = #selector(UIPanGestureRecognizer.swizzling_touchesBegan(_:with:)) replace(selector1, with: selector2, for: self) let selector3 = #selector(UIPanGestureRecognizer.touchesMoved(_:with:)) let selector4 = #selector(UIPanGestureRecognizer.swizzling_touchesMoved(_:with:)) replace(selector3, with: selector4, for: self) } @objc private func swizzling_touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { self.swizzling_touchesBegan(touches, with: event) guard direction != nil else { return } touchesBegan = true } @objc private func swizzling_touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { self.swizzling_touchesMoved(touches, with: event) guard let direction = direction, touchesBegan == true else { return } defer { touchesBegan = false } let forbiddenDirectionsCount = touches .compactMap({ ($0.location(in: $0.view) - $0.previousLocation(in: $0.view)).direction }) .filter({ $0 != direction }) .count if forbiddenDirectionsCount > 0 { state = .failed } } } public extension UIPanGestureRecognizer { enum Direction: Int { case horizontal = 0 case vertical } private struct UIPanGestureRecognizerRuntimeKeys { static var directions = "\(#file)+\(#line)" static var touchesBegan = "\(#file)+\(#line)" } var direction: UIPanGestureRecognizer.Direction? { get { let object = objc_getAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.directions) return object as? UIPanGestureRecognizer.Direction } set { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.directions, newValue, policy) } } private var touchesBegan: Bool { get { let object = objc_getAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.touchesBegan) return (object as? Bool) ?? false } set { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.touchesBegan, newValue, policy) } } } private extension CGPoint { var direction: UIPanGestureRecognizer.Direction? { guard self != .zero else { return nil } switch abs(x) > abs(y) { case true: return .horizontal case false: return .vertical } } static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } }
1e99a765c548db710902c9f441673f35
34.20274
171
0.606818
false
false
false
false
kyleweiner/KWButtonNode
refs/heads/master
Demo/KWButtonNodeDemo/Controllers/GameViewController.swift
mit
1
// // GameViewController.swift // Created by Kyle Weiner on 4/18/15. // import UIKit import SpriteKit class GameViewController: UIViewController { override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() let skview = view as! SKView skview.ignoresSiblingOrder = true skview.multipleTouchEnabled = true if let scene = GameScene(fileNamed: "GameScene") { scene.scaleMode = .AspectFill scene.blendMode = .Replace skview.presentScene(scene) } #if DEBUG skview.showsFPS = true skview.showsDrawCount = true skview.showsNodeCount = true #endif } }
267e4ea5bf83231f00903e0d0dc53b1d
22.181818
58
0.60733
false
false
false
false
MillmanY/MMPlayerView
refs/heads/master
MMPlayerView/Classes/Extension/MMPlayer+String+SRTTime.swift
mit
1
// // String+SRTTime.swift // MMPlayerView // // Created by Millman on 2019/12/9. // import Foundation extension String { var timeToInterval: TimeInterval { let split = self.split(separator: ",") let count = split.count if count == 0 { return 0 } else if count == 2 { let time = split[0] let hms = time.split(separator: ":") if hms.count == 3 { let h = (Double(String(hms[0])) ?? 0)*3600 let m = (Double(String(hms[1])) ?? 0)*60 let s = (Double(String(hms[2])) ?? 0) let mile = (Double(String(split[1])) ?? 0)/1000 return h+m+s+mile } } return 0 } var splitSRTTime: ClosedRange<TimeInterval> { let slice = self.components(separatedBy: CharacterSet.whitespaces) if slice.count == 3 { return slice[0].timeToInterval...slice[2].timeToInterval } return 0...0 } }
81223afa2e40a87dc735cc3f6a2bc60e
27.111111
74
0.507905
false
false
false
false
ZeldaIV/TDC2015-FP
refs/heads/master
Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift
gpl-3.0
13
// // UIBarButtonItem.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift #endif extension UIBarButtonItem { /** Reactive wrapper for target action pattern on `self`. */ public var rx_tap: ControlEvent<Void> { let source: Observable<Void> = AnonymousObservable { observer in let target = BarButtonItemTarget(barButtonItem: self) { observer.on(.Next()) } return target }.takeUntil(rx_deallocated) return ControlEvent(source: source) } } @objc class BarButtonItemTarget: NSObject, Disposable { typealias Callback = () -> Void weak var barButtonItem: UIBarButtonItem? var callback: Callback! init(barButtonItem: UIBarButtonItem, callback: () -> Void) { self.barButtonItem = barButtonItem self.callback = callback super.init() barButtonItem.target = self barButtonItem.action = Selector("action:") } deinit { dispose() } func dispose() { MainScheduler.ensureExecutingOnScheduler() barButtonItem?.target = nil barButtonItem?.action = nil callback = nil } func action(sender: AnyObject) { callback() } }
358cd8c418adfd0e8fe1974863eab1b2
20.861538
72
0.596479
false
false
false
false
MangoMade/MMSegmentedControl
refs/heads/master
Source/Extension.swift
mit
1
// // Extension.swift // MMSegmentedControl // // Created by Aqua on 2017/4/25. // Copyright © 2017年 Aqua. All rights reserved. // internal extension UIImage { static func image(color: UIColor) -> UIImage { let size = CGSize(width: 1, height: 1) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } internal extension String { func getTextRectSize(font:UIFont, size:CGSize) -> CGRect { let attributes = [NSAttributedStringKey.font: font] let rect:CGRect = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) return rect; } } internal extension UIColor { convenience init(hex hexValue: Int, alpha: CGFloat = 1) { let redValue = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 let greenValue = CGFloat((hexValue & 0xFF00) >> 8) / 255.0 let blueValue = CGFloat(hexValue & 0xFF) / 255.0 self.init(red: redValue, green: greenValue, blue: blueValue, alpha: alpha) } }
f6922970879d40fb88d7baf79ac78166
30.585366
127
0.647876
false
false
false
false
googlearchive/cannonball-ios
refs/heads/master
Cannonball/Theme.swift
apache-2.0
1
// // Copyright (C) 2018 Google, Inc. and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation open class Theme { let name: String let words: [String] let pictures: [String] init?(jsonDictionary: [String : AnyObject]) { if let optionalName = jsonDictionary["name"] as? String, let optionalWords = jsonDictionary["words"] as? [String], let optionalPictures = jsonDictionary["pictures"] as? [String] { name = optionalName words = optionalWords pictures = optionalPictures } else { name = "" words = [] pictures = [] return nil } } open func getRandomWords(_ wordCount: Int) -> [String] { var wordsCopy = [String](words) // Sort randomly the elements of the dictionary. wordsCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the desired number of words. return Array(wordsCopy[0..<wordCount]) } open func getRandomPicture() -> String? { var picturesCopy = [String](pictures) // Sort randomly the pictures. picturesCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the first picture. return picturesCopy.first } class func getThemes() -> [Theme] { var themes = [Theme]() let path = Bundle.main.path(forResource: "Themes", ofType: "json")! if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), let jsonArray = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [AnyObject] { themes = jsonArray.compactMap() { return Theme(jsonDictionary: $0 as! [String : AnyObject]) } } return themes } }
6151994cf23b0751753adb8f76d7649a
31.053333
109
0.612313
false
false
false
false
andinfinity/idrop.link-osx
refs/heads/master
JWT/JWT.swift
apache-2.0
6
import Foundation import CryptoSwift public typealias Payload = [String:AnyObject] /// The supported Algorithms public enum Algorithm : CustomStringConvertible { /// No Algorithm, i-e, insecure case None /// HMAC using SHA-256 hash algorithm case HS256(String) /// HMAC using SHA-384 hash algorithm case HS384(String) /// HMAC using SHA-512 hash algorithm case HS512(String) static func algorithm(name:String, key:String?) -> Algorithm? { if name == "none" { if key != nil { return nil // We don't allow nil when we configured a key } return Algorithm.None } else if let key = key { if name == "HS256" { return .HS256(key) } else if name == "HS384" { return .HS384(key) } else if name == "HS512" { return .HS512(key) } } return nil } public var description:String { switch self { case .None: return "none" case .HS256: return "HS256" case .HS384: return "HS384" case .HS512: return "HS512" } } /// Sign a message using the algorithm func sign(message:String) -> String { func signHS(key:String, variant:CryptoSwift.HMAC.Variant) -> String { let keyData = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let messageData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let mac = Authenticator.HMAC(key: keyData.arrayOfBytes(), variant:variant) let result = mac.authenticate(messageData.arrayOfBytes())! return base64encode(NSData.withBytes(result)) } switch self { case .None: return "" case .HS256(let key): return signHS(key, variant: .sha256) case .HS384(let key): return signHS(key, variant: .sha384) case .HS512(let key): return signHS(key, variant: .sha512) } } /// Verify a signature for a message using the algorithm func verify(message:String, signature:NSData) -> Bool { return sign(message) == base64encode(signature) } } // MARK: Encoding /*** Encode a payload - parameter payload: The payload to sign - parameter algorithm: The algorithm to sign the payload with - returns: The JSON web token as a String */ public func encode(payload:Payload, algorithm:Algorithm) -> String { func encodeJSON(payload:Payload) -> String? { if let data = try? NSJSONSerialization.dataWithJSONObject(payload, options: NSJSONWritingOptions(rawValue: 0)) { return base64encode(data) } return nil } let header = encodeJSON(["typ": "JWT", "alg": algorithm.description])! let payload = encodeJSON(payload)! let signingInput = "\(header).\(payload)" let signature = algorithm.sign(signingInput) return "\(signingInput).\(signature)" } public class PayloadBuilder { var payload = Payload() public var issuer:String? { get { return payload["iss"] as? String } set { payload["iss"] = newValue } } public var audience:String? { get { return payload["aud"] as? String } set { payload["aud"] = newValue } } public var expiration:NSDate? { get { if let expiration = payload["exp"] as? NSTimeInterval { return NSDate(timeIntervalSince1970: expiration) } return nil } set { payload["exp"] = newValue?.timeIntervalSince1970 } } public var notBefore:NSDate? { get { if let notBefore = payload["nbf"] as? NSTimeInterval { return NSDate(timeIntervalSince1970: notBefore) } return nil } set { payload["nbf"] = newValue?.timeIntervalSince1970 } } public var issuedAt:NSDate? { get { if let issuedAt = payload["iat"] as? NSTimeInterval { return NSDate(timeIntervalSince1970: issuedAt) } return nil } set { payload["iat"] = newValue?.timeIntervalSince1970 } } public subscript(key: String) -> AnyObject? { get { return payload[key] } set { payload[key] = newValue } } } public func encode(algorithm:Algorithm, closure:(PayloadBuilder -> ())) -> String { let builder = PayloadBuilder() closure(builder) return encode(builder.payload, algorithm: algorithm) }
94bd1e55fe3c618f16041fe077ab0f07
22.755556
116
0.637278
false
false
false
false
LarsStegman/helios-for-reddit
refs/heads/master
Sources/Authorization/AuthorizationPageLoader.swift
mit
1
// // AuthorizationPageLoader.swift // Helios // // Created by Lars Stegman on 16-01-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation protocol AuthorizationLocationCreator { func urlForAuthorization(using parameters: AuthorizationParameters) throws -> URL } protocol AuthorizationParameters { var clientId: String { get } var redirectUri: URL { get } var scopes: [Scope] { get } var preferredDuration: AuthorizationDuration { get } var sentState: String { get } var responseType: AuthorizationFlowType { get } } extension AuthorizationParameters { var scopeList: String { return scopes.map( { return $0.rawValue }).joined(separator: " ") } } extension AuthorizationContext: AuthorizationParameters {} /// Creates the URL at which users can authorize an application struct AuthorizationPageLoader: AuthorizationLocationCreator { var compact: Bool = false init(compact: Bool = false) { self.compact = compact } private var authorizationURL: URLComponents { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "www.reddit.com" urlComponents.path = compact ? "/api/v1/authorize.compact" : "/api/v1/authorize" return urlComponents } /// Generates the url where the user can authorize the application /// /// - Parameter parameters: <#parameters description#> /// - Returns: <#return value description#> /// - Throws: <#throws value description#> func urlForAuthorization(using parameters: AuthorizationParameters) throws -> URL { guard let encodedState = parameters.sentState.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { throw AuthorizationError.invalidStateString } var url = authorizationURL url.queryItems = [URLQueryItem(name: "client_id", value: parameters.clientId), URLQueryItem(name: "response_type", value: parameters.responseType.rawValue), URLQueryItem(name: "state", value: encodedState), URLQueryItem(name: "redirect_uri", value: parameters .redirectUri.absoluteString), URLQueryItem(name: "duration", value: parameters.preferredDuration.rawValue), URLQueryItem(name: "scope", value: parameters.scopeList)] return url.url! } }
afc183ff4226dae54ef1c67cf2b6f96f
36.242424
123
0.673312
false
false
false
false
yannickl/AwaitKit
refs/heads/master
Tests/AwaitKitTests/AwaitKitAwaitTests.swift
mit
1
/* * AwaitKit * * Copyright 2016-present Yannick Loriot. * http://yannickloriot.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 AwaitKit import PromiseKit import XCTest class AwaitKitAwaitTests: XCTestCase { let backgroundQueue = DispatchQueue(label: "com.yannickloriot.testqueue", attributes: .concurrent) let commonError = NSError(domain: "com.yannickloriot.error", code: 320, userInfo: nil) func testSimpleAwaitPromise() { let promise: Promise<String> = Promise { seal in let deadlineTime = DispatchTime.now() + .seconds(1) backgroundQueue.asyncAfter(deadline: deadlineTime, execute: { seal.fulfill("AwaitedPromiseKit") }) } let name = try! await(promise) XCTAssertEqual(name, "AwaitedPromiseKit") } func testSimpleAwaitGuarantee() { let guarantee: Guarantee<String> = Guarantee { fulfill in let deadlineTime = DispatchTime.now() + .seconds(1) backgroundQueue.asyncAfter(deadline: deadlineTime, execute: { fulfill("AwaitedPromiseKit") }) } let name = try! await(guarantee) XCTAssertEqual(name, "AwaitedPromiseKit") } func testSimpleFailedAwaitPromise() { let promise: Promise<String> = Promise { seal in let deadlineTime = DispatchTime.now() + .seconds(1) backgroundQueue.asyncAfter(deadline: deadlineTime, execute: { seal.reject(self.commonError) }) } XCTAssertThrowsError(try await(promise)) } func testNoValueAwaitPromise() { let promise: Promise<Void> = Promise { seal in seal.fulfill(()) } XCTAssertNotNil(promise.value) } func testNoValueAwaitGuarantee() { let guarantee: Guarantee<Void> = Guarantee { fulfill in fulfill(()) } XCTAssertNotNil(guarantee.value) } func testAwaitBlock() { var name: String = try! await { return "AwaitedPromiseKit" } XCTAssertEqual(name, "AwaitedPromiseKit") name = try! await { Thread.sleep(forTimeInterval: 0.2) return "PromiseKit" } XCTAssertEqual(name, "PromiseKit") do { try await { throw self.commonError } XCTAssertTrue(false) } catch { XCTAssertTrue(true) } } func testAsyncInsideAwaitBlock() { let name: String = try! await(async({ return "AwaitedPromiseKit" })) XCTAssertEqual(name, "AwaitedPromiseKit") let error: String? = try? await(async({ throw self.commonError })) XCTAssertNil(error) } }
a15a444a20b900afbb8b449e2ad2bcf4
26.341085
100
0.693224
false
true
false
false
SanctionCo/pilot-ios
refs/heads/master
Example/Pods/Locksmith/Source/LocksmithInternetProtocol.swift
apache-2.0
13
import Foundation public enum LocksmithInternetProtocol: RawRepresentable { case ftp, ftpAccount, http, irc, nntp, pop3, smtp, socks, imap, ldap, appleTalk, afp, telnet, ssh, ftps, https, httpProxy, httpsProxy, ftpProxy, smb, rtsp, rtspProxy, daap, eppc, ipp, nntps, ldaps, telnetS, imaps, ircs, pop3S public init?(rawValue: String) { switch rawValue { case String(kSecAttrProtocolFTP): self = .ftp case String(kSecAttrProtocolFTPAccount): self = .ftpAccount case String(kSecAttrProtocolHTTP): self = .http case String(kSecAttrProtocolIRC): self = .irc case String(kSecAttrProtocolNNTP): self = .nntp case String(kSecAttrProtocolPOP3): self = .pop3 case String(kSecAttrProtocolSMTP): self = .smtp case String(kSecAttrProtocolSOCKS): self = .socks case String(kSecAttrProtocolIMAP): self = .imap case String(kSecAttrProtocolLDAP): self = .ldap case String(kSecAttrProtocolAppleTalk): self = .appleTalk case String(kSecAttrProtocolAFP): self = .afp case String(kSecAttrProtocolTelnet): self = .telnet case String(kSecAttrProtocolSSH): self = .ssh case String(kSecAttrProtocolFTPS): self = .ftps case String(kSecAttrProtocolHTTPS): self = .https case String(kSecAttrProtocolHTTPProxy): self = .httpProxy case String(kSecAttrProtocolHTTPSProxy): self = .httpsProxy case String(kSecAttrProtocolFTPProxy): self = .ftpProxy case String(kSecAttrProtocolSMB): self = .smb case String(kSecAttrProtocolRTSP): self = .rtsp case String(kSecAttrProtocolRTSPProxy): self = .rtspProxy case String(kSecAttrProtocolDAAP): self = .daap case String(kSecAttrProtocolEPPC): self = .eppc case String(kSecAttrProtocolIPP): self = .ipp case String(kSecAttrProtocolNNTPS): self = .nntps case String(kSecAttrProtocolLDAPS): self = .ldaps case String(kSecAttrProtocolTelnetS): self = .telnetS case String(kSecAttrProtocolIMAPS): self = .imaps case String(kSecAttrProtocolIRCS): self = .ircs case String(kSecAttrProtocolPOP3S): self = .pop3S default: self = .http } } public var rawValue: String { switch self { case .ftp: return String(kSecAttrProtocolFTP) case .ftpAccount: return String(kSecAttrProtocolFTPAccount) case .http: return String(kSecAttrProtocolHTTP) case .irc: return String(kSecAttrProtocolIRC) case .nntp: return String(kSecAttrProtocolNNTP) case .pop3: return String(kSecAttrProtocolPOP3) case .smtp: return String(kSecAttrProtocolSMTP) case .socks: return String(kSecAttrProtocolSOCKS) case .imap: return String(kSecAttrProtocolIMAP) case .ldap: return String(kSecAttrProtocolLDAP) case .appleTalk: return String(kSecAttrProtocolAppleTalk) case .afp: return String(kSecAttrProtocolAFP) case .telnet: return String(kSecAttrProtocolTelnet) case .ssh: return String(kSecAttrProtocolSSH) case .ftps: return String(kSecAttrProtocolFTPS) case .https: return String(kSecAttrProtocolHTTPS) case .httpProxy: return String(kSecAttrProtocolHTTPProxy) case .httpsProxy: return String(kSecAttrProtocolHTTPSProxy) case .ftpProxy: return String(kSecAttrProtocolFTPProxy) case .smb: return String(kSecAttrProtocolSMB) case .rtsp: return String(kSecAttrProtocolRTSP) case .rtspProxy: return String(kSecAttrProtocolRTSPProxy) case .daap: return String(kSecAttrProtocolDAAP) case .eppc: return String(kSecAttrProtocolEPPC) case .ipp: return String(kSecAttrProtocolIPP) case .nntps: return String(kSecAttrProtocolNNTPS) case .ldaps: return String(kSecAttrProtocolLDAPS) case .telnetS: return String(kSecAttrProtocolTelnetS) case .imaps: return String(kSecAttrProtocolIMAPS) case .ircs: return String(kSecAttrProtocolIRCS) case .pop3S: return String(kSecAttrProtocolPOP3S) } } }
ae077fce6e67fa2291642fd64d667615
33.553191
229
0.590928
false
false
false
false
kyouko-taiga/anzen
refs/heads/master
Tests/ParserTests/ExpressionParserTests.swift
apache-2.0
1
import XCTest import AST @testable import Parser class ExpressionParserTests: XCTestCase, ParserTestCase { func testParseNullRef() { var pr: Parser.Result<Expr?> pr = parse("nullref", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: NullRef.self)) } func testParseIntegerLiteral() { var pr: Parser.Result<Expr?> pr = parse("42", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Int>.self)) assertThat((pr.value as? Literal<Int>)?.value, .equals(42)) } func testParseFloatingPointLiteral() { var pr: Parser.Result<Expr?> pr = parse("4.2", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Double>.self)) assertThat((pr.value as? Literal<Double>)?.value, .equals(4.2)) } func testParseStringLiteral() { var pr: Parser.Result<Expr?> pr = parse("\"Hello, World!\"", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<String>.self)) assertThat((pr.value as? Literal<String>)?.value, .equals("Hello, World!")) } func testParseBoolLiteral() { var pr: Parser.Result<Expr?> pr = parse("true", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Bool>.self)) assertThat((pr.value as? Literal<Bool>)?.value, .equals(true)) pr = parse("false", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Bool>.self)) assertThat((pr.value as? Literal<Bool>)?.value, .equals(false)) } func testParseUnaryExpression() { var pr: Parser.Result<Expr?> pr = parse("+1", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: UnExpr.self)) if let expression = pr.value as? UnExpr { assertThat(expression.op, .equals(.add)) assertThat(expression.operand, .isInstance(of: Literal<Int>.self)) } } func testCastExpression() { var pr: Parser.Result<Expr?> pr = parse("a as Int", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CastExpr.self)) pr = parse("a as Int as Any", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CastExpr.self)) if let expression = pr.value as? CastExpr { assertThat(expression.castType, .isInstance(of: TypeIdent.self)) if let typeIdentifier = expression.castType as? TypeIdent { assertThat(typeIdentifier.name, .equals("Any")) } } let source = "a as Int".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CastExpr.self)) } func testBinaryExpression() { var pr: Parser.Result<Expr?> pr = parse("a + b", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) pr = parse("a + b * c", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) if let expression = pr.value as? BinExpr { assertThat(expression.right, .isInstance(of: BinExpr.self)) } pr = parse("a * b + c", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) if let expression = pr.value as? BinExpr { assertThat(expression.right, .isInstance(of: Ident.self)) } let source = "a + b".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) } func testParseIdentifier() { var pr: Parser.Result<Expr?> pr = parse("x", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Ident.self)) if let identifier = pr.value as? Ident { assertThat(identifier.name, .equals("x")) assertThat(identifier.specializations, .isEmpty) } pr = parse("Map<Key=String, Value=Int>", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Ident.self)) if let identifier = pr.value as? Ident { assertThat(identifier.name, .equals("Map")) assertThat(identifier.specializations, .count(2)) assertThat(identifier.specializations.keys, .contains("Key")) assertThat(identifier.specializations.keys, .contains("Value")) } let source = "Map < Key = String , Value = Int , >" .split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Ident.self)) } func testParseIfExpression() { var pr: Parser.Result<Expr?> pr = parse("if c1 {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) if let conditional = pr.value as? IfExpr { assertThat(conditional.elseBlock, .isNil) } pr = parse("if c1 {} else {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) if let conditional = pr.value as? IfExpr { assertThat(conditional.elseBlock, .isInstance(of: Block.self)) } pr = parse("if c1 {} else if c2 {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) if let conditional = pr.value as? IfExpr { assertThat(conditional.elseBlock, .isInstance(of: IfExpr.self)) } let source = "if c1 { } else if c2 { }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) } func testParseLambda() { var pr: Parser.Result<Expr?> pr = parse("fun {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .isEmpty) assertThat(lambda.codomain, .isNil) } pr = parse("fun (a: Int, _ b: Int, c d: Int) {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .count(3)) if lambda.parameters.count > 2 { assertThat(lambda.parameters[0].label, .equals("a")) assertThat(lambda.parameters[0].name, .equals("a")) assertThat(lambda.parameters[0].typeAnnotation, .not(.isNil)) assertThat(lambda.parameters[1].label, .isNil) assertThat(lambda.parameters[1].name, .equals("b")) assertThat(lambda.parameters[1].typeAnnotation, .not(.isNil)) assertThat(lambda.parameters[2].label, .equals("c")) assertThat(lambda.parameters[2].name, .equals("d")) assertThat(lambda.parameters[2].typeAnnotation, .not(.isNil)) } assertThat(lambda.codomain, .isNil) } pr = parse("fun -> Int {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .isEmpty) assertThat(lambda.codomain, .not(.isNil)) } pr = parse("fun (_ x: Int) -> Int {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .count(1)) assertThat(lambda.codomain, .not(.isNil)) } let source = "fun ( _ x: Int , ) -> Int { }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) } func testParseArrayLiteral() { var pr: Parser.Result<Expr?> pr = parse("[]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) if let literal = pr.value as? ArrayLiteral { assertThat(literal.elements, .isEmpty) } pr = parse("[ a ]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) if let literal = pr.value as? ArrayLiteral { assertThat(literal.elements, .count(1)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } pr = parse("[ a, b, c ]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) if let literal = pr.value as? ArrayLiteral { assertThat(literal.elements, .count(3)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } let source = "[ a , b , c , ]".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) } func testParseSetLiteral() { var pr: Parser.Result<Expr?> pr = parse("{}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) if let literal = pr.value as? SetLiteral { assertThat(literal.elements, .isEmpty) } pr = parse("{ a }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) if let literal = pr.value as? SetLiteral { assertThat(literal.elements, .count(1)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } pr = parse("{ a, b, c }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) if let literal = pr.value as? SetLiteral { assertThat(literal.elements, .count(3)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } let source = "{ a , b , c , }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) } func testParseMapLiteral() { var pr: Parser.Result<Expr?> pr = parse("{:}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) if let literal = pr.value as? MapLiteral { assertThat(literal.elements, .isEmpty) } pr = parse("{ a: 1 }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) if let literal = pr.value as? MapLiteral { assertThat(literal.elements, .count(1)) assertThat(literal.elements["a"], .isInstance(of: Literal<Int>.self)) } pr = parse("{ a: 1, b: 2, c: 3 }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) if let literal = pr.value as? MapLiteral { assertThat(literal.elements, .count(3)) assertThat(literal.elements["a"], .isInstance(of: Literal<Int>.self)) assertThat(literal.elements["b"], .isInstance(of: Literal<Int>.self)) assertThat(literal.elements["c"], .isInstance(of: Literal<Int>.self)) } let source = "{ a : 1 , b : 2 , c : 3 , }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) } func testParseImplicitSelect() { var pr: Parser.Result<Expr?> pr = parse(".a", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isNil) assertThat(select.ownee.name, .equals("a")) } pr = parse(".+", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isNil) assertThat(select.ownee.name, .equals("+")) } } func testParseSelect() { var pr: Parser.Result<Expr?> pr = parse("a.a", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isInstance(of: Ident.self)) assertThat(select.ownee.name, .equals("a")) } pr = parse("a.+", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isInstance(of: Ident.self)) assertThat(select.ownee.name, .equals("+")) } let source = "a .+".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) } func testParseCall() { var pr: Parser.Result<Expr?> pr = parse("f()", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .isEmpty) } pr = parse("f()()", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: CallExpr.self)) } pr = parse("f(x)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f(a := x)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .equals("a")) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f(x, b := y)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(2)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } if call.arguments.count > 1 { assertThat(call.arguments[1].label, .equals("b")) assertThat(call.arguments[1].bindingOp, .equals(.copy)) assertThat(call.arguments[1].value, .isInstance(of: Ident.self)) } } let source = "f( x , b := y , )".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) } func testParseSubscript() { var pr: Parser.Result<Expr?> pr = parse("f[]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .isEmpty) } pr = parse("f[][]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: SubscriptExpr.self)) } pr = parse("f[x]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f[a := x]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .equals("a")) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f[x, b := y]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(2)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } if call.arguments.count > 1 { assertThat(call.arguments[1].label, .equals("b")) assertThat(call.arguments[1].bindingOp, .equals(.copy)) assertThat(call.arguments[1].value, .isInstance(of: Ident.self)) } } let source = "f[ x , b := y , ]".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) } func testParseEnclosed() { var pr: Parser.Result<Expr?> pr = parse("(a)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: EnclosedExpr.self)) if let enclosed = pr.value as? EnclosedExpr { assertThat(enclosed.expression, .isInstance(of: Ident.self)) } let source = "( a )".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: EnclosedExpr.self)) if let enclosed = pr.value as? EnclosedExpr { assertThat(enclosed.expression, .isInstance(of: Ident.self)) } } }
232f864e00db678c5530763192323020
35.885185
94
0.657194
false
false
false
false
mozilla-mobile/focus
refs/heads/master
Blockzilla/AppDelegate.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Telemetry import Glean protocol AppSplashController { var splashView: UIView { get } func toggleSplashView(hide: Bool) } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, ModalDelegate, AppSplashController { static let prefIntroDone = "IntroDone" static let prefIntroVersion = 2 static let prefWhatsNewDone = "WhatsNewDone" static let prefWhatsNewCounter = "WhatsNewCounter" static var needsAuthenticated = false // This enum can be expanded to support all new shortcuts added to menu. enum ShortcutIdentifier: String { case EraseAndOpen init?(fullIdentifier: String) { guard let shortIdentifier = fullIdentifier.components(separatedBy: ".").last else { return nil } self.init(rawValue: shortIdentifier) } } var window: UIWindow? var splashView: UIView = UIView() private lazy var browserViewController = { BrowserViewController(appSplashController: self) }() private var queuedUrl: URL? private var queuedString: String? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if AppInfo.testRequestsReset() { if let bundleID = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: bundleID) } UserDefaults.standard.removePersistentDomain(forName: AppInfo.sharedContainerIdentifier) } setupContinuousDeploymentTooling() setupErrorTracking() setupTelemetry() TPStatsBlocklistChecker.shared.startup() // Count number of app launches for requesting a review let currentLaunchCount = UserDefaults.standard.integer(forKey: UIConstants.strings.userDefaultsLaunchCountKey) UserDefaults.standard.set(currentLaunchCount + 1, forKey: UIConstants.strings.userDefaultsLaunchCountKey) // Set original default values for showing tips let tipDefaults = [TipManager.TipKey.autocompleteTip: true, TipManager.TipKey.sitesNotWorkingTip: true, TipManager.TipKey.siriFavoriteTip: true, TipManager.TipKey.biometricTip: true, TipManager.TipKey.shareTrackersTip: true, TipManager.TipKey.siriEraseTip: true, TipManager.TipKey.requestDesktopTip: true] UserDefaults.standard.register(defaults: tipDefaults) // Disable localStorage. // We clear the Caches directory after each Erase, but WebKit apparently maintains // localStorage in-memory (bug 1319208), so we just disable it altogether. UserDefaults.standard.set(false, forKey: "WebKitLocalStorageEnabledPreferenceKey") UserDefaults.standard.removeObject(forKey: "searchedHistory") // Re-register the blocking lists at startup in case they've changed. Utils.reloadSafariContentBlocker() LocalWebServer.sharedInstance.start() window = UIWindow(frame: UIScreen.main.bounds) browserViewController.modalDelegate = self window?.rootViewController = browserViewController window?.makeKeyAndVisible() WebCacheUtils.reset() displaySplashAnimation() KeyboardHelper.defaultHelper.startObserving() // Override default keyboard appearance UITextField.appearance().keyboardAppearance = .dark let prefIntroDone = UserDefaults.standard.integer(forKey: AppDelegate.prefIntroDone) if AppInfo.isTesting() { let firstRunViewController = IntroViewController() firstRunViewController.modalPresentationStyle = .fullScreen self.browserViewController.present(firstRunViewController, animated: false, completion: nil) return true } let needToShowFirstRunExperience = prefIntroDone < AppDelegate.prefIntroVersion if needToShowFirstRunExperience { // Show the first run UI asynchronously to avoid the "unbalanced calls to begin/end appearance transitions" warning. DispatchQueue.main.async { // Set the prefIntroVersion viewed number in the same context as the presentation. UserDefaults.standard.set(AppDelegate.prefIntroVersion, forKey: AppDelegate.prefIntroDone) UserDefaults.standard.set(AppInfo.shortVersion, forKey: AppDelegate.prefWhatsNewDone) let introViewController = IntroViewController() introViewController.modalPresentationStyle = .fullScreen self.browserViewController.present(introViewController, animated: false, completion: nil) } } // Don't highlight whats new on a fresh install (prefIntroDone == 0 on a fresh install) if let lastShownWhatsNew = UserDefaults.standard.string(forKey: AppDelegate.prefWhatsNewDone)?.first, let currentMajorRelease = AppInfo.shortVersion.first { if prefIntroDone != 0 && lastShownWhatsNew != currentMajorRelease { let counter = UserDefaults.standard.integer(forKey: AppDelegate.prefWhatsNewCounter) switch counter { case 4: // Shown three times, remove counter UserDefaults.standard.set(AppInfo.shortVersion, forKey: AppDelegate.prefWhatsNewDone) UserDefaults.standard.removeObject(forKey: AppDelegate.prefWhatsNewCounter) default: // Show highlight UserDefaults.standard.set(counter+1, forKey: AppDelegate.prefWhatsNewCounter) } } } return true } func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } guard let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [AnyObject], let urlSchemes = urlTypes.first?["CFBundleURLSchemes"] as? [String] else { // Something very strange has happened; org.mozilla.Blockzilla should be the zeroeth URL type. return false } guard let scheme = components.scheme, let host = url.host, urlSchemes.contains(scheme) else { return false } let query = getQuery(url: url) let isHttpScheme = scheme == "http" || scheme == "https" if isHttpScheme { if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. browserViewController.submit(url: url) } else { queuedUrl = url } } else if host == "open-url" { let urlString = unescape(string: query["url"]) ?? "" guard let url = URL(string: urlString) else { return false } if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. browserViewController.submit(url: url) } else { queuedUrl = url } } else if host == "open-text" || isHttpScheme { let text = unescape(string: query["text"]) ?? "" if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. browserViewController.openOverylay(text: text) } else { queuedString = text } } return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { completionHandler(handleShortcut(shortcutItem: shortcutItem)) } private func handleShortcut(shortcutItem: UIApplicationShortcutItem) -> Bool { let shortcutType = shortcutItem.type guard let shortcutIdentifier = ShortcutIdentifier(fullIdentifier: shortcutType) else { return false } switch shortcutIdentifier { case .EraseAndOpen: browserViewController.resetBrowser(hidePreviousSession: true) } return true } public func getQuery(url: URL) -> [String: String] { var results = [String: String]() let keyValues = url.query?.components(separatedBy: "&") if keyValues?.count ?? 0 > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results[kv[0]] = kv[1] } } } return results } public func unescape(string: String?) -> String? { guard let string = string else { return nil } return CFURLCreateStringByReplacingPercentEscapes( kCFAllocatorDefault, string as CFString, "" as CFString) as String } private func displaySplashAnimation() { let splashView = self.splashView splashView.backgroundColor = UIConstants.colors.background window!.addSubview(splashView) let logoImage = UIImageView(image: AppInfo.config.wordmark) splashView.addSubview(logoImage) splashView.snp.makeConstraints { make in make.edges.equalTo(window!) } logoImage.snp.makeConstraints { make in make.center.equalTo(splashView) } let animationDuration = 0.25 UIView.animate(withDuration: animationDuration, delay: 0.0, options: UIView.AnimationOptions(), animations: { logoImage.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1.0) }, completion: { success in UIView.animate(withDuration: animationDuration, delay: 0.0, options: UIView.AnimationOptions(), animations: { splashView.alpha = 0 logoImage.layer.transform = CATransform3DMakeScale(2.0, 2.0, 1.0) }, completion: { success in splashView.isHidden = true logoImage.layer.transform = CATransform3DIdentity }) }) } func applicationWillResignActive(_ application: UIApplication) { toggleSplashView(hide: false) browserViewController.exitFullScreenVideo() } func applicationDidBecomeActive(_ application: UIApplication) { if Settings.siriRequestsErase() { browserViewController.photonActionSheetDidDismiss() browserViewController.dismiss(animated: true, completion: nil) browserViewController.navigationController?.popViewController(animated: true) browserViewController.resetBrowser(hidePreviousSession: true) Settings.setSiriRequestErase(to: false) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.eraseInBackground) } Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.foreground, object: TelemetryEventObject.app) if let url = queuedUrl { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.openedFromExtension, object: TelemetryEventObject.app) browserViewController.ensureBrowsingMode() browserViewController.submit(url: url) queuedUrl = nil } else if let text = queuedString { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.openedFromExtension, object: TelemetryEventObject.app) browserViewController.openOverylay(text: text) queuedString = nil } } func applicationDidEnterBackground(_ application: UIApplication) { // Record an event indicating that we have entered the background and end our telemetry // session. This gets called every time the app goes to background but should not get // called for *temporary* interruptions such as an incoming phone call until the user // takes action and we are officially backgrounded. AppDelegate.needsAuthenticated = true let orientation = UIDevice.current.orientation.isPortrait ? "Portrait" : "Landscape" Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.background, object: TelemetryEventObject.app, value: nil, extras: ["orientation": orientation]) } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { guard #available(iOS 12.0, *) else { return false } browserViewController.photonActionSheetDidDismiss() browserViewController.dismiss(animated: true, completion: nil) browserViewController.navigationController?.popViewController(animated: true) switch userActivity.activityType { case "org.mozilla.ios.Klar.eraseAndOpen": browserViewController.resetBrowser(hidePreviousSession: true) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.eraseAndOpen) case "org.mozilla.ios.Klar.openUrl": guard let urlString = userActivity.userInfo?["url"] as? String, let url = URL(string: urlString) else { return false } browserViewController.resetBrowser(hidePreviousSession: true) browserViewController.ensureBrowsingMode() browserViewController.submit(url: url) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.openFavoriteSite) case "EraseIntent": guard userActivity.interaction?.intent as? EraseIntent != nil else { return false } browserViewController.resetBrowser() Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.eraseInBackground) default: break } return true } func toggleSplashView(hide: Bool) { let duration = 0.25 splashView.animateHidden(hide, duration: duration) if !hide { browserViewController.deactivateUrlBarOnHomeView() } else { browserViewController.activateUrlBarOnHomeView() } } } // MARK: - Telemetry & Tooling setup extension AppDelegate { func setupContinuousDeploymentTooling() { #if BUDDYBUILD BuddyBuildSDK.setup() #endif } func setupErrorTracking() { // Set up Sentry let sendUsageData = Settings.getToggle(.sendAnonymousUsageData) SentryIntegration.shared.setup(sendUsageData: sendUsageData) } func setupTelemetry() { let telemetryConfig = Telemetry.default.configuration telemetryConfig.appName = AppInfo.isKlar ? "Klar" : "Focus" telemetryConfig.userDefaultsSuiteName = AppInfo.sharedContainerIdentifier telemetryConfig.appVersion = AppInfo.shortVersion // Since Focus always clears the caches directory and Telemetry files are // excluded from iCloud backup, we store pings in documents. telemetryConfig.dataDirectory = .documentDirectory let activeSearchEngine = SearchEngineManager(prefs: UserDefaults.standard).activeEngine let defaultSearchEngineProvider = activeSearchEngine.isCustom ? "custom" : activeSearchEngine.name telemetryConfig.defaultSearchEngineProvider = defaultSearchEngineProvider telemetryConfig.measureUserDefaultsSetting(forKey: SearchEngineManager.prefKeyEngine, withDefaultValue: defaultSearchEngineProvider) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockAds, withDefaultValue: Settings.getToggle(.blockAds)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockAnalytics, withDefaultValue: Settings.getToggle(.blockAnalytics)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockSocial, withDefaultValue: Settings.getToggle(.blockSocial)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockOther, withDefaultValue: Settings.getToggle(.blockOther)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockFonts, withDefaultValue: Settings.getToggle(.blockFonts)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.biometricLogin, withDefaultValue: Settings.getToggle(.biometricLogin)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.enableSearchSuggestions, withDefaultValue: Settings.getToggle(.enableSearchSuggestions)) #if DEBUG telemetryConfig.updateChannel = "debug" telemetryConfig.isCollectionEnabled = false telemetryConfig.isUploadEnabled = false #else telemetryConfig.updateChannel = "release" telemetryConfig.isCollectionEnabled = Settings.getToggle(.sendAnonymousUsageData) telemetryConfig.isUploadEnabled = Settings.getToggle(.sendAnonymousUsageData) #endif Telemetry.default.add(pingBuilderType: CorePingBuilder.self) Telemetry.default.add(pingBuilderType: FocusEventPingBuilder.self) // Start the telemetry session and record an event indicating that we have entered the Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.foreground, object: TelemetryEventObject.app) if let clientId = UserDefaults .standard.string(forKey: "telemetry-key-prefix-clientId") .flatMap(UUID.init(uuidString:)) { GleanMetrics.LegacyIds.clientId.set(clientId) } Glean.shared.initialize(uploadEnabled: Settings.getToggle(.sendAnonymousUsageData)) } func presentModal(viewController: UIViewController, animated: Bool) { window?.rootViewController?.present(viewController, animated: animated, completion: nil) } } protocol ModalDelegate { func presentModal(viewController: UIViewController, animated: Bool) } extension UINavigationController { override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
d74ad19f25f9ecab4a150c6f83087a77
44.907363
167
0.680447
false
true
false
false
AlexeyGolovenkov/DocGenerator
refs/heads/master
GRMustache.swift/Tests/Public/LambdaTests.swift
mit
1
// 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 XCTest import Mustache class LambdaTests: XCTestCase { func testMustacheSpecInterpolation() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L15 let lambda = Lambda { "world" } let template = try! Template(string: "Hello, {{lambda}}!") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "Hello, world!") } func testMustacheSpecInterpolationExpansion() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L29 let lambda = Lambda { "{{planet}}" } let template = try! Template(string: "Hello, {{lambda}}!") let data = [ "planet": Box("world"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "Hello, world!") } func testMustacheSpecInterpolationAlternateDelimiters() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L44 // With a difference: remove the "\n" character because GRMustache does // not honor mustache spec white space rules. let lambda = Lambda { "|planet| => {{planet}}" } let template = try! Template(string: "{{= | | =}}Hello, (|&lambda|)!") let data = [ "planet": Box("world"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "Hello, (|planet| => world)!") } func testMustacheSpecMultipleCalls() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L59 var calls = 0 let lambda = Lambda { calls += 1; return "\(calls)" } let template = try! Template(string: "{{lambda}} == {{{lambda}}} == {{lambda}}") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "1 == 2 == 3") } func testMustacheSpecEscaping() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L73 let lambda = Lambda { ">" } let template = try! Template(string: "<{{lambda}}{{{lambda}}}") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<&gt;>") } func testMustacheSpecSection() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L87 let lambda = Lambda { (string: String) in if string == "{{x}}" { return "yes" } else { return "no" } } let template = try! Template(string: "<{{#lambda}}{{x}}{{/lambda}}>") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<yes>") } func testMustacheSpecSectionExpansion() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L102 let lambda = Lambda { (string: String) in return "\(string){{planet}}\(string)" } let template = try! Template(string: "<{{#lambda}}-{{/lambda}}>") let data = [ "planet": Box("Earth"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<-Earth->") } func testMustacheSpecSectionAlternateDelimiters() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L117 let lambda = Lambda { (string: String) in return "\(string){{planet}} => |planet|\(string)" } let template = try! Template(string: "{{= | | =}}<|#lambda|-|/lambda|>") let data = [ "planet": Box("Earth"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<-{{planet}} => Earth->") } func testMustacheSpecSectionMultipleCalls() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L132 let lambda = Lambda { (string: String) in return "__\(string)__" } let template = try! Template(string: "{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "__FILE__ != __LINE__") } func testMustacheSpecInvertedSection() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L146 let lambda = Lambda { (string: String) in return "" } let template = try! Template(string: "<{{^lambda}}{{static}}{{/lambda}}>") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<>") } func testPartialInArity0Lambda() { // Lambda can't render partials let partials = ["partial" : "success"] let templateRepository = TemplateRepository(templates: partials) let lambda = Lambda { "{{>partial}}" } let template = try! templateRepository.template(string: "<{{lambda}}>") let data = [ "lambda": Box(lambda), ] do { try template.render(Box(data)) XCTFail("Expected MustacheError") } catch let error as MustacheError { XCTAssertEqual(error.kind, MustacheError.Kind.TemplateNotFound) } catch { XCTFail("Expected MustacheError") } } func testPartialInArity1Lambda() { // Lambda can't render partials let partials = ["partial" : "success"] let templateRepository = TemplateRepository(templates: partials) let lambda = Lambda { (string: String) in "{{>partial}}" } let template = try! templateRepository.template(string: "<{{#lambda}}...{{/lambda}}>") let data = [ "lambda": Box(lambda), ] do { try template.render(Box(data)) XCTFail("Expected MustacheError") } catch let error as MustacheError { XCTAssertEqual(error.kind, MustacheError.Kind.TemplateNotFound) } catch { XCTFail("Expected MustacheError") } } func testArity0LambdaInSectionTag() { let lambda = Lambda { "success" } let template = try! Template(string: "{{#lambda}}<{{.}}>{{/lambda}}") let rendering = try! template.render(Box(["lambda": Box(lambda)])) XCTAssertEqual(rendering, "<success>") } func testArity1LambdaInVariableTag() { let lambda = Lambda { (string) in string } let template = try! Template(string: "<{{lambda}}>") let rendering = try! template.render(Box(["lambda": Box(lambda)])) XCTAssertEqual(rendering, "<(Lambda)>") } }
ea838446d6f009431b9443381c582f1c
39.815166
115
0.601719
false
true
false
false
indragiek/Ares
refs/heads/master
client/AresKit/IncomingFileTransfer.swift
mit
1
// // IncomingFileTransfer.swift // Ares // // Created by Indragie on 1/31/16. // Copyright © 2016 Indragie Karunaratne. All rights reserved. // import Foundation import MultipeerConnectivity public protocol IncomingFileTransferDelegate: AnyObject { func incomingFileTransfer(transfer: IncomingFileTransfer, didStartReceivingFileWithName name: String, progress: NSProgress) func incomingFileTransfer(transfer: IncomingFileTransfer, didReceiveFileWithName name: String, URL: NSURL) func incomingFileTransfer(transfer: IncomingFileTransfer, didFailToReceiveFileWithName name: String, error: NSError) } @objc public final class IncomingFileTransfer: NSObject, MCSessionDelegate { public let context: FileTransferContext let session: MCSession private let remotePeerID: MCPeerID public weak var delegate: IncomingFileTransferDelegate? init(context: FileTransferContext, localPeerID: MCPeerID, remotePeerID: MCPeerID) { self.context = context self.session = MCSession(peer: localPeerID) self.remotePeerID = remotePeerID super.init() self.session.delegate = self } // MARK: MCSessionDelegate public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { guard peerID == remotePeerID else { return } delegate?.incomingFileTransfer(self, didStartReceivingFileWithName: resourceName, progress: progress) } public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) { guard peerID == remotePeerID else { return } if let error = error { delegate?.incomingFileTransfer(self, didFailToReceiveFileWithName: resourceName, error: error) } else { delegate?.incomingFileTransfer(self, didReceiveFileWithName: resourceName, URL: localURL) } session.disconnect() } public func session(session: MCSession, didReceiveCertificate certificate: [AnyObject]?, fromPeer peerID: MCPeerID, certificateHandler: (Bool) -> Void) { guard peerID == remotePeerID else { return } certificateHandler(true) } // Unused public func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {} public func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {} public func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) {} }
979cb84b32c79ce71dd0e6220f112db9
41.640625
179
0.729938
false
false
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Data/Networking/Model/EcoPoints/LeaderboardPlayer.swift
gpl-3.0
1
import Foundation import SwiftyJSON final class LeaderboardPlayer: JSONable, JSONCollection { let id: String let username: String let points: Int let profile: Int required init(parameter: JSON) { id = parameter["id"].stringValue username = parameter["username"].stringValue points = parameter["points"].intValue profile = parameter["profile"].intValue } static func collection(parameter: JSON) -> [LeaderboardPlayer] { var items: [LeaderboardPlayer] = [] for itemRepresentation in parameter.arrayValue { items.append(LeaderboardPlayer(parameter: itemRepresentation)) } return items } }
cc9ffe944135f99fdf0256647f7df708
23.206897
74
0.65812
false
false
false
false
annecruz/MDCSwipeToChoose
refs/heads/master
Examples/SwiftLikedOrNope/SwiftLikedOrNope/Person.swift
mit
3
// // Person.swift // SwiftLikedOrNope // // Copyright (c) 2014 to present, Richard Burdish @rjburdish // // 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 class Person: NSObject { let Name: NSString let Image: UIImage! let Age: NSNumber let NumberOfSharedFriends: NSNumber? let NumberOfSharedInterests: NSNumber let NumberOfPhotos: NSNumber override var description: String { return "Name: \(Name), \n Image: \(Image), \n Age: \(Age) \n NumberOfSharedFriends: \(NumberOfSharedFriends) \n NumberOfSharedInterests: \(NumberOfSharedInterests) \n NumberOfPhotos/: \(NumberOfPhotos)" } init(name: NSString?, image: UIImage?, age: NSNumber?, sharedFriends: NSNumber?, sharedInterest: NSNumber?, photos:NSNumber?) { self.Name = name ?? "" self.Image = image self.Age = age ?? 0 self.NumberOfSharedFriends = sharedFriends ?? 0 self.NumberOfSharedInterests = sharedInterest ?? 0 self.NumberOfPhotos = photos ?? 0 } }
173278716d4a4772159618ba0e2fd33c
41.081633
210
0.719068
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Components/Views/IconImageView/VideoIconStyle.swift
gpl-3.0
1
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireCommonComponents import WireSyncEngine enum VideoIconStyle: String, IconImageStyle { case video case screenshare case hidden var icon: StyleKitIcon? { switch self { case .hidden: return .none case .screenshare: return .screenshare case .video: return .camera } } var accessibilitySuffix: String { return rawValue } var accessibilityLabel: String { return rawValue } } extension VideoIconStyle { init(state: VideoState?) { guard let state = state else { self = .hidden return } switch state { case .screenSharing: self = .screenshare case .started, .paused, .badConnection: self = .video case .stopped: self = .hidden } } }
8ec4737891f5421b0919ad65564b4be7
24.507937
71
0.634101
false
false
false
false
delannoyk/BoumBoum
refs/heads/master
sources/BoumBoum/CVImageBuffer+RGBHSVAverage.swift
mit
1
// // CVImageBuffer+RGBHSVAverage.swift // BoumBoum // // Created by Kevin DELANNOY on 20/01/16. // Copyright © 2016 Kevin Delannoy. All rights reserved. // import UIKit import AVFoundation typealias RGB = (r: CGFloat, g: CGFloat, b: CGFloat) typealias HSV = (h: CGFloat, s: CGFloat, v: CGFloat) extension CVImageBuffer { func averageRGBHSVValueFromImageBuffer() -> (rgb: RGB, hsv: HSV) { CVPixelBufferLockBaseAddress(self, 0) let width = CVPixelBufferGetWidth(self) let height = CVPixelBufferGetHeight(self) var buffer = UnsafeMutablePointer<UInt8>(CVPixelBufferGetBaseAddress(self)) let bytesPerRow = CVPixelBufferGetBytesPerRow(self) //Let's compute average RGB value of the frame var r = CGFloat(0) var g = CGFloat(0) var b = CGFloat(0) for _ in 0..<height { for x in 0..<width { let rx = x * 4 b = b + CGFloat(buffer[rx]) g = g + CGFloat(buffer[rx + 1]) r = r + CGFloat(buffer[rx + 2]) } buffer += bytesPerRow } CVPixelBufferUnlockBaseAddress(self, 0) let bufferSize = width * height r = r / CGFloat(255 * bufferSize) g = g / CGFloat(255 * bufferSize) b = b / CGFloat(255 * bufferSize) let rgb = (r, g, b) let hsv = RGBToHSV(rgb) return (rgb, hsv) } private func RGBToHSV(value: RGB) -> HSV { let minimum = min(value.r, min(value.g, value.b)) let maximum = max(value.r, max(value.g, value.b)) let delta = maximum - minimum if maximum > CGFloat(FLT_EPSILON) { let h: CGFloat let v = maximum let s = delta / maximum if value.r == maximum { h = (value.g - value.b) / delta } else if value.g == maximum { h = 2 + (value.b - value.r) / delta } else { h = 4 + (value.r - value.g) / delta } if h < 0 { return (h + 360, 0, 0) } return (h, s, v) } return (0, 0, 0) } }
36f45e3e5efc18a54ee9ca5a4281496f
26.936709
83
0.517898
false
false
false
false
ringohub/swift-todo
refs/heads/master
ToDo/ToDoListViewController.swift
mit
1
import UIKit import CoreData class ToDoListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var todoEntities: [ToDo]! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoEntities.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "ToDoListItem")! cell.textLabel!.text = todoEntities[indexPath.row].item return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { todoEntities.remove(at: indexPath.row).mr_deleteEntity() NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait() tableView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // TODO: 文字列比較以外の方法は? // TODO: 少し改善したけど、まだString if segue.identifier == StoryboardSegue.Main.Edit.rawValue { let todoController = segue.destination as! ToDoItemViewController let task = todoEntities[tableView.indexPathForSelectedRow!.row] todoController.task = task } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) todoEntities = ToDo.mr_findAll() as? [ToDo] tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() todoEntities = ToDo.mr_findAll() as? [ToDo] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
162d6abbe918f1538f196f566e55f74c
30.125
125
0.726908
false
false
false
false
Tsiems/mobile-sensing-apps
refs/heads/master
06-Daily/code/Daily/IBAnimatable/SystemMoveInAnimator.swift
gpl-3.0
5
// // Created by Tom Baranes on 02/04/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class SystemMoveInAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private fileprivate var fromDirection: TransitionAnimationType.Direction public init(from direction: TransitionAnimationType.Direction, transitionDuration: Duration) { fromDirection = direction self.transitionDuration = transitionDuration switch fromDirection { case .right: self.transitionAnimationType = .systemMoveIn(from: .right) self.reverseAnimationType = .systemMoveIn(from: .left) self.interactiveGestureType = .pan(from: .left) case .top: self.transitionAnimationType = .systemMoveIn(from: .top) self.reverseAnimationType = .systemMoveIn(from: .bottom) self.interactiveGestureType = .pan(from: .bottom) case .bottom: self.transitionAnimationType = .systemMoveIn(from: .bottom) self.reverseAnimationType = .systemMoveIn(from: .top) self.interactiveGestureType = .pan(from: .top) default: self.transitionAnimationType = .systemMoveIn(from: .left) self.reverseAnimationType = .systemMoveIn(from: .right) self.interactiveGestureType = .pan(from: .right) } super.init() } } extension SystemMoveInAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { animateWithCATransition(transitionContext: transitionContext, type: TransitionAnimationType.SystemTransitionType.moveIn, subtype: fromDirection.caTransitionSubtype) } }
c153cf74fcbe4671a5d3140234fcfcf7
39.245283
168
0.766995
false
false
false
false
oNguyenVanHung/TODO-App
refs/heads/master
TO-DO-APP/TimelineViewController.swift
mit
1
// // TimelineViewController.swift // TO-DO-APP // // Created by ha.van.duc on 8/9/17. // Copyright © 2017 framgia. All rights reserved. // import UIKit class TimelineViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet weak var timelineCollectionView: UICollectionView! @IBOutlet weak var labelNumberDay: UILabel! @IBOutlet weak var labelNameDay: UILabel! @IBOutlet weak var labelFullDay: UILabel! var listTask = [[String : Any]]() override func viewDidLoad() { super.viewDidLoad() timelineCollectionView.dataSource = self timelineCollectionView.delegate = self let nidName = UINib(nibName: "TimelineCollectionViewCell", bundle: nil) timelineCollectionView.register(nidName, forCellWithReuseIdentifier: "Cell") let currentDay = Date() let query = "SELECT * FROM tasks WHERE tasks.selectedDate = '\(CommonUtility.formatToString(currentDay))'" listTask = SqliteManager.shared.getDataWithQuery(query: query) labelFullDay.text = CommonUtility.getMonthInYear(currentDay) labelNameDay.text = CommonUtility.getDayName(currentDay) labelNumberDay.text = CommonUtility.getNumberDay(currentDay) navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.setBackgroundImage(UIImage(named: "header_backgroud_create_task"), for: .default) navigationItem.title = "Timeline" navigationItem.setLeftBarButton(UIBarButtonItem(image: UIImage(named: "icon_menu")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), style: .done, target: self, action: #selector(openMenuSidebar(_:))), animated: true) var image = UIImage(named: "avatar.png") image = image?.withRenderingMode(.alwaysOriginal) navigationItem.setRightBarButton(UIBarButtonItem(image: image, style: .done, target: self, action: nil), animated: true) } func openMenuSidebar(_ sender: Any) { navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return listTask.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! TimelineCollectionViewCell if let fromTime = listTask[indexPath.row]["fromTime"] as? String, let toTime = listTask[indexPath.row]["toTime"] as? String, let title = listTask[indexPath.row]["title"] as? String, let description = listTask[indexPath.row]["description"] as? String, let status = listTask[indexPath.row]["status"] as? String { let timeTask = "\(fromTime) - \(toTime)" cell.update(timeTask: timeTask, title: title, description: description, status: status) } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 300, height: 100) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return CGFloat(0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return CGFloat(0) } }
9ccbda2c52cd41d4ed2aa3560b5f55cd
43.770115
232
0.717073
false
false
false
false
freak4pc/SMWebView
refs/heads/master
Pods/SMWebView/SMWebView.swift
mit
2
// // SMWebView // // Created by Shai Mishali on 8/19/15. // Copyright (c) 2015 Shai Mishali. All rights reserved. // import Foundation import UIKit open class SMWebView: UIWebView, UIWebViewDelegate{ //MARK: Typealiasing for Closure Types public typealias SMWebViewClosure = (_ webView :SMWebView) -> () public typealias SMWebViewFailClosure = (_ webView :SMWebView, _ error: Error?) -> () public typealias SMWebViewShouldLoadClosure = (_ webView :SMWebView, _ request: URLRequest, _ navigationType: UIWebViewNavigationType) -> (Bool) //MARK: Internal storage for Closures fileprivate var didStartLoadingHandler: SMWebViewClosure? = nil fileprivate var didFinishLoadingHandler: SMWebViewClosure? = nil fileprivate var didCompleteLoadingHandler: SMWebViewClosure? = nil fileprivate var didFailLoadingHandler: SMWebViewFailClosure? = nil fileprivate var shouldStartLoadingHandler: SMWebViewShouldLoadClosure? = nil //MARK: Initializers override init(frame: CGRect) { super.init(frame: frame) delegate = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self } // URL/String loaders with Chaining-support public class func loadURL(_ URL: URL) -> SMWebView { let wv = SMWebView() wv.loadRequest(URLRequest(url: URL)) return wv } public class func loadHTML(_ string: String, baseURL: URL) -> SMWebView { let wv = SMWebView() wv.loadHTMLString(string, baseURL: baseURL) return wv } @discardableResult public func loadURL(_ URL: URL) -> SMWebView { loadRequest(URLRequest(url: URL)) return self } @discardableResult public func loadHTML(_ string: String, baseURL: URL) -> SMWebView { loadHTMLString(string, baseURL: baseURL) return self } //MARK: Closure methods @discardableResult public func didStartLoading(handler: @escaping SMWebViewClosure) -> SMWebView { didStartLoadingHandler = handler return self } @discardableResult public func didFinishLoading(handler: @escaping SMWebViewClosure) -> SMWebView { didFinishLoadingHandler = handler return self } @discardableResult public func didFailLoading(handler: @escaping SMWebViewFailClosure) -> SMWebView { didFailLoadingHandler = handler return self } @discardableResult public func didCompleteLoading(handler: @escaping SMWebViewClosure) -> SMWebView { didCompleteLoadingHandler = handler return self } @discardableResult public func shouldStartLoading(handler: @escaping SMWebViewShouldLoadClosure) -> SMWebView { shouldStartLoadingHandler = handler return self } //MARK: UIWebView Delegate & Closure Handling public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { didFailLoadingHandler?(self, error) } public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let handler = shouldStartLoadingHandler, shouldStartLoadingHandler != nil else { return true } return handler(self, request, navigationType) } public func webViewDidStartLoad(_ webView: UIWebView) { didStartLoadingHandler?(self) } public func webViewDidFinishLoad(_ webView: UIWebView) { didFinishLoadingHandler?(self) if !webView.isLoading { didCompleteLoadingHandler?(self) } } }
98d421adf86a6b93b5f69e5990142d46
32.068376
176
0.646162
false
false
false
false
KrishMunot/swift
refs/heads/master
test/IDE/import_as_member_cf.swift
apache-2.0
1
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=ImportAsMember.C -always-argument-labels > %t.printed.C.txt // REQUIRES: objc_interop // RUN: FileCheck %s -check-prefix=PRINTC -strict-whitespace < %t.printed.C.txt // PRINTC: extension CCPowerSupply { // PRINTC-NEXT: /*not inherited*/ init(watts watts: Double) // PRINTC-NEXT: } // PRINTC: extension CCRefrigerator { // PRINTC-NEXT: /*not inherited*/ init(powerSupply power: CCPowerSupply) // PRINTC-NEXT: func open() // PRINTC-NEXT: var powerSupply: CCPowerSupply // PRINTC-NEXT: } // PRINTC: extension CCMutableRefrigerator { // PRINTC-NEXT: /*not inherited*/ init(powerSupply power: CCPowerSupply) // PRINTC-NEXT: } // RUN: %target-parse-verify-swift -I %S/Inputs/custom-modules import ImportAsMember.C let powerSupply = CCPowerSupply(watts: 500.0) let refrigerator = CCRefrigerator(powerSupply: powerSupply) refrigerator.open(); refrigerator.powerSupply = powerSupply
619fa2b8cba5226b5c4894b6a18ac041
37.25
223
0.722689
false
false
false
false
ainopara/Stage1st-Reader
refs/heads/master
Stage1st/Model/Forum.swift
bsd-3-clause
1
// // Forum.swift // Stage1st // // Created by Zheng Li on 09/02/2017. // Copyright © 2017 Renaissance. All rights reserved. // import Foundation public struct Forum: Codable { public let id: Int public let name: String public let threadCount: Int public let postCount: Int public let rules: String? } extension Forum { init?(rawForum: RawForum) { guard let id = Int(rawForum.id), let threadCount = Int(rawForum.threadCount), let postCount = Int(rawForum.postCount) else { return nil } self.id = id self.name = rawForum.name self.threadCount = threadCount self.postCount = postCount self.rules = rawForum.rules } }
f16fff785d5c8cfecd23d84a5535ecc5
20.8
56
0.600262
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGraphics/PDFDocument/PDFRenderer/PDFColorSpace.swift
mit
1
// // PDFColorSpace.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public enum PDFColorSpace: Hashable { case deviceGray case deviceRGB case deviceCMYK case colorSpace(AnyColorSpace) indirect case indexed(PDFColorSpace, [Data]) indirect case pattern(PDFColorSpace?) public init(_ colorSpace: AnyColorSpace) { self = .colorSpace(colorSpace) } } extension PDFColorSpace { var numberOfComponents: Int { switch self { case .deviceGray: return 1 case .deviceRGB: return 3 case .deviceCMYK: return 4 case .indexed: return 1 case let .colorSpace(colorSpace): return colorSpace.numberOfComponents case let .pattern(base): return base?.numberOfComponents ?? 0 } } var black: [Double]? { switch self { case .deviceGray: return [0] case .deviceRGB: return [0, 0, 0] case .deviceCMYK: return [0, 0, 0, 1] case .indexed: return nil case let .colorSpace(colorSpace): switch colorSpace.base { case is ColorSpace<GrayColorModel>: return [0] case is ColorSpace<RGBColorModel>: return [0, 0, 0] case is ColorSpace<CMYColorModel>: return [1, 1, 1] case is ColorSpace<CMYKColorModel>: return [0, 0, 0, 1] default: return Array(repeating: 0, count: colorSpace.numberOfComponents) } case let .pattern(base): return base?.black } } } extension PDFColorSpace { init?(_ object: PDFObject, _ colorSpaces: [PDFName: PDFColorSpace] = [:]) { switch object.name ?? object.array?.first?.name { case "DeviceGray", "G": self = .deviceGray case "DeviceRGB", "RGB": self = .deviceRGB case "DeviceCMYK", "CMYK": self = .deviceCMYK case "CalGray": guard let parameter = object.array?.dropFirst().first else { return nil } guard let white = parameter["WhitePoint"].vector else { return nil } let black = parameter["BlackPoint"].vector ?? Vector() let gamma = parameter["Gamma"].doubleValue ?? 1 let _white = XYZColorModel(x: white.x, y: white.y, z: white.z) let _black = XYZColorModel(x: black.x, y: black.y, z: black.z) self.init(.calibratedGray(white: _white, black: _black, gamma: gamma)) case "CalRGB": guard let parameter = object.array?.dropFirst().first else { return nil } guard let white = parameter["WhitePoint"].vector else { return nil } let black = parameter["BlackPoint"].vector ?? Vector() let gamma = parameter["Gamma"].vector ?? Vector(x: 1, y: 1, z: 1) let matrix = parameter["Matrix"].matrix ?? [1, 0, 0, 0, 1, 0, 0, 0, 1] let _white = XYZColorModel(x: white.x, y: white.y, z: white.z) let _black = XYZColorModel(x: black.x, y: black.y, z: black.z) let red = XYZColorModel(x: matrix[0], y: 0, z: 0) let green = XYZColorModel(x: 0, y: matrix[4], z: 0) let blue = XYZColorModel(x: 0, y: 0, z: matrix[8]) self.init(.calibratedRGB(white: _white, black: _black, red: red.point, green: green.point, blue: blue.point, gamma: (gamma.x, gamma.y, gamma.z))) case "Lab": guard let parameter = object.array?.dropFirst().first else { return nil } guard let white = parameter["WhitePoint"].vector else { return nil } let black = parameter["BlackPoint"].vector ?? Vector() let _white = XYZColorModel(x: white.x, y: white.y, z: white.z) let _black = XYZColorModel(x: black.x, y: black.y, z: black.z) self.init(.cieLab(white: _white, black: _black)) case "ICCBased": guard let parameter = object.array?.dropFirst().first else { return nil } guard let iccData = parameter.stream?.decode() else { return nil } guard let colorSpace = try? AnyColorSpace(iccData: iccData) else { return nil } self.init(colorSpace) case "Indexed", "I": guard let array = object.array else { return nil } guard array.count >= 4 else { return nil } guard let base = PDFColorSpace(array[1], colorSpaces) else { return nil } guard let hival = array[2].intValue else { return nil } guard let data = array[3].string?.data ?? array[3].stream?.decode() else { return nil } guard (hival + 1) * base.numberOfComponents <= data.count else { return nil } let table = data.chunks(ofCount: base.numberOfComponents).prefix(hival + 1) self = .indexed(base, Array(table)) case "Pattern": if let array = object.array, let base = PDFColorSpace(PDFObject(array.dropFirst()), colorSpaces) { self = .pattern(base) } else { self = .pattern(nil) } default: return nil } } } extension PDFColorSpace { static func deviceGrayFromRGB(_ colorSpace: ColorSpace<RGBColorModel>) -> ColorSpace<GrayColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: { GrayColorModel(white: 0.3 * $0.red + 0.59 * $0.green + 0.11 * $0.blue) }, convertToBase: RGBColorModel.init ) } static func deviceGrayFromCMYK(_ colorSpace: ColorSpace<CMYKColorModel>) -> ColorSpace<GrayColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: { GrayColorModel(white: 1 - min(1, 0.3 * $0.cyan + 0.59 * $0.magenta + 0.11 * $0.yellow + $0.black)) }, convertToBase: CMYKColorModel.init ) } static func deviceRGBFromGray(_ colorSpace: ColorSpace<GrayColorModel>) -> ColorSpace<RGBColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: RGBColorModel.init, convertToBase: { GrayColorModel(white: 0.3 * $0.red + 0.59 * $0.green + 0.11 * $0.blue) } ) } static func deviceRGBFromCMYK(_ colorSpace: ColorSpace<CMYKColorModel>) -> ColorSpace<RGBColorModel> { return ColorSpace.wrapped(base: colorSpace, convertFromBase: RGBColorModel.init, convertToBase: CMYKColorModel.init) } static func deviceCMYKFromGray(_ colorSpace: ColorSpace<GrayColorModel>) -> ColorSpace<CMYKColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: CMYKColorModel.init, convertToBase: { GrayColorModel(white: 1 - min(1, 0.3 * $0.cyan + 0.59 * $0.magenta + 0.11 * $0.yellow + $0.black)) } ) } static func deviceCMYKFromRGB(_ colorSpace: ColorSpace<RGBColorModel>) -> ColorSpace<CMYKColorModel> { return ColorSpace.wrapped(base: colorSpace, convertFromBase: CMYKColorModel.init, convertToBase: RGBColorModel.init) } } extension PDFColorSpace { func create_color(_ color: [PDFNumber], device colorSpace: AnyColorSpace?) -> AnyColor? { switch self { case .deviceGray: let _colorSpace: AnyColorSpace switch colorSpace?.base { case let colorSpace as ColorSpace<GrayColorModel>: _colorSpace = AnyColorSpace(colorSpace) case let colorSpace as ColorSpace<RGBColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceGrayFromRGB(colorSpace)) case let colorSpace as ColorSpace<CMYKColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceGrayFromCMYK(colorSpace)) default: _colorSpace = .genericGamma22Gray } return AnyColor(colorSpace: _colorSpace, components: color.map { $0.doubleValue ?? 0 }) case .deviceRGB: let _colorSpace: AnyColorSpace switch colorSpace?.base { case let colorSpace as ColorSpace<GrayColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceRGBFromGray(colorSpace)) case let colorSpace as ColorSpace<RGBColorModel>: _colorSpace = AnyColorSpace(colorSpace) case let colorSpace as ColorSpace<CMYKColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceRGBFromCMYK(colorSpace)) default: _colorSpace = .sRGB } return AnyColor(colorSpace: _colorSpace, components: color.map { $0.doubleValue ?? 0 }) case .deviceCMYK: let _colorSpace: AnyColorSpace switch colorSpace?.base { case let colorSpace as ColorSpace<GrayColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceCMYKFromGray(colorSpace)) case let colorSpace as ColorSpace<RGBColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceCMYKFromRGB(colorSpace)) case let colorSpace as ColorSpace<CMYKColorModel>: _colorSpace = AnyColorSpace(colorSpace) default: _colorSpace = AnyColorSpace(PDFColorSpace.deviceCMYKFromRGB(.sRGB)) } return AnyColor(colorSpace: _colorSpace, components: color.map { $0.doubleValue ?? 0 }) case let .indexed(base, table): guard let index = color[0].int64Value else { return nil } let _color = table[Int(index)].map { PDFNumber(Double($0) / 255) } return 0..<table.count ~= Int(index) ? base.create_color(_color, device: colorSpace) : nil case let .colorSpace(colorSpace): return AnyColor(colorSpace: colorSpace, components: color.map { $0.doubleValue ?? 0 }) case let .pattern(base): return base.flatMap { $0.create_color(color, device: colorSpace) } } } }
3535a10c9d3493d733a715460fe9af10
41.169118
157
0.595815
false
false
false
false
steelwheels/KiwiControls
refs/heads/master
Source/Controls/KCIconViewCore.swift
lgpl-2.1
1
/** * @file KCIconViewCore.swift * @brief Define KCIconViewCore class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ #if os(OSX) import Cocoa #else import UIKit #endif import CoconutData #if os(OSX) public class KCIconButtonCell: NSButtonCell { public override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) { self.isHighlighted = flag } } #endif open class KCIconViewCore : KCCoreView { static let SmallSizeValue : CGFloat = 32.0 static let RegularSizeValue : CGFloat = 64.0 static let LargeSizeValue : CGFloat = 129.0 public var buttonPressedCallback: (() -> Void)? = nil #if os(OSX) @IBOutlet weak var mImageButton: NSButton! @IBOutlet weak var mLabelView: NSTextField! #else @IBOutlet weak var mImageButton: UIButton! @IBOutlet weak var mLabelView: UILabel! #endif private var mSize: CNIconSize = .regular public func setup(frame frm: CGRect){ super.setup(isSingleView: false, coreView: mImageButton) KCView.setAutolayoutMode(views: [self, mImageButton]) self.title = "Untitled" #if os(OSX) mImageButton.imageScaling = .scaleProportionallyUpOrDown mImageButton.imagePosition = .imageOnly mImageButton.isTransparent = true mLabelView.isEditable = false mLabelView.isSelectable = false #else mImageButton.contentMode = .scaleAspectFit //mImageButton.imagePosition = .imageAbove #endif } #if os(OSX) @IBAction func buttonPressed(_ sender: Any) { if let callback = buttonPressedCallback { callback() } } #else @IBAction func buttonPressed(_ sender: Any) { if let callback = buttonPressedCallback { callback() } } #endif public var image: CNImage? { get { #if os(OSX) return mImageButton.image #else return mImageButton.image(for: .normal) #endif } set(newimg) { guard let img = newimg else { CNLog(logLevel: .error, message: "No image") return } #if os(OSX) mImageButton.image = img #else mImageButton.setImage(img, for: .normal) #endif mImageButton.invalidateIntrinsicContentSize() } } public var title: String { get { #if os(OSX) return mLabelView.stringValue #else if let str = mLabelView.text { return str } else { return "" } #endif } set(newstr){ #if os(OSX) mLabelView.stringValue = newstr #else mLabelView.text = newstr #endif mLabelView.invalidateIntrinsicContentSize() } } public var size: CNIconSize { get { return mSize } set(newsize) { mSize = newsize } } open override func setFrameSize(_ newsize: CGSize) { let _ = adjustSize(in: newsize) super.setFrameSize(newsize) } public override func invalidateIntrinsicContentSize() { super.invalidateIntrinsicContentSize() // The size of image is NOT invalidated } #if os(OSX) open override var fittingSize: CGSize { get { return requiredSize() } } #else open override func sizeThatFits(_ size: CGSize) -> CGSize { return adjustSize(in: size) } #endif open override var intrinsicContentSize: CGSize { get { return requiredSize() } } private func requiredSize() -> CGSize { let btnsize = mImageButton.intrinsicContentSize let labsize = mLabelView.intrinsicContentSize return CNUnionSize(sizeA: btnsize, sizeB: labsize, doVertical: true, spacing: CNPreference.shared.windowPreference.spacing) } private func adjustSize(in sz: CGSize) -> CGSize { if sz.width <= KCIconViewCore.SmallSizeValue || sz.height <= KCIconViewCore.SmallSizeValue { return adjustSize(sizeType: .small) } else if sz.width <= KCIconViewCore.RegularSizeValue || sz.height <= KCIconViewCore.RegularSizeValue { return adjustSize(sizeType: .regular) } else { return adjustSize(sizeType: .large) } } private func adjustSize(sizeType styp: CNIconSize) -> CGSize { let targsize = sizeToValue(size: styp) let spacing = CNPreference.shared.windowPreference.spacing /* Get label size */ let labsize: CGSize mLabelView.sizeToFit() labsize = mLabelView.frame.size #if os(OSX) mLabelView.setFrameSize(labsize) #else mLabelView.setFrame(size: labsize) #endif /* Adjust image size */ let imgsize: CGSize if targsize.height > (labsize.height + spacing) { if let img = imageInButton() { let reqsize = CGSize(width: targsize.width, height: targsize.height - (labsize.height + spacing)) imgsize = adjustImageSize(image: img, targetSize: reqsize) } else { CNLog(logLevel: .error, message: "No image in icon", atFunction: #function, inFile: #file) imgsize = CGSize.zero } } else { CNLog(logLevel: .error, message: "No space to put image in icon", atFunction: #function, inFile: #file) imgsize = CGSize.zero } return CNUnionSize(sizeA: imgsize, sizeB: labsize, doVertical: true, spacing: 0.0) } private func adjustImageSize(image img: CNImage, targetSize target: CGSize) -> CGSize { let newsize = img.size.resizeWithKeepingAscpect(inSize: target) if let newimg = img.resized(to: newsize) { setImageToButton(image: newimg) #if os(OSX) mImageButton.setFrameSize(newsize) #else mImageButton.setFrame(size: newsize) #endif return newsize } else { CNLog(logLevel: .error, message: "Failed to resize image", atFunction: #function, inFile: #file) return img.size } } private func sizeToValue(size sz: CNIconSize) -> CGSize { let val: CGFloat switch sz { case .small: val = KCIconViewCore.SmallSizeValue case .regular: val = KCIconViewCore.RegularSizeValue case .large: val = KCIconViewCore.LargeSizeValue @unknown default: CNLog(logLevel: .error, message: "Unknown icon size", atFunction: #function, inFile: #file) val = KCIconViewCore.RegularSizeValue } return CGSize(width: val, height: val) } private func imageInButton() -> CNImage? { #if os(OSX) return mImageButton.image #else return mImageButton.image(for: .normal) #endif } private func setImageToButton(image img: CNImage) { #if os(OSX) mImageButton.image = img #else mImageButton.setImage(img, for: .normal) #endif } public override func setExpandabilities(priorities prival: KCViewBase.ExpansionPriorities) { super.setExpandabilities(priorities: prival) mImageButton.setExpansionPriorities(priorities: prival) let labpri = KCViewBase.ExpansionPriorities(holizontalHugging: prival.holizontalHugging, holizontalCompression: prival.holizontalCompression, verticalHugging: .low, verticalCompression: .low) mLabelView.setExpansionPriorities(priorities: labpri) } }
d2886e1250cddb7b69bc9e202b787e59
25.495968
125
0.713286
false
false
false
false
leo-lp/LPIM
refs/heads/master
LPIM/Classes/Login/LPRegisterViewController.swift
mit
1
// // LPRegisterViewController.swift // LPIM // // Created by lipeng on 2017/6/16. // Copyright © 2017年 lipeng. All rights reserved. // import UIKit import UIColor_Hex_Swift protocol LPRegisterViewControllerDelegate: NSObjectProtocol { func registDidComplete(account: String?, password: String?) -> Void } class LPRegisterViewController: LPBaseViewController { @IBOutlet weak var accountTextField: UITextField! @IBOutlet weak var nicknameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! weak var delegate: LPRegisterViewControllerDelegate? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNav() } override func viewDidLoad() { super.viewDidLoad() resetTextField(accountTextField) resetTextField(nicknameTextField) resetTextField(passwordTextField) } func setupNav() { let registerBtn = UIButton(type: .custom) registerBtn.setTitle("完成", for: .normal) registerBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15) registerBtn.setTitleColor(UIColor(hex6: 0x2294ff), for: .normal) registerBtn.setBackgroundImage(#imageLiteral(resourceName: "login_btn_done_normal"), for: .normal) registerBtn.setBackgroundImage(#imageLiteral(resourceName: "login_btn_done_pressed"), for: .highlighted) registerBtn.addTarget(self, action: #selector(doneButtonClicked), for: .touchUpInside) registerBtn.sizeToFit() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: registerBtn) navigationItem.rightBarButtonItem?.isEnabled = false let image = #imageLiteral(resourceName: "icon_back_normal") navigationController?.navigationBar.backIndicatorImage = image navigationController?.navigationBar.backIndicatorTransitionMaskImage = image let backItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) navigationController?.navigationBar.tintColor = UIColor.white navigationItem.backBarButtonItem = backItem } @IBAction func textFieldEditingChanged(_ sender: UITextField) { var enabled = false if let account = accountTextField.text, let nickname = nicknameTextField.text, let pwd = passwordTextField.text { enabled = account.characters.count > 0 && nickname.characters.count > 0 && pwd.characters.count > 0 } navigationItem.rightBarButtonItem?.isEnabled = enabled } @IBAction func existedButtonClicked(_ sender: UIButton) { navigationController?.popViewController(animated: true) } func doneButtonClicked(_ sender: UIButton?) { UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil) if !check() { return } let data = LPRegisterData(account: accountTextField.text!, token: passwordTextField.text!.tokenByPassword(), nickname: nicknameTextField.text!) LPHUD.showHUD(at: nil, text: nil) LPHTTPSession.shared.registerUser(with: data) { (errorMsg) in LPHUD.hide(true) if let errorMsg = errorMsg { self.delegate?.registDidComplete(account: nil, password: nil) LPHUD.showError(at: nil, text: "注册失败(\(errorMsg))") return } LPHUD.showSuccess(at: nil, text: "注册成功") self.delegate?.registDidComplete(account: data.account, password: self.passwordTextField.text) self.navigationController?.popViewController(animated: true) } } } extension LPRegisterViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "\n" { doneButtonClicked(nil) return false } return true } } // MARK: - // MARK: - Private extension LPRegisterViewController { fileprivate func resetTextField(_ textField: UITextField) { textField.tintColor = UIColor.white let dict = [NSForegroundColorAttributeName: UIColor(hex6: 0xffffff, alpha: 0.6)] let mas = NSAttributedString(string: textField.placeholder!, attributes: dict) textField.attributedPlaceholder = mas if let clearButton = textField.value(forKey: "_clearButton") as? UIButton { clearButton.setImage(#imageLiteral(resourceName: "login_icon_clear"), for: .normal) } } fileprivate func check() -> Bool { var checkAccount: Bool { guard let account = accountTextField.text else { return false } return account.characters.count > 0 && account.characters.count <= 20 } var checkPassword: Bool { guard let pwd = passwordTextField.text else { return false } return pwd.characters.count >= 6 && pwd.characters.count <= 20 } var checkNickname: Bool { guard let nickname = nicknameTextField.text else { return false } return nickname.characters.count > 0 && nickname.characters.count <= 10 } if !checkAccount { LPHUD.showError(at: view, text: "账号长度有误") return false } if !checkPassword { LPHUD.showError(at: view, text: "密码长度有误") return false } if !checkNickname { LPHUD.showError(at: view, text: "昵称长度有误") return false } return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } }
ca8dec97c23d53e634e5a6ef06cabf1e
37.381579
129
0.645183
false
false
false
false
withcopper/CopperKit
refs/heads/master
CopperKit/C29UserDevice.swift
mit
1
// // C29UserDevice // Copper // // Created by Doug Williams on 12/1/15. // Copyright (c) 2014 Doug Williams. All rights reserved. // import Foundation public class C29UserDevice: NSObject, NSCoding { public enum Key: String { case DeviceId = "device_id" case Timestamp = "created" case LastActive = "last_active" case Name = "name" case Type = "type" case Label = "label" case DeviceToken = "device_token" case PushEnabled = "push_enabled" case BundleId = "bundle_id" } public enum DeviceType: String { case Mobile = "mobile" case Desktop = "desktop" case Browser = "browser" case Chrome = "chrome" case Safari = "safari" case Other = "other" } public let id: String! public let timestamp: NSDate! public let name: String! public let type: DeviceType! public let lastActive: NSDate! public let label: String! public let pushEnabled: Bool! public let deviceToken: String? public let bundleId: String? init(id: String, timestamp: NSDate, name: String, lastActive: NSDate, type: DeviceType, label: String, pushEnabled: Bool = false, deviceToken: String! = nil, bundleId: String! = nil) { self.id = id self.timestamp = timestamp self.name = name self.lastActive = lastActive self.type = type self.label = label self.pushEnabled = pushEnabled self.deviceToken = deviceToken self.bundleId = bundleId } // MARK: - NSCoding convenience required public init?(coder decoder: NSCoder) { let id = decoder.decodeObjectForKey(Key.DeviceId.rawValue) as! String let timestamp = decoder.decodeObjectForKey(Key.Timestamp.rawValue) as! NSDate let name = decoder.decodeObjectForKey(Key.Name.rawValue) as! String let lastActive = decoder.decodeObjectForKey(Key.LastActive.rawValue) as? NSDate ?? NSDate() var type = DeviceType.Other if let typeRawValue = decoder.decodeObjectForKey(C29UserDevice.Key.Type.rawValue) as? String, let _type = DeviceType(rawValue: typeRawValue) { type = _type } let label = decoder.decodeObjectForKey(Key.Label.rawValue) as! String let pushEnabled = decoder.decodeObjectForKey(Key.PushEnabled.rawValue) as? Bool ?? false let deviceToken = decoder.decodeObjectForKey(Key.DeviceToken.rawValue) as? String let bundleId = decoder.decodeObjectForKey(Key.BundleId.rawValue) as? String self.init(id: id, timestamp: timestamp, name: name, lastActive: lastActive, type: type, label: label, pushEnabled: pushEnabled, deviceToken: deviceToken, bundleId: bundleId) } public func encodeWithCoder(coder: NSCoder) { coder.encodeObject(id, forKey: Key.DeviceId.rawValue) coder.encodeObject(timestamp, forKey: Key.Timestamp.rawValue) coder.encodeObject(name, forKey: Key.Name.rawValue) coder.encodeObject(lastActive, forKey: Key.LastActive.rawValue) coder.encodeObject(type?.rawValue, forKey: C29UserDevice.Key.Type.rawValue) coder.encodeObject(label, forKey: Key.Label.rawValue) coder.encodeObject(pushEnabled, forKey: Key.PushEnabled.rawValue) coder.encodeObject(deviceToken, forKey: Key.DeviceToken.rawValue) coder.encodeObject(bundleId, forKey: Key.BundleId.rawValue) } public class func fromDictionary(dataDict: NSDictionary) -> C29UserDevice? { if let id = dataDict[Key.DeviceId.rawValue] as? String, let createdTimestamp = dataDict[Key.Timestamp.rawValue] as? Double, let name = dataDict[Key.Name.rawValue] as? String, let label = dataDict[Key.Label.rawValue] as? String, let lastActiveTimestamp = dataDict[Key.LastActive.rawValue] as? Double, let typeRawValue = dataDict[C29UserDevice.Key.Type.rawValue] as? String { let timestamp = NSDate(timeIntervalSince1970: createdTimestamp) let lastActive = NSDate(timeIntervalSince1970: lastActiveTimestamp) let type = DeviceType(rawValue: typeRawValue) ?? .Other let pushEnabled = dataDict[Key.PushEnabled.rawValue] as? Bool ?? false let deviceToken = dataDict[Key.DeviceToken.rawValue] as? String let bundleId = dataDict[Key.BundleId.rawValue] as? String return C29UserDevice(id: id, timestamp: timestamp, name: name, lastActive: lastActive, type: type, label: label, pushEnabled: pushEnabled, deviceToken: deviceToken, bundleId: bundleId) } else { // we are receiving Application json of an unexpected format C29LogWithRemote(.Error, error: Error.InvalidFormat.nserror, infoDict: dataDict as! [String : AnyObject]) return C29UserDevice?() } } // expected dataDict format is {{deviceid,name,timestamp},{deviceid,...}}" public class func getDevicesFromDictionary(dataDict: [NSDictionary]) -> [C29UserDevice]? { var devices = [C29UserDevice]() for deviceDict in dataDict { if let device = C29UserDevice.fromDictionary(deviceDict) { devices.append(device) } else { C29LogWithRemote(.Error, error: Error.InvalidFormat.nserror, infoDict: deviceDict as! [String : AnyObject]) return nil } } return devices } override public func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? C29UserDevice { return rhs.id == self.id } return false } } extension C29UserDevice { enum Error: Int { case InvalidFormat = 1 case DeleteUnsuccessful = 2 var reason: String { switch self { case DeleteUnsuccessful: return "C29UserDevice delete failed unexpectedly" case InvalidFormat: return "C29UserDevice fromDictionary failed because some required data was omitted or in the wrong format" } } var nserror: NSError { return NSError(domain: self.domain, code: self.rawValue, userInfo: [NSLocalizedFailureReasonErrorKey: self.reason]) } var domain: String { return "\(NSBundle.mainBundle().bundleIdentifier!).C29UserDevice" } } }
b211224bc0ee9670a6f404e9617fdb03
41.084416
196
0.645525
false
false
false
false
LongPF/FaceTube
refs/heads/master
FaceTube/Home/FTHomeViewController.swift
mit
1
// // HomeViewController.swift // FaceTube // // Created by 龙鹏飞 on 2017/3/1. // Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import AMScrollingNavbar import MJRefresh class FTHomeViewController: FTViewController, ScrollingNavigationControllerDelegate { var tableView: FTTableView! var dataSource: FTHomeLiveDataSource! var palyUrl = "" var player: IJKFFMoviePlayerController! = nil; var toolbar: UIToolbar! var selectedCell: FTHomeLiveTableViewCell? //MARK: ************************ life cycle ************************ override func viewDidLoad() { super.viewDidLoad() title = "FaceTube" view.backgroundColor = UIColor.backgroundColor() //dataSource self.dataSource = FTHomeLiveDataSource() self.dataSource.fetchDataCompleted = { (dataSource: FTDataSource) in self.tableView.reloadData() self.tableView.mj_header.endRefreshing() } //tableView self.tableView = FTTableView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_SIZE.width, height: SCREEN_SIZE.height-40), style: .plain) self.tableView.register(FTHomeLiveTableViewCell.classForCoder(), forCellReuseIdentifier: "cell") self.tableView.backgroundColor = UIColor.white self.tableView.dataSource = self self.tableView.delegate = self self.tableView.separatorStyle = .none self.tableView.backgroundColor = UIColor.backgroundColor() self.view.addSubview(self.tableView) //refresh let header: MJRefreshNormalHeader = MJRefreshNormalHeader() header.setRefreshingTarget(self.dataSource, refreshingAction: #selector(FTDataSource.fetchNewestData)) self.tableView.mj_header = header //获取数据 self.tableView.mj_header.beginRefreshing() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (navigationController?.delegate == nil){ navigationController?.delegate = self } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = UIColor.navigationBarColor() if let navigationController = self.navigationController as? ScrollingNavigationController { navigationController.followScrollView(tableView, delay: 0.0) navigationController.scrollingNavbarDelegate = self } self.tableView.mj_header.isHidden = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.tableView.mj_header.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: 转场动画 override func captureView() -> UIView { return (selectedCell?.thumbImageView)! } override func needBlur() -> Bool { return true } override func needHiddenTabBar() -> Bool { return true } } extension FTHomeViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count: NSInteger! = (self.dataSource.dataArray?.count)! return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: FTHomeLiveTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FTHomeLiveTableViewCell let model: FTHomeLiveModel = self.dataSource.dataArray?.object(at: indexPath.row) as! FTHomeLiveModel cell.updateHomeLiveCell(model: model) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return SCREEN_SIZE.width+50 } } extension FTHomeViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedCell = tableView.cellForRow(at: indexPath) as! FTHomeLiveTableViewCell? let model: FTHomeLiveModel = dataSource.dataArray[indexPath.row] as! FTHomeLiveModel let detailCon: FTLiveDetailViewController = FTLiveDetailViewController() detailCon.homeLiveModel = model detailCon.hidesBottomBarWhenPushed = true navigationController?.pushViewController(detailCon, animated: true) } } extension FTHomeViewController { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.push { return FTMagicMoveTransion() } else { return nil } } }
ecca58342528b26e6077ea17ebb6c750
32.414474
246
0.677299
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Swifter/32Singleton.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Foundation #if swift(>=3.0) #else // Swift之前的版本 class MyManager1 { class var shared : MyManager1 { struct Static { static var onceToken : dispatch_once_t = 0 static var staticInstance : MyManager1? = nil } dispatch_once(&Static.onceToken) { Static.staticInstance = MyManager1() } return Static.staticInstance! } } MyManager1.shared #endif class MyManager2 { private static let sharedInstance = MyManager2() class var sharedManager : MyManager2 { return sharedInstance } } MyManager2.sharedManager class MyManager3 { class var sharedManager : MyManager3 { return sharedInstance } } private let sharedInstance = MyManager3() MyManager3.sharedManager // 现在用这种 class MyManager { static let sharedManager = MyManager() private init() {} } MyManager.sharedManager
e78f3d1ed978d76deb4a29d0ab04c627
17.25
52
0.669125
false
false
false
false
Daltron/Spartan
refs/heads/master
Example/Pods/AlamoRecord/AlamoRecord/Classes/AlamoRecordObject.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2017 Tunespeak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Alamofire import AlamofireObjectMapper import ObjectMapper open class AlamoRecordObject<U: URLProtocol, E: AlamoRecordError>: NSObject, Mappable { /// Key to encode/decode the id variable private let idKey: String = "id" /// The RequestManager that is tied to all instances of this class open class var requestManager: RequestManager<U, E> { fatalError("requestManager must be overriden in your AlamoRecordObject subclass") } /// The RequestManager that is tied to this instance open var requestManager: RequestManager<U, E> { return type(of: self).requestManager } /// The id of this instance. This can be a String or an Int. open var id: Any! /// The root of all instances of this class. This is used when making URL's that relate to a component of this class. // Example: '/comment/id' --> '/\(Comment.root)/id' open class var root: String { fatalError("root must be overriden in your AlamoRecordObject subclass") } /// The root of this instance open var root: String { return type(of: self).root } /// The plural root of all instances of this class. This is used when making URL's that relate to a component of this class. // Example: '/comments/id' --> '/\(Comment.pluralRoot)/id' open class var pluralRoot: String { return "\(root)s" } /// The pluralRoot of this instance open var pluralRoot: String { return type(of: self).pluralRoot } /// The key path of all instances of this class. This is used when mapping instances of this class from JSON. /* Example: { comment: { // json encpasulated here } } If this is nil, then the expected JSON woud look like: { // json encpasulated here } */ open class var keyPath: String? { return nil } /// The keyPath of this instance open var keyPath: String? { return type(of: self).keyPath } /// The key path of all instances of this class. This is used when mapping instances of this class from JSON. See keyPath for example open class var pluralKeyPath: String? { guard let keyPath = keyPath else { return nil } return "\(keyPath)s" } /// The pluralKeyPath of this instance open var pluralKeyPath: String? { return type(of: self).pluralKeyPath } public override init() { super.init() } public required init?(map: Map) { super.init() mapping(map: map) } open func mapping(map: Map) { id <- map["id"] } /** Returns an array of all objects of this instance if the server supports it - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func all<T: AlamoRecordObject>(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (([T]) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.findArray(T.urlForAll(), parameters: parameters, keyPath: T.pluralKeyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Creates an object of this instance - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func create<T: AlamoRecordObject>(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.createObject(parameters: parameters, keyPath: keyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Creates an object of this instance - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func create(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.createObject(url: urlForCreate(), parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Finds an object of this instance based on the given id - parameter id: The id of the object to find - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func find<T: AlamoRecordObject>(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.findObject(id: id, parameters: parameters, keyPath: keyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates the object - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open func update<T: AlamoRecordObject>(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return T.update(id: id, parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates an object of this instance based with the given id - parameter id: The id of the object to update - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func update<T: AlamoRecordObject>(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.updateObject(id: id, parameters: parameters, keyPath: keyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates an object of this instance based with the given id - parameter id: The id of the object to update - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func update(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.updateObject(url: urlForUpdate(id), parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates an object of this instance based with the given id - parameter id: The id of the object to update - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open func update(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return type(of: self).update(id: id, parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Destroys the object - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open func destroy(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return type(of: self).destroy(id: id, parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Finds an object of this instance based on the given id - parameter id: The id of the object to destroy - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func destroy(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.destroyObject(url: urlForDestroy(id), parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** The URL to use when making a create request for all objects of this instance */ open class func urlForCreate() -> U { return U(url: "\(pluralRoot)") } public func urlForCreate() -> U { return type(of: self).urlForCreate() } /** The URL to use when making a find request for all objects of this instance - parameter id: The id of the object to find */ open class func urlForFind(_ id: Any) -> U { return U(url: "\(pluralRoot)/\(id)") } public func urlForFind() -> U { return type(of: self).urlForFind(id) } /** The URL to use when making an update request for all objects of this instance - parameter id: The id of the object to update */ open class func urlForUpdate(_ id: Any) -> U { return U(url: "\(pluralRoot)/\(id)") } public func urlForUpdate() -> U { return type(of: self).urlForUpdate(id) } /** The URL to use when making a destroy request for all objects this instance - parameter id: The id of the object to destroy */ open class func urlForDestroy(_ id: Any) -> U { return U(url: "\(pluralRoot)/\(id)") } public func urlForDestroy() -> U { return type(of: self).urlForDestroy(id) } /** The URL to use when making an all request for all objects of this instance */ open class func urlForAll() -> U { return U(url: "\(pluralRoot)") } public func urlForAll() -> U { return type(of: self).urlForAll() } }
4cf0c25ec2b2ff36df247fa05605d92f
41.128954
147
0.542651
false
false
false
false
namanhams/Swift-UIImageView-AFNetworking
refs/heads/master
UIImageView+AFNetworking.swift
apache-2.0
1
// // UIImageView+AFNetworking.swift // // Created by Pham Hoang Le on 23/2/15. // Copyright (c) 2015 Pham Hoang Le. All rights reserved. // import UIKit @objc public protocol AFImageCacheProtocol:class{ func cachedImageForRequest(request:NSURLRequest) -> UIImage? func cacheImage(image:UIImage, forRequest request:NSURLRequest); } extension UIImageView { private struct AssociatedKeys { static var SharedImageCache = "SharedImageCache" static var RequestImageOperation = "RequestImageOperation" static var URLRequestImage = "UrlRequestImage" } public class func setSharedImageCache(cache:AFImageCacheProtocol?) { objc_setAssociatedObject(self, &AssociatedKeys.SharedImageCache, cache, .OBJC_ASSOCIATION_RETAIN) } public class func sharedImageCache() -> AFImageCacheProtocol { struct Static { static var token : dispatch_once_t = 0 static var defaultImageCache:AFImageCache? } dispatch_once(&Static.token, { () -> Void in Static.defaultImageCache = AFImageCache() NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidReceiveMemoryWarningNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) -> Void in Static.defaultImageCache!.removeAllObjects() } }) return objc_getAssociatedObject(self, &AssociatedKeys.SharedImageCache) as? AFImageCacheProtocol ?? Static.defaultImageCache! } private class func af_sharedImageRequestOperationQueue() -> NSOperationQueue { struct Static { static var token:dispatch_once_t = 0 static var queue:NSOperationQueue? } dispatch_once(&Static.token, { () -> Void in Static.queue = NSOperationQueue() Static.queue!.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount }) return Static.queue! } private var af_requestImageOperation:(operation:NSOperation?, request: NSURLRequest?) { get { let operation:NSOperation? = objc_getAssociatedObject(self, &AssociatedKeys.RequestImageOperation) as? NSOperation let request:NSURLRequest? = objc_getAssociatedObject(self, &AssociatedKeys.URLRequestImage) as? NSURLRequest return (operation, request) } set { objc_setAssociatedObject(self, &AssociatedKeys.RequestImageOperation, newValue.operation, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.URLRequestImage, newValue.request, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func setImageWithUrl(url:NSURL, placeHolderImage:UIImage? = nil) { let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.addValue("image/*", forHTTPHeaderField: "Accept") self.setImageWithUrlRequest(request, placeHolderImage: placeHolderImage, success: nil, failure: nil) } public func setImageWithUrlRequest(request:NSURLRequest, placeHolderImage:UIImage? = nil, success:((request:NSURLRequest?, response:NSURLResponse?, image:UIImage, fromCache:Bool) -> Void)?, failure:((request:NSURLRequest?, response:NSURLResponse?, error:NSError) -> Void)?) { self.cancelImageRequestOperation() if let cachedImage = UIImageView.sharedImageCache().cachedImageForRequest(request) { if success != nil { success!(request: nil, response:nil, image: cachedImage, fromCache:true) } else { self.image = cachedImage } return } if placeHolderImage != nil { self.image = placeHolderImage } self.af_requestImageOperation = (NSBlockOperation(block: { () -> Void in var response:NSURLResponse? do { let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) dispatch_async(dispatch_get_main_queue(), { () -> Void in if request.URL!.isEqual(self.af_requestImageOperation.request?.URL) { let image:UIImage? = UIImage(data: data) if image != nil { if success != nil { success!(request: request, response: response, image: image!, fromCache:false) } else { self.image = image! } UIImageView.sharedImageCache().cacheImage(image!, forRequest: request) } self.af_requestImageOperation = (nil, nil) } }) } catch { if failure != nil { failure!(request: request, response:response, error: error as NSError) } } }), request: request) UIImageView.af_sharedImageRequestOperationQueue().addOperation(self.af_requestImageOperation.operation!) } private func cancelImageRequestOperation() { self.af_requestImageOperation.operation?.cancel() self.af_requestImageOperation = (nil, nil) } } func AFImageCacheKeyFromURLRequest(request:NSURLRequest) -> String { return request.URL!.absoluteString! } class AFImageCache: NSCache, AFImageCacheProtocol { func cachedImageForRequest(request: NSURLRequest) -> UIImage? { switch request.cachePolicy { case NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData: return nil default: break } return self.objectForKey(AFImageCacheKeyFromURLRequest(request)) as? UIImage } func cacheImage(image: UIImage, forRequest request: NSURLRequest) { self.setObject(image, forKey: AFImageCacheKeyFromURLRequest(request)) } }
b2875610155a4ee39103942d270c1b08
39.986755
197
0.625626
false
false
false
false
chuckwired/ios-scroll-test
refs/heads/master
scrollTest/ViewController.swift
gpl-2.0
1
// // ViewController.swift // scrollTest // // Created by Charles Rice on 04/11/2014. // Copyright (c) 2014 Cake Solutions. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { @IBOutlet var scrollView: UIScrollView! var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do cool stuff //Part 1 let image2 = UIImage(named: "photo2.png") let image = UIImage(named: "photo1.png") imageView = UIImageView(image: image) var theImageSize = CGSizeZero if let image = image { theImageSize = image.size } imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:theImageSize) scrollView.addSubview(imageView) //Part2 scrollView.contentSize = theImageSize //Part 3 var doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "scrollViewDoubleTapped:") doubleTapRecognizer.numberOfTapsRequired = 2 doubleTapRecognizer.numberOfTouchesRequired = 1 scrollView.addGestureRecognizer(doubleTapRecognizer) //Part 4 let scrollViewFrame = scrollView.frame let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height let minScale = min(scaleWidth, scaleHeight) scrollView.minimumZoomScale = minScale //Part 5 scrollView.maximumZoomScale = 1.0 scrollView.zoomScale = minScale //Part 6 centerScrollViewContents() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Scroll delegates func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(scrollView: UIScrollView) { centerScrollViewContents() } //Double tap to zoom func scrollViewDoubleTapped(recognizer: UITapGestureRecognizer){ //Part 1 let pointInView = recognizer.locationInView(imageView) //Part 2 var newZoomScale = scrollView.zoomScale * 1.5 newZoomScale = min(newZoomScale, scrollView.maximumZoomScale) //Part 3 let scrollViewSize = scrollView.bounds.size let w = scrollViewSize.width / newZoomScale let h = scrollViewSize.height / newZoomScale let x = pointInView.x - (w / 2.0) let y = pointInView.y - (h / 2.0) let rectToZoomTo = CGRect(x: x, y: y, width: w, height: h) //Part 4 scrollView.zoomToRect(rectToZoomTo, animated: true) } //Fixes UIScrollView autodisplay in top-left func centerScrollViewContents(){ let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if(contentsFrame.size.width < boundsSize.width){ contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } }
976278514a3df00720c0d0f0d763a7b9
31.145455
105
0.626414
false
false
false
false
fabiomassimo/eidolon
refs/heads/master
Kiosk/Bid Fulfillment/ConfirmYourBidEnterYourEmailViewController.swift
mit
1
import UIKit import ReactiveCocoa import Swift_RAC_Macros public class ConfirmYourBidEnterYourEmailViewController: UIViewController { @IBOutlet public var emailTextField: UITextField! @IBOutlet public var confirmButton: UIButton! @IBOutlet public var bidDetailsPreviewView: BidDetailsPreviewView! class public func instantiateFromStoryboard(storyboard: UIStoryboard) -> ConfirmYourBidEnterYourEmailViewController { return storyboard.viewControllerWithID(.ConfirmYourBidEnterEmail) as! ConfirmYourBidEnterYourEmailViewController } override public func viewDidLoad() { super.viewDidLoad() let emailTextSignal = emailTextField.rac_textSignal() let inputIsEmail = emailTextSignal.map(stringIsEmailAddress) confirmButton.rac_command = RACCommand(enabled: inputIsEmail) { [weak self] _ in if (self == nil) { return RACSignal.empty() } let endpoint: ArtsyAPI = ArtsyAPI.FindExistingEmailRegistration(email: self!.emailTextField.text) return XAppRequest(endpoint).filterStatusCode(200).doNext({ (__) -> Void in self?.performSegue(.ExistingArtsyUserFound) return }).doError { (error) -> Void in self?.performSegue(.EmailNotFoundonArtsy) return } } let unbindSignal = confirmButton.rac_command.executing.ignore(false) let nav = self.fulfillmentNav() bidDetailsPreviewView.bidDetails = nav.bidDetails RAC(nav.bidDetails.newUser, "email") <~ emailTextSignal.takeUntil(unbindSignal) emailTextField.returnKeySignal().subscribeNext { [weak self] (_) -> Void in self?.confirmButton.rac_command.execute(nil) return } } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.emailTextField.becomeFirstResponder() } } private extension ConfirmYourBidEnterYourEmailViewController { @IBAction func dev_emailFound(sender: AnyObject) { performSegue(.ExistingArtsyUserFound) } @IBAction func dev_emailNotFound(sender: AnyObject) { performSegue(.EmailNotFoundonArtsy) } }
ad9302833fc5cf37c01ae29a14466136
32.25
121
0.684956
false
false
false
false
CodaFi/swift
refs/heads/main
stdlib/public/core/ArrayBufferProtocol.swift
apache-2.0
11
//===--- ArrayBufferProtocol.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// The underlying buffer for an ArrayType conforms to /// `_ArrayBufferProtocol`. This buffer does not provide value semantics. @usableFromInline internal protocol _ArrayBufferProtocol : MutableCollection, RandomAccessCollection where Indices == Range<Int> { /// Create an empty buffer. init() /// Adopt the entire buffer, presenting it at the provided `startIndex`. init(_buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int) init(copying buffer: Self) /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @discardableResult __consuming func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self` /// buffer store `minimumCapacity` elements, returns that buffer. /// Otherwise, returns `nil`. /// /// - Note: The result's firstElementAddress may not match ours, if we are a /// _SliceBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? /// Returns `true` iff this buffer is backed by a uniquely-referenced mutable /// _ContiguousArrayBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func isMutableAndUniquelyReferenced() -> Bool /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? /// Replace the given `subRange` with the first `newCount` elements of /// the given collection. /// /// - Precondition: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer`. mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newCount: Int, elementsOf newValues: __owned C ) where C: Collection, C.Element == Element /// Returns a `_SliceBuffer` containing the elements in `bounds`. subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R /// The number of elements the buffer stores. override var count: Int { get set } /// The number of elements the buffer can store without reallocation. var capacity: Int { get } /// An object that keeps the elements stored in this buffer alive. var owner: AnyObject { get } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. var firstElementAddress: UnsafeMutablePointer<Element> { get } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { get } /// Returns a base address to which you can add an index `i` to get the /// address of the corresponding element at `i`. var subscriptBaseAddress: UnsafeMutablePointer<Element> { get } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. var identity: UnsafeRawPointer { get } } extension _ArrayBufferProtocol where Indices == Range<Int>{ @inlinable internal var subscriptBaseAddress: UnsafeMutablePointer<Element> { return firstElementAddress } // Make sure the compiler does not inline _copyBuffer to reduce code size. @inline(never) @inlinable // This code should be specializable such that copying an array is // fast and does not end up in an unspecialized entry point. internal init(copying buffer: Self) { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: buffer.count, minimumCapacity: buffer.count) buffer._copyContents( subRange: buffer.indices, initializing: newBuffer.firstElementAddress) self = Self( _buffer: newBuffer, shiftedToStartIndex: buffer.startIndex) } @inlinable internal mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newCount: Int, elementsOf newValues: __owned C ) where C: Collection, C.Element == Element { _internalInvariant(startIndex == 0, "_SliceBuffer should override this function.") let oldCount = self.count let eraseCount = subrange.count let growth = newCount - eraseCount // This check will prevent storing a 0 count to the empty array singleton. if growth != 0 { self.count = oldCount + growth } let elements = self.subscriptBaseAddress let oldTailIndex = subrange.upperBound let oldTailStart = elements + oldTailIndex let newTailIndex = oldTailIndex + growth let newTailStart = oldTailStart + growth let tailCount = oldCount - subrange.upperBound if growth > 0 { // Slide the tail part of the buffer forwards, in reverse order // so as not to self-clobber. newTailStart.moveInitialize(from: oldTailStart, count: tailCount) // Assign over the original subrange var i = newValues.startIndex for j in subrange { elements[j] = newValues[i] newValues.formIndex(after: &i) } // Initialize the hole left by sliding the tail forward for j in oldTailIndex..<newTailIndex { (elements + j).initialize(to: newValues[i]) newValues.formIndex(after: &i) } _expectEnd(of: newValues, is: i) } else { // We're not growing the buffer // Assign all the new elements into the start of the subrange var i = subrange.lowerBound var j = newValues.startIndex for _ in 0..<newCount { elements[i] = newValues[j] i += 1 newValues.formIndex(after: &j) } _expectEnd(of: newValues, is: j) // If the size didn't change, we're done. if growth == 0 { return } // Move the tail backward to cover the shrinkage. let shrinkage = -growth if tailCount > shrinkage { // If the tail length exceeds the shrinkage // Assign over the rest of the replaced range with the first // part of the tail. newTailStart.moveAssign(from: oldTailStart, count: shrinkage) // Slide the rest of the tail back oldTailStart.moveInitialize( from: oldTailStart + shrinkage, count: tailCount - shrinkage) } else { // Tail fits within erased elements // Assign over the start of the replaced range with the tail newTailStart.moveAssign(from: oldTailStart, count: tailCount) // Destroy elements remaining after the tail in subrange (newTailStart + tailCount).deinitialize( count: shrinkage - tailCount) } } } }
92b36d560f18f31636c33035fc966206
36.479638
86
0.680792
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Views/Sliders/SliderExample/SliderExample/ViewController.swift
mit
1
// // ViewController.swift // SliderExample // // Created by Domenico Solazzo on 05/05/15. // LICENSE MIT // import UIKit class ViewController: UIViewController { // Slider var slider:UISlider? override func viewDidLoad() { super.viewDidLoad() slider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 23)) slider!.center = self.view.center // Max value slider?.maximumValue = 100 // Min value slider?.minimumValue = 0 // Current Value slider?.value = slider!.maximumValue / 2.0 // Set thumb images slider?.setThumbImage(UIImage(named: "ThumbNormal"), for: UIControlState()) slider?.setThumbImage(UIImage(named: "ThumbHighlighted"), for: .highlighted) self.view.addSubview(slider!) } }
d690ba22dc42b70019413fde0f2103be
22.081081
84
0.59719
false
false
false
false
hivinau/LivingElectro
refs/heads/master
iOS/LivingElectro/LivingElectro/TitleCell.swift
mit
1
// // TitleCell.swift // LivingElectro // // Created by Aude Sautier on 14/05/2017. // Copyright © 2017 Hivinau GRAFFE. All rights reserved. // import UIKit @objc(TitleCell) public class TitleCell: UICollectionViewCell { @IBOutlet weak var titleLabel: PaddingLabel! public override var isSelected: Bool { didSet { titleLabel.textColor = isSelected ? .white : .gray } } public var titleValue: String? { didSet { titleLabel.text = titleValue titleLabel.sizeToFit() } } public override func layoutSubviews() { super.layoutSubviews() titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byTruncatingTail titleLabel.textAlignment = .center titleLabel.textColor = isSelected ? .white : .gray if let font = UIFont(name: "Helvetica", size: 14.0) { titleLabel.font = font } } public override func prepareForReuse() { super.prepareForReuse() titleLabel.text?.removeAll() } }
beb0ba14367095c260de4b3e1b20419c
22.08
62
0.571924
false
false
false
false
huonw/swift
refs/heads/master
tools/SwiftSyntax/RawSyntax.swift
apache-2.0
1
//===------------------ RawSyntax.swift - Raw Syntax nodes ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation /// Represents the raw tree structure underlying the syntax tree. These nodes /// have no notion of identity and only provide structure to the tree. They /// are immutable and can be freely shared between syntax nodes. indirect enum RawSyntax: Codable { /// A tree node with a kind, an array of children, and a source presence. case node(SyntaxKind, [RawSyntax?], SourcePresence) /// A token with a token kind, leading trivia, trailing trivia, and a source /// presence. case token(TokenKind, Trivia, Trivia, SourcePresence) /// The syntax kind of this raw syntax. var kind: SyntaxKind { switch self { case .node(let kind, _, _): return kind case .token(_, _, _, _): return .token } } var tokenKind: TokenKind? { switch self { case .node(_, _, _): return nil case .token(let kind, _, _, _): return kind } } /// The layout of the children of this Raw syntax node. var layout: [RawSyntax?] { switch self { case .node(_, let layout, _): return layout case .token(_, _, _, _): return [] } } /// The source presence of this node. var presence: SourcePresence { switch self { case .node(_, _, let presence): return presence case .token(_, _, _, let presence): return presence } } /// Whether this node is present in the original source. var isPresent: Bool { return presence == .present } /// Whether this node is missing from the original source. var isMissing: Bool { return presence == .missing } /// Keys for serializing RawSyntax nodes. enum CodingKeys: String, CodingKey { // Keys for the `node` case case kind, layout, presence // Keys for the `token` case case tokenKind, leadingTrivia, trailingTrivia } /// Creates a RawSyntax from the provided Foundation Decoder. init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let presence = try container.decode(SourcePresence.self, forKey: .presence) if let kind = try container.decodeIfPresent(SyntaxKind.self, forKey: .kind) { let layout = try container.decode([RawSyntax?].self, forKey: .layout) self = .node(kind, layout, presence) } else { let kind = try container.decode(TokenKind.self, forKey: .tokenKind) let leadingTrivia = try container.decode(Trivia.self, forKey: .leadingTrivia) let trailingTrivia = try container.decode(Trivia.self, forKey: .trailingTrivia) self = .token(kind, leadingTrivia, trailingTrivia, presence) } } /// Encodes the RawSyntax to the provided Foundation Encoder. func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .node(kind, layout, presence): try container.encode(kind, forKey: .kind) try container.encode(layout, forKey: .layout) try container.encode(presence, forKey: .presence) case let .token(kind, leadingTrivia, trailingTrivia, presence): try container.encode(kind, forKey: .tokenKind) try container.encode(leadingTrivia, forKey: .leadingTrivia) try container.encode(trailingTrivia, forKey: .trailingTrivia) try container.encode(presence, forKey: .presence) } } /// Creates a RawSyntax node that's marked missing in the source with the /// provided kind and layout. /// - Parameters: /// - kind: The syntax kind underlying this node. /// - layout: The children of this node. /// - Returns: A new RawSyntax `.node` with the provided kind and layout, with /// `.missing` source presence. static func missing(_ kind: SyntaxKind) -> RawSyntax { return .node(kind, [], .missing) } /// Creates a RawSyntax token that's marked missing in the source with the /// provided kind and no leading/trailing trivia. /// - Parameter kind: The token kind. /// - Returns: A new RawSyntax `.token` with the provided kind, no /// leading/trailing trivia, and `.missing` source presence. static func missingToken(_ kind: TokenKind) -> RawSyntax { return .token(kind, [], [], .missing) } /// Returns a new RawSyntax node with the provided layout instead of the /// existing layout. /// - Note: This function does nothing with `.token` nodes --- the same token /// is returned. /// - Parameter newLayout: The children of the new node you're creating. func replacingLayout(_ newLayout: [RawSyntax?]) -> RawSyntax { switch self { case let .node(kind, _, presence): return .node(kind, newLayout, presence) case .token(_, _, _, _): return self } } /// Creates a new RawSyntax with the provided child appended to its layout. /// - Parameter child: The child to append /// - Note: This function does nothing with `.token` nodes --- the same token /// is returned. /// - Return: A new RawSyntax node with the provided child at the end. func appending(_ child: RawSyntax) -> RawSyntax { var newLayout = layout newLayout.append(child) return replacingLayout(newLayout) } /// Returns the child at the provided cursor in the layout. /// - Parameter index: The index of the child you're accessing. /// - Returns: The child at the provided index. subscript<CursorType: RawRepresentable>(_ index: CursorType) -> RawSyntax? where CursorType.RawValue == Int { return layout[index.rawValue] } /// Replaces the child at the provided index in this node with the provided /// child. /// - Parameters: /// - index: The index of the child to replace. /// - newChild: The new child that should occupy that index in the node. func replacingChild(_ index: Int, with newChild: RawSyntax) -> RawSyntax { precondition(index < layout.count, "Cursor \(index) reached past layout") var newLayout = layout newLayout[index] = newChild return replacingLayout(newLayout) } } extension RawSyntax: TextOutputStreamable { /// Prints the RawSyntax node, and all of its children, to the provided /// stream. This implementation must be source-accurate. /// - Parameter stream: The stream on which to output this node. func write<Target>(to target: inout Target) where Target: TextOutputStream { switch self { case .node(_, let layout, _): for child in layout { guard let child = child else { continue } child.write(to: &target) } case let .token(kind, leadingTrivia, trailingTrivia, presence): guard case .present = presence else { return } for piece in leadingTrivia { piece.write(to: &target) } target.write(kind.text) for piece in trailingTrivia { piece.write(to: &target) } } } } extension RawSyntax { func accumulateAbsolutePosition(_ pos: AbsolutePosition) { switch self { case .node(_, let layout, _): for child in layout { guard let child = child else { continue } child.accumulateAbsolutePosition(pos) } case let .token(kind, leadingTrivia, trailingTrivia, presence): guard case .present = presence else { return } for piece in leadingTrivia { piece.accumulateAbsolutePosition(pos) } pos.add(text: kind.text) for piece in trailingTrivia { piece.accumulateAbsolutePosition(pos) } } } var leadingTrivia: Trivia? { switch self { case .node(_, let layout, _): for child in layout { guard let child = child else { continue } guard let result = child.leadingTrivia else { continue } return result } return nil case let .token(_, leadingTrivia, _, presence): guard case .present = presence else { return nil } return leadingTrivia } } var trailingTrivia: Trivia? { switch self { case .node(_, let layout, _): for child in layout.reversed() { guard let child = child else { continue } guard let result = child.trailingTrivia else { continue } return result } return nil case let .token(_, _, trailingTrivia, presence): guard case .present = presence else { return nil } return trailingTrivia } } func accumulateLeadingTrivia(_ pos: AbsolutePosition) { guard let trivia = leadingTrivia else { return } for piece in trivia { piece.accumulateAbsolutePosition(pos) } } func accumulateTrailingTrivia(_ pos: AbsolutePosition) { guard let trivia = trailingTrivia else { return } for piece in trivia { piece.accumulateAbsolutePosition(pos) } } }
22e7aca0aa76f89cd7a3bc56ddd688ab
34.142308
85
0.653825
false
false
false
false
svd-zp/SDPagingViewController
refs/heads/master
SDPagingViewController/SDPagingViewController/ModelController.swift
mit
1
// // ModelController.swift // SDPagingViewController // // Created by SvD on 09.12.15. // Copyright © 2015 SvD. All rights reserved. // import UIKit /* A controller object that manages a simple model -- a collection of month names. The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:. It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application. There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand. */ class ModelController: NSObject, UIPageViewControllerDataSource { var pageData: [String] = [] override init() { super.init() // Create the data model. let dateFormatter = NSDateFormatter() pageData = dateFormatter.monthSymbols } func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? { // Return the data view controller for the given index. if (self.pageData.count == 0) || (index >= self.pageData.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as! DataViewController dataViewController.dataObject = self.pageData[index] return dataViewController } func indexOfViewController(viewController: DataViewController) -> Int { // Return the index of the given data view controller. // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. return pageData.indexOf(viewController.dataObject) ?? NSNotFound } // MARK: - Page View Controller Data Source func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if (index == 0) || (index == NSNotFound) { // return nil index = self.pageData.count } if index > 0 { index-- } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if index == NSNotFound { index = 0 } index++ if index == self.pageData.count { index = 0 } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } }
cc35cd9051cc61e732a01981978bc6be
38.9
225
0.7099
false
false
false
false
herrkaefer/AccelerateWatch
refs/heads/master
AccelerateWatch/Classes/DSBuffer.swift
mit
1
/// DSBuffer /// /// Created by Yang Liu (gloolar [at] gmail [dot] com) on 16/6/20. /// Copyright © 2016年 Yang Liu. All rights reserved. import Foundation /// Fixed-length buffer for windowed signal processing public class DSBuffer { private var buffer: OpaquePointer private var size: Int private var fftIsSupported: Bool private var fftData: [dsbuffer_complex]? private var fftIsUpdated: Bool? // MARK: Initializer and deinitializer /// Initializer /// /// - parameter size: Buffer length. If you set fftIsSupperted to be true, the size should be **even** number /// - parameter fftIsSupported: Whether FFT will be performed on the buffer /// - returns: DSBuffer object /// /// *Tips*: /// /// - If you do not need to perform FFT on the buffer, set fftIsSupperted to be false could save 50% memory. /// - If you need to perform FFT, set buffer size to power of 2 could accelerate more. init(_ size: Int, fftIsSupported: Bool = true) { if (fftIsSupported && size % 2 == 1) { print(String(format: "WARNING: size must be even for FFT. Reset size to: %d.", size+1)) self.size = size + 1 } else { self.size = size } self.buffer = dsbuffer_new(size, fftIsSupported) self.fftIsSupported = fftIsSupported if (fftIsSupported) { self.fftData = [dsbuffer_complex](repeating: dsbuffer_complex(real: 0.0, imag: 0.0), count: self.size/2+1) self.fftIsUpdated = false } } /// :nodoc: deinitializer deinit { dsbuffer_free_unsafe(self.buffer) } // MARK: Regular operations /// Push new value to buffer (and the foremost will be dropped) /// /// - parameter value: New value to be added func push(_ value: Float) { dsbuffer_push(self.buffer, value) if (self.fftIsSupported) { self.fftIsUpdated = false } } /// Get data by index func dataAt(_ index: Int) -> Float { return dsbuffer_at(self.buffer, index) } /// Get Buffer size var bufferSize: Int { return self.size } /// Dump buffer as array var data: [Float] { var dumped = [Float](repeating: 0.0, count: self.size) dsbuffer_dump(self.buffer, &dumped) return dumped } /// Reset buffer to be zero filled func clear() { dsbuffer_clear(self.buffer) if (self.fftIsSupported) { self.fftIsUpdated = false } } /// Print buffer func printBuffer(_ dataFormat: String) { print("DSBuffer size: \(self.size)") for idx in 0..<self.size { print(String(format: dataFormat, dsbuffer_at(self.buffer, idx)), terminator: " ") } print("\n") } // MARK: Vector-like operations /// Add value to each buffer data func add(_ withValue: Float) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_add(self.buffer, withValue, &result) return result } /// Multiply each buffer data with value func multiply(_ withValue: Float) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_multiply(self.buffer, withValue, &result) return result } /// Modulus by value of each buffer data func mod(_ withValue: Float) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_mod(self.buffer, withValue, &result) return result } /// Remove mean value var centralized: [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_remove_mean(self.buffer, &result) return result } /// Normalize vector to have unit length /// /// - parameter centralized: Should remove mean? func normalizedToUnitLength(_ centralized: Bool) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_normalize_to_unit_length(self.buffer, centralized, &result) return result } /// Normalize vector to have unit variance /// /// - parameter centralized: Should remove mean? func normalizedToUnitVariance(_ centralized: Bool) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_normalize_to_unit_variance(self.buffer, centralized, &result) return result } /// Perform dot production with array func dotProduct(_ with: [Float]) -> Float { assert(self.size == with.count) return dsbuffer_dot_product(self.buffer, with) } // MARK: Time-domain features /// Mean value var mean: Float { return dsbuffer_mean(self.buffer) } /// Mean value var sum: Float { return dsbuffer_sum(self.buffer) } /// Vector length var length: Float { return dsbuffer_length(self.buffer) } /// Square of length var energy: Float { return dsbuffer_energy(self.buffer) } /// Max value var max: Float { return dsbuffer_max(self.buffer) } /// Min value var min: Float { return dsbuffer_min(self.buffer) } /// Variance var variance: Float { return dsbuffer_variance(self.buffer) } /// Standard deviation var std: Float { return dsbuffer_std(self.buffer) } // MARK: FFT & frequency-domain features // Perform FFT if it is not updated private func updateFFT() { assert (self.fftIsSupported) if (!self.fftIsUpdated!) { _ = fft() } } /// Perform FFT /// /// **Note for FFT related methods**: /// /// - Set fftIsSupported to true when creating the buffer. /// - Buffer size should be even. If you pass odd size when creating the buffer, it is automatically increased by 1. /// - Only results in nfft/2+1 complex frequency bins from DC to Nyquist are returned. func fft() -> (real: [Float], imaginary: [Float]) { assert (self.fftIsSupported, "FFT is not supported on this buffer") dsbuffer_fftr(self.buffer, &self.fftData!) self.fftIsUpdated = true return (self.fftData!.map{$0.real}, self.fftData!.map{$0.imag}) } /// FFT sample frequencies /// /// - returns: array of size nfft/2+1 func fftFrequencies(_ fs: Float) -> [Float] { assert (self.fftIsSupported) var fftFreq = [Float](repeating: 0.0, count: self.size/2+1) dsbuffer_fft_freq(self.buffer, fs, &fftFreq) return fftFreq } /// FFT magnitudes, i.e. abs(fft()) /// /// - returns: array of size nfft/2+1 func fftMagnitudes() -> [Float] { updateFFT() return self.fftData!.map{sqrt($0.real*$0.real + $0.imag*$0.imag)} } /// Square of FFT magnitudes, i.e. (abs(fft()))^2 /// /// - returns: array of size nfft/2+1 func squaredPowerSpectrum() -> [Float] { updateFFT() var sps = self.fftData!.map{($0.real*$0.real + $0.imag*$0.imag) * 2} sps[0] /= 2.0 // DC return sps } /// Mean-squared power spectrum, i.e. (abs(fft()))^2 / N /// /// - returns: array of size nfft/2+1 func meanSquaredPowerSpectrum() -> [Float] { updateFFT() var pxx = self.fftData!.map{($0.real*$0.real + $0.imag*$0.imag) * 2 / Float(self.size)} pxx[0] /= 2.0 // DC return pxx } /// Power spectral density (PSD), i.e. (abs(fft()))^2 / (fs*N) /// /// - returns: array of size nfft/2+1 func powerSpectralDensity(_ fs: Float) -> [Float] { updateFFT() var psd = self.fftData!.map{($0.real*$0.real + $0.imag*$0.imag) * 2.0 / (fs * Float(self.size))} psd[0] /= 2.0 // DC return psd } /// Average power over specific frequency band, i.e. mean(abs(fft(from...to))^2) func averageBandPower(_ fromFreq: Float = 0, toFreq: Float, fs: Float) -> Float { assert (fromFreq >= 0) assert (toFreq <= fs/2.0) assert (fromFreq <= toFreq) updateFFT() // Compute index range corresponding to given frequency band // f = idx*df = idx*fs/N ==> idx = N*f/fs let fromIdx = Int(floor(fromFreq * Float(self.size) / fs)) let toIdx = Int(ceil(toFreq * Float(self.size) / fs)) let bandPower = self.fftData![fromIdx...toIdx].map{$0.real*$0.real+$0.imag*$0.imag} // Averaging return bandPower.reduce(0.0, +) / Float(toIdx - fromIdx + 1) } // MARK: FIR filter // Setup FIR filter func setupFIRFilter(_ FIRTaps: [Float]) { assert (self.size >= FIRTaps.count) dsbuffer_setup_fir(self.buffer, FIRTaps, FIRTaps.count) } /// Get latest FIR output func latestFIROutput() -> Float { return dsbuffer_latest_fir_output(self.buffer) } /// FIR filtered buffer func FIRFiltered() -> [Float] { var output = [Float](repeating: 0.0, count: self.size) dsbuffer_fir_filter(self.buffer, &output) return output } /// :nodoc: Self test public class func test() { print("\nDSBuffer test: ==============\n") let size = 16 let buf = DSBuffer(size, fftIsSupported: true) buf.printBuffer("%.2f") let signalData: [Float] = [1.0, 4, 2, 5, 6, 7, -1, -8] for value in signalData { buf.push(value) // print(buf.signals) } buf.printBuffer("%.2f") let startTime = CFAbsoluteTimeGetCurrent() let fft = buf.fft() let deltaTime = CFAbsoluteTimeGetCurrent() - startTime print("FFT time: \(deltaTime)") print(fft) let fftSM = buf.squaredPowerSpectrum() print(fftSM) buf.clear() for _ in 0 ..< 10000 { let a = Float(arc4random_uniform(100)) buf.push(a) let signals = buf.data // print(a) // print(signals) assert(signals[size-1] == a) } let norm = buf.normalizedToUnitLength(true) let coeff = vDotProduct(norm, v2: norm) print(String(format: "coeff: %.2f\n", coeff)) print("\nDSBuffer test OK.\n\n") } }
ef0bd274aef951ca9803dfa39261340a
27.070681
120
0.55367
false
false
false
false
almazrafi/Metatron
refs/heads/master
Sources/ID3v2/FrameStuffs/ID3v2SyncedLyrics.swift
mit
1
// // ID3v2SyncedLyrics.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 public class ID3v2SyncedLyrics: ID3v2FrameStuff { // MARK: Nested Types public enum ContentType: UInt8 { case other case lyrics case transcription case movement case events case chord case trivia case webpageURLs case imageURLs } public struct Syllable: Equatable { // MARK: Instance Properties public var text: String = "" public var timeStamp: UInt32 = 0 // MARK: public var isEmpty: Bool { return self.text.isEmpty } // MARK: Initializers init(_ text: String, timeStamp: UInt32) { self.text = text self.timeStamp = timeStamp } init() { } } // MARK: Instance Properties public var textEncoding: ID3v2TextEncoding = ID3v2TextEncoding.utf8 public var language: ID3v2Language = ID3v2Language.und public var timeStampFormat: ID3v2TimeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds public var contentType: ContentType = ContentType.other public var description: String = "" public var syllables: [Syllable] = [] // MARK: public var isEmpty: Bool { return self.syllables.isEmpty } // MARK: Initializers public init() { } public required init(fromData data: [UInt8], version: ID3v2Version) { guard data.count > 11 else { return } guard let textEncoding = ID3v2TextEncoding(rawValue: data[0]) else { return } guard let language = ID3v2Language(code: [UInt8](data[1..<4])) else { return } guard let timeStampFormat = ID3v2TimeStampFormat(rawValue: data[4]) else { return } guard let contentType = ContentType(rawValue: data[5]) else { return } guard let description = textEncoding.decode([UInt8](data.suffix(from: 6))) else { return } var offset = 6 + description.endIndex var syllables: [Syllable] = [] if textEncoding == ID3v2TextEncoding.utf16 { guard offset <= data.count - 8 else { return } let utf16TextEncoding: ID3v2TextEncoding if (data[offset] == 255) && (data[offset + 1] == 254) { utf16TextEncoding = ID3v2TextEncoding.utf16LE } else if (data[offset] == 254) && (data[offset + 1] == 255) { utf16TextEncoding = ID3v2TextEncoding.utf16BE } else { utf16TextEncoding = textEncoding } repeat { guard let text = utf16TextEncoding.decode([UInt8](data.suffix(from: offset))) else { return } offset += text.endIndex guard offset < data.count - 3 else { return } var timeStamp = UInt32(data[offset + 3]) timeStamp |= UInt32(data[offset + 2]) << 8 timeStamp |= UInt32(data[offset + 1]) << 16 timeStamp |= UInt32(data[offset + 0]) << 24 syllables.append(Syllable(text.text, timeStamp: timeStamp)) offset += 4 } while offset < data.count } else { guard offset <= data.count - 5 else { return } repeat { guard let text = textEncoding.decode([UInt8](data.suffix(from: offset))) else { return } offset += text.endIndex guard offset < data.count - 3 else { return } var timeStamp = UInt32(data[offset + 3]) timeStamp |= UInt32(data[offset + 2]) << 8 timeStamp |= UInt32(data[offset + 1]) << 16 timeStamp |= UInt32(data[offset + 0]) << 24 syllables.append(Syllable(text.text, timeStamp: timeStamp)) offset += 4 } while offset < data.count } self.textEncoding = textEncoding self.language = language self.timeStampFormat = timeStampFormat self.contentType = contentType self.description = description.text self.syllables = syllables } // MARK: Instance Methods public func toData(version: ID3v2Version) -> [UInt8]? { guard !self.isEmpty else { return nil } let textEncoding: ID3v2TextEncoding switch version { case ID3v2Version.v2, ID3v2Version.v3: if self.textEncoding == ID3v2TextEncoding.latin1 { textEncoding = ID3v2TextEncoding.latin1 } else { textEncoding = ID3v2TextEncoding.utf16 } case ID3v2Version.v4: textEncoding = self.textEncoding } var data = [textEncoding.rawValue] data.append(contentsOf: self.language.code) data.append(self.timeStampFormat.rawValue) data.append(self.contentType.rawValue) data.append(contentsOf: textEncoding.encode(self.description, termination: true)) var timeStamp: UInt32 = 0 for syllable in self.syllables { if timeStamp < syllable.timeStamp { timeStamp = syllable.timeStamp } data.append(contentsOf: textEncoding.encode(syllable.text, termination: true)) data.append(contentsOf: [UInt8((timeStamp >> 24) & 255), UInt8((timeStamp >> 16) & 255), UInt8((timeStamp >> 8) & 255), UInt8((timeStamp) & 255)]) } return data } public func toData() -> (data: [UInt8], version: ID3v2Version)? { guard let data = self.toData(version: ID3v2Version.v4) else { return nil } return (data: data, version: ID3v2Version.v4) } } public class ID3v2SyncedLyricsFormat: ID3v2FrameStuffSubclassFormat { // MARK: Type Properties public static let regular = ID3v2SyncedLyricsFormat() // MARK: Instance Methods public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2SyncedLyrics { return ID3v2SyncedLyrics(fromData: data, version: version) } public func createStuffSubclass(fromOther other: ID3v2SyncedLyrics) -> ID3v2SyncedLyrics { let stuff = ID3v2SyncedLyrics() stuff.textEncoding = other.textEncoding stuff.language = other.language stuff.timeStampFormat = other.timeStampFormat stuff.contentType = other.contentType stuff.description = other.description stuff.syllables = other.syllables return stuff } public func createStuffSubclass() -> ID3v2SyncedLyrics { return ID3v2SyncedLyrics() } } public func == (left: ID3v2SyncedLyrics.Syllable, right: ID3v2SyncedLyrics.Syllable) -> Bool { if left.text != right.text { return false } if left.timeStamp != right.timeStamp { return false } return true } public func != (left: ID3v2SyncedLyrics.Syllable, right: ID3v2SyncedLyrics.Syllable) -> Bool { return !(left == right) }
9ad3264362471c4c57454737809672a2
27.306931
105
0.587968
false
false
false
false
cocoaswifty/V2EX
refs/heads/master
V2EX/UIView.swift
apache-2.0
1
// // UIView.swift // EngineerMaster // // Created by tracetw on 2016/2/17. // Copyright © 2016年 mycena. All rights reserved. // import UIKit extension UIView { func squareTurnCircle() { // self.layer.cornerRadius = self.frame.width/2 layer.cornerRadius = frame.width/2 } class func loadNib<T: UIView>(_ viewType: T.Type) -> T { let className = String.className(viewType) return Bundle(for: viewType).loadNibNamed(className, owner: nil, options: nil)!.first as! T } class func loadNib() -> Self { return loadNib(self) } // @IBInspectable var cornerRadius: CGFloat { // get { // return layer.cornerRadius // } // set { // layer.cornerRadius = newValue // layer.masksToBounds = newValue > 0 // } // } }
aa6286ceb90c6eba5d9a54aecc700fca
22.722222
99
0.576112
false
false
false
false
JGiola/swift
refs/heads/main
test/decl/init/failable.swift
apache-2.0
5
// Run in compatibility modes that disable and enable optional flattening // in 'try?' to verify that initializer delegation diagnostics that are related // to 'try?' are stable. // RUN: %target-typecheck-verify-swift -swift-version 4 // RUN: %target-typecheck-verify-swift -swift-version 5 // REQUIRES: objc_interop import Foundation struct S0 { init!(int: Int) { } init! (uint: UInt) { } init !(float: Float) { } init?(string: String) { } init ?(double: Double) { } init ? (char: Character) { } } struct S1<T> { init?(value: T) { } } class DuplicateDecls { init!() { } // expected-note{{'init()' previously declared here}} init?() { } // expected-error{{invalid redeclaration of 'init()'}} init!(string: String) { } // expected-note{{'init(string:)' previously declared here}} init(string: String) { } // expected-error{{invalid redeclaration of 'init(string:)'}} init(double: Double) { } // expected-note{{'init(double:)' previously declared here}} init?(double: Double) { } // expected-error{{invalid redeclaration of 'init(double:)'}} } // Construct via a failable initializer. func testConstruction(_ i: Int, s: String) { let s0Opt = S0(string: s) assert(s0Opt != nil) var _: S0 = s0Opt // expected-error{{value of optional type 'S0?' must be unwrapped}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let s0IUO = S0(int: i) assert(s0IUO != nil) _ = s0IUO } // ---------------------------------------------------------------------------- // Superclass initializer chaining // ---------------------------------------------------------------------------- class Super { init?(fail: String) { } init!(failIUO: String) { } init() { } // expected-note 2{{non-failable initializer 'init()' overridden here}} } class Sub : Super { override init() { super.init() } // okay, never fails init(nonfail: Int) { // expected-note{{propagate the failure with 'init?'}}{{7-7=?}} super.init(fail: "boom") // expected-error{{a non-failable initializer cannot chain to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } convenience init(forceNonfail: Int) { self.init(nonfail: forceNonfail)! // expected-error{{cannot force unwrap value of non-optional type}} {{37-38=}} } init(nonfail2: Int) { // okay, traps on nil super.init(failIUO: "boom") } init(nonfail3: Int) { super.init(fail: "boom")! } override init?(fail: String) { super.init(fail: fail) // okay, propagates ? } init?(fail2: String) { // okay, propagates ! as ? super.init(failIUO: fail2) } init?(fail3: String) { // okay, can introduce its own failure super.init() } override init!(failIUO: String) { super.init(failIUO: failIUO) // okay, propagates ! } init!(failIUO2: String) { // okay, propagates ? as ! super.init(fail: failIUO2) } init!(failIUO3: String) { // okay, can introduce its own failure super.init() } } // ---------------------------------------------------------------------------- // Initializer delegation // ---------------------------------------------------------------------------- extension Super { convenience init(convenienceNonFailNonFail: String) { // okay, non-failable self.init() } convenience init(convenienceNonFailFail: String) { // expected-note{{propagate the failure with 'init?'}}{{19-19=?}} self.init(fail: convenienceNonFailFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{44-44=!}} } convenience init(convenienceNonFailFailForce: String) { self.init(fail: convenienceNonFailFailForce)! } convenience init(convenienceNonFailFailIUO: String) { // okay, trap on failure self.init(failIUO: convenienceNonFailFailIUO) } convenience init?(convenienceFailNonFail: String) { self.init() // okay, can introduce its own failure } convenience init?(convenienceFailFail: String) { self.init(fail: convenienceFailFail) // okay, propagates ? } convenience init?(convenienceFailFailIUO: String) { // okay, propagates ! as ? self.init(failIUO: convenienceFailFailIUO) } convenience init!(convenienceFailIUONonFail: String) { self.init() // okay, can introduce its own failure } convenience init!(convenienceFailIUOFail: String) { self.init(fail: convenienceFailIUOFail) // okay, propagates ? as ! } convenience init!(convenienceFailIUOFailIUO: String) { // okay, propagates ! self.init(failIUO: convenienceFailIUOFailIUO) } } struct SomeStruct { init?(failable: Void) {} init!(failableIUO: Void) {} init(throws: Void) throws {} init?(failableAndThrows: Void) throws {} init!(failableIUOAndThrows: Void) throws {} init(delegationOk1: Void) { self.init(failable: ())! } init(delegationOk2: Void) { try! self.init(throws: ()) } init(delegationOk3: Void) { try! self.init(failableAndThrows: ())! } init(delegationOk4: Void) { try! self.init(failableIUOAndThrows: ()) } init(nonFailable: Void) { // expected-note{{propagate the failure with 'init?'}}{{7-7=?}} self.init(failable: ()) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(failable:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{28-28=!}} } init(delegationBad1: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(nonFailable: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad2: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableIUO: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad3: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(throws: ()) // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-2 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad4: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try! try? self.init(throws: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{10-14=try!}} } init(delegationBad5: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try try? self.init(throws: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{9-13=try!}} } init(delegationBad6: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableAndThrows: ())! // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-2 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad7: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try! self.init(failableAndThrows: ()) // expected-error@-1 {{a non-failable initializer cannot delegate to failable initializer 'init(failableAndThrows:)' written with 'init?'}} // expected-note@-2 {{force potentially-failing result with '!'}}{{42-42=!}} } init(delegationBad8: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableIUOAndThrows: ()) // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-2 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad9: Void) { // expected-note 2 {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableAndThrows: ()) // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-error@-2 {{a non-failable initializer cannot delegate to failable initializer 'init(failableAndThrows:)' written with 'init?'}} // expected-note@-3 {{force potentially-failing result with '!'}}{{42-42=!}} // expected-note@-4 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } } extension Optional { init(delegationOk1: Void) { self.init(nonFailable: ()) } init?(delegationOk2: Void) { self.init(nonFailable: ()) } init?(delegationOk3: Void) { self.init(failable: ()) } init(delegationBad1: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} self.init(failable: ()) // expected-error@-1 {{a non-failable initializer cannot delegate to failable initializer 'init(failable:)' written with 'init?'}} // expected-note@-2 {{force potentially-failing result with '!'}}{{28-28=!}} } init(nonFailable: Void) {} init?(failable: Void) {} } // ---------------------------------------------------------------------------- // Initializer overriding // ---------------------------------------------------------------------------- class Sub2 : Super { override init!(fail: String) { // okay to change ? to ! super.init(fail: fail) } override init?(failIUO: String) { // okay to change ! to ? super.init(failIUO: failIUO) } override init() { super.init() } // no change } // Dropping optionality class Sub3 : Super { override init(fail: String) { // okay, strengthened result type super.init() } override init(failIUO: String) { // okay, strengthened result type super.init() } override init() { } // no change } // Adding optionality class Sub4 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init?() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } class Sub5 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init!() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } // ---------------------------------------------------------------------------- // Initializer conformances // ---------------------------------------------------------------------------- protocol P1 { init(string: String) } @objc protocol P1_objc { init(string: String) } protocol P2 { init?(fail: String) } protocol P3 { init!(failIUO: String) } class C1a : P1 { required init?(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} } class C1b : P1 { required init!(string: String) { } // okay } class C1b_objc : P1_objc { @objc required init!(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' in Objective-C protocol cannot be satisfied by a failable initializer ('init!')}} } class C1c { required init?(string: String) { } // expected-note {{'init(string:)' declared here}} } extension C1c: P1 {} // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} class C2a : P2 { required init(fail: String) { } // okay to remove failability } class C2b : P2 { required init?(fail: String) { } // okay, ? matches } class C2c : P2 { required init!(fail: String) { } // okay to satisfy init? with init! } class C3a : P3 { required init(failIUO: String) { } // okay to remove failability } class C3b : P3 { required init?(failIUO: String) { } // okay to satisfy ! with ? } class C3c : P3 { required init!(failIUO: String) { } // okay, ! matches } // ---------------------------------------------------------------------------- // Initiating failure // ---------------------------------------------------------------------------- struct InitiateFailureS { init(string: String) { // expected-note{{use 'init?' to make the initializer 'init(string:)' failable}}{{7-7=?}} return (nil) // expected-error{{only a failable initializer can return 'nil'}} } init(int: Int) { return 0 // expected-error{{'nil' is the only return value permitted in an initializer}} } init?(double: Double) { return nil // ok } init!(char: Character) { return nil // ok } }
848823755e44720ab49d21adf06936b5
33.268734
196
0.625396
false
false
false
false
apple/swift-lldb
refs/heads/stable
packages/Python/lldbsuite/test/lang/swift/generic_class_arg/main.swift
apache-2.0
2
protocol P { func foo() -> Int32 } public class C: P { var x: Int32 = 11223344 public func foo() -> Int32 { return x } } public struct S : P { var x: Int32 = 44332211 public func foo() -> Int32 { return x } } func foo<T1: P, T2: P> (_ t1: T1, _ t2: T2) -> Int32 { return t1.foo() + t2.foo() //% self.expect('frame variable -d run -- t1', substrs=['11223344']) //% self.expect('frame variable -d run -- t2', substrs=['44332211']) //% self.expect('expression -d run -- t1', substrs=['11223344']) //% self.expect('expression -d run -- t2', substrs=['44332211']) } print(foo(C(), S()))
9e0309d25a3072ecc112eab8bf621267
22.884615
97
0.570048
false
false
false
false
theddnc/iPromise
refs/heads/master
iPromiseTests/iPromiseTests.swift
mit
1
// // PromiseTests.swift // iPromiseTests // // Created by jzaczek on 24.10.2015. // Copyright © 2015 jzaczek. All rights reserved. // import XCTest @testable import iPromise class PromiseTests: XCTestCase { enum Error: ErrorType { case Error } /** Tests promise fulfilling mechanisms */ func testFulfill() { let promise = Promise.fulfill(true) XCTAssertEqual(promise.state, State.Fulfilled, "Promise should be fulfilled.") expect { testExpectation in promise.success { result in XCTAssertEqual(result, true, "Promise's result should be equal to true.") testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run.") } } } func testReadmeTest() { enum Error: ErrorType { case FailureAndError } expect { testEx in async { return 0.5 }.then({ result in if result > 0.5 { print("This is quite a large number") } else { throw Error.FailureAndError } }).then({ result in // this won't be called }).then({ result in // this won't be called }).failure({ (error) -> Double in // but this will switch error as! Error { case .FailureAndError: print("Long computation has failed miserably :(") } // let's recover return 0.6 }).then ({ result -> Double in if result > 0.5 { print("This is quite a large number") testEx.fulfill() } return 0.1 }) } } /** Tests promise rejection mechanisms */ func testReject() { let promise = Promise<Any>.reject(PromiseError.NilReason) XCTAssertEqual(promise.state, State.Rejected, "Promise should be rejected.") expect { testExpectation in promise.failure { error in XCTAssert(error is PromiseError) testExpectation.fulfill() } promise.success { result in XCTFail("Success handler should not have run.") } } } /** Tests promise construction capabilities and state watchers */ func testFulfillFromExecutor() { let promise = Promise { fulfill, reject in fulfill(true) } expect { testExpectation in promise.success { result in XCTAssertEqual(result, true, "Promise's result should be equal to true") testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run") } } } /** Tests promise construction capabilities and state watchers */ func testRejectFromExecutor() { let promise = Promise<Any> { fulfill, reject in reject(PromiseError.NilReason) } expect { testExpectation in promise.failure { error in XCTAssert(error is PromiseError) testExpectation.fulfill() } promise.success { result in XCTFail("Sucess handler should not have run") } } } func testAsyncReturn() { expect { testExpectation in let promise = async { return true } promise.success { result in XCTAssertEqual(result, true, "Async result should be true") testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run") } } } func testAsyncThrow() { expect { testExpectation in let promise = async { throw Error.Error } promise.failure { reason in XCTAssertEqual(reason as? Error, Error.Error, "Async reason should be Error.Error") testExpectation.fulfill() } promise.success { result in XCTFail("Success handler should not have run") } } } func testRace() { let bigInt = 10000000 let promises: [Promise<Int>] = self.promiseArray(bigInt) expect { testExpectation in let promise = Promise<Int>.race(promises) promise.success { result -> Int in XCTAssertEqual(result, bigInt, "First promise should finish sooner") testExpectation.fulfill() return result } promise.failure { error in XCTFail("Failure handler should not have run") } } } func testRaceFailure() { let promises: [Promise<Int>] = [ Promise.reject(PromiseError.NilReason), Promise.reject(PromiseError.NilReason) ] expect { testExpectation in let promise = Promise<Int>.race(promises) promise.failure { error in if let error = error as? PromiseError { switch error { case .NilReason: testExpectation.fulfill() default: XCTFail() } } else { XCTFail() } } promise.success { result in XCTFail("Success handler should not have run") } } } func testAllWithFailure() { let bigInt = 10000000 let promises: [Promise<Int>] = self.promiseArray(bigInt, failing: true) expect { testExpectation in let promise = Promise<Any>.all(promises) promise.success { result in XCTAssertEqual(result[0].0, bigInt, "First promise should yield bigInt") XCTAssertEqual(result[1].0, 2*bigInt, "Second promise should yield 2*bigInt") XCTAssert(result[2].1 is PromiseError) testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run") } } } func testThrowingFromPromiseHandler() { expect { testExpectation in let promise = Promise<Bool> { fulfill, reject in for _ in 1...1000000 { continue } fulfill(true) } .success { result in throw Error.Error } promise.failure { error in XCTAssertEqual(error as? Error, Error.Error, "Promise's rejection reason should be Error.Error") promise.failure { error in XCTAssertEqual(error as? Error, Error.Error, "Promise's rejection reason should be Error.Error") testExpectation.fulfill() throw Error.Error } throw Error.Error } } } func testChainFailure() { let successTask: () -> Promise<String> = { return Promise.fulfill("shortSuccess") } expect { testExpectation in successTask() .then({ result in XCTAssertEqual(result, "shortSuccess") throw PromiseError.NilReason }) .then({ result in XCTFail("Expected skip to failure handler") }) .then({ result in XCTFail("Expected skip to failure handler") testExpectation.fulfill() }) .failure({ error -> String in XCTAssert(error is PromiseError) return "recovered" }) .success({ result in XCTAssertEqual(result, "recovered") testExpectation.fulfill() }) } } func testReturningPromiseFromSuccess() { expect { testExpectation in Promise { fulfill, reject in fulfill(10) }.then({ result in return Promise { fulfill, reject in fulfill(100) } }).then({ result in XCTAssertEqual(result, 100) testExpectation.fulfill() }) } } func testReturningPromiseFromFailure() { expect { testExpectation in Promise<Void>.reject(Error.Error).then(nil, onFailure: { error in return Promise { fulfill, reject in fulfill(100) } }).then({ result in XCTAssertEqual(result, 100) testExpectation.fulfill() }) } } private func promiseArray(bigInt: Int, failing: Bool = false) -> [Promise<Int>] { var promises: [Promise<Int>] = [ Promise { fulfill, reject in var ret = 0 for i in 1...bigInt { ret = i } fulfill(ret) }, Promise { fulfill, reject in var ret = 0 for i in 1...bigInt*2 { ret = i } fulfill(ret) } ] if failing { promises.append(Promise.reject(PromiseError.NilReason)) } return promises } private func expect(testClosure: (XCTestExpectation) -> Void) -> Void { let testExpectation = expectationWithDescription("Test expectation") testClosure(testExpectation) waitForExpectationsWithTimeout(10, handler: { error in XCTAssertNil(error, "Error") }) } }
73535ae8a7ad46fcb860bf3569c79ab2
28.957865
116
0.470605
false
true
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Filters/Low Pass Butterworth Filter/AKLowPassButterworthFilter.swift
mit
1
// // AKLowPassButterworthFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// These filters are Butterworth second-order IIR filters. They offer an almost /// flat passband and very good precision and stopband attenuation. /// open class AKLowPassButterworthFilter: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKLowPassButterworthFilterAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "btlp") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var cutoffFrequencyParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// Cutoff frequency. (in Hertz) @objc open dynamic var cutoffFrequency: Double = 1_000.0 { willSet { if cutoffFrequency != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { cutoffFrequencyParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.cutoffFrequency = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - cutoffFrequency: Cutoff frequency. (in Hertz) /// @objc public init( _ input: AKNode? = nil, cutoffFrequency: Double = 1_000.0) { self.cutoffFrequency = cutoffFrequency _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self!) } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } cutoffFrequencyParameter = tree["cutoffFrequency"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.cutoffFrequency = Float(cutoffFrequency) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
8961d436ad0dde887ee970eccd3a5091
30.743119
102
0.613006
false
false
false
false
yonasstephen/swift-of-airbnb
refs/heads/master
airbnb-main/airbnb-main/AirbnbHomeItemCell.swift
mit
1
// // AirbnbHomeItemCell.swift // airbnb-main // // Created by Yonas Stephen on 3/4/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit class AirbnbHomeItemCell: BaseCollectionCell { var home: AirbnbHome? { didSet { imageView.image = UIImage(named: home!.imageName) priceLabel.text = "$\(home!.price)" descriptionLabel.text = home?.homeDescription reviewCountLabel.text = "\(home!.reviewCount) Reviews" ratingView.rating = home!.rating } } var homeDescription: String? { didSet { descriptionLabel.text = homeDescription } } var imageView: UIImageView = { let view = UIImageView() view.translatesAutoresizingMaskIntoConstraints = false view.contentMode = .scaleAspectFill view.clipsToBounds = true return view }() var priceLabel: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.boldSystemFont(ofSize: 14) view.textColor = UIColor.black return view }() var descriptionLabel: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.systemFont(ofSize: 14) view.textColor = UIColor.gray return view }() var ratingView: AirbnbReview = { let view = AirbnbReview() view.translatesAutoresizingMaskIntoConstraints = false return view }() var reviewCountLabel: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.boldSystemFont(ofSize: 10) view.textColor = UIColor.darkGray return view }() override func setupViews() { addSubview(imageView) imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true imageView.heightAnchor.constraint(equalToConstant: 180).isActive = true imageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true addSubview(priceLabel) priceLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10).isActive = true priceLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true priceLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true priceLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true addSubview(descriptionLabel) descriptionLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10).isActive = true descriptionLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true descriptionLabel.leftAnchor.constraint(equalTo: priceLabel.rightAnchor).isActive = true descriptionLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true addSubview(ratingView) ratingView.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 0).isActive = true ratingView.heightAnchor.constraint(equalToConstant: 20).isActive = true ratingView.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true ratingView.widthAnchor.constraint(equalToConstant: ratingView.starSize * CGFloat(ratingView.stars.count)).isActive = true addSubview(reviewCountLabel) reviewCountLabel.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 0).isActive = true reviewCountLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true reviewCountLabel.leftAnchor.constraint(equalTo: ratingView.rightAnchor, constant: 5).isActive = true reviewCountLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true } }
1ae974948bfc1873936e19883b63d156
37.238095
129
0.672478
false
false
false
false