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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
FRA7/FJWeibo
|
refs/heads/master
|
FJWeibo/Classes/Home/Popover/PopoverPresentationController.swift
|
mit
|
1
|
//
// PopoverPresentationController.swift
// FJWeibo
//
// Created by Francis on 3/1/16.
// Copyright © 2016 FRAJ. All rights reserved.
//
import UIKit
class PopoverPresentationController:UIPresentationController {
var presentFrame = CGRectZero
override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
}
override func containerViewWillLayoutSubviews() {
if presentFrame == CGRectZero{
//1.设置弹出视图的大小
// let preX = UIScreen.mainScreen().bounds.size.width / 2 - 100
// print(preX)
presentedView()?.frame = CGRect(x: 100, y: 56, width: 200, height: 200)
}else{
presentedView()?.frame = presentFrame
}
//2.增加蒙版
containerView?.insertSubview(coverView, atIndex: 0)
}
//MARK: - 懒加载
private lazy var coverView:UIView = {
//1.创建view
let v = UIView()
v.backgroundColor = UIColor(white: 0.0, alpha: 0.3)
v.frame = UIScreen.mainScreen().bounds
//2.添加监听
let tap = UITapGestureRecognizer(target: self, action: #selector(PopoverPresentationController.close))
v.addGestureRecognizer(tap)
return v
}()
func close(){
presentedViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
|
8c4e04a80e685d25a438aa071e40f823
| 27.851852 | 120 | 0.619384 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
test/SILGen/function_conversion.swift
|
apache-2.0
|
10
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
// Check SILGen against various FunctionConversionExprs emitted by Sema.
// ==== Representation conversions
// CHECK-LABEL: sil hidden @_TF19function_conversion7cToFuncFcSiSiFSiSi : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_owned (Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFtCc_dSi_dSi_XFo_dSi_dSi_
// CHECK: [[FUNC:%.*]] = partial_apply [[THUNK]](%0)
// CHECK: return [[FUNC]]
func cToFunc(arg: @convention(c) Int -> Int) -> Int -> Int {
return arg
}
// CHECK-LABEL: sil hidden @_TF19function_conversion8cToBlockFcSiSibSiSi : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int
// CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]]
// CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int
// CHECK: return [[COPY]]
func cToBlock(arg: @convention(c) Int -> Int) -> @convention(block) Int -> Int {
return arg
}
// ==== Throws variance
// CHECK-LABEL: sil hidden @_TF19function_conversion12funcToThrowsFFT_T_FzT_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> @owned @callee_owned () -> @error ErrorType
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@callee_owned () -> () to $@callee_owned () -> @error ErrorType
// CHECK: return [[FUNC]]
func funcToThrows(x: () -> ()) -> () throws -> () {
return x
}
// CHECK-LABEL: sil hidden @_TF19function_conversion12thinToThrowsFXfT_T_XfzT_T_ : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error ErrorType
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error ErrorType
// CHECK: return [[FUNC]] : $@convention(thin) () -> @error ErrorType
func thinToThrows(x: @convention(thin) () -> ()) -> @convention(thin) () throws -> () {
return x
}
// FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs
/*
func thinFunc() {}
func thinToThrows() {
let _: @convention(thin) () -> () = thinFunc
}
*/
// ==== Class downcasts and upcasts
class Feral {}
class Domesticated : Feral {}
// CHECK-LABEL: sil hidden @_TF19function_conversion12funcToUpcastFFT_CS_12DomesticatedFT_CS_5Feral : $@convention(thin) (@owned @callee_owned () -> @owned Domesticated) -> @owned @callee_owned () -> @owned Feral
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@callee_owned () -> @owned Domesticated to $@callee_owned () -> @owned Feral
// CHECK: return [[FUNC]]
func funcToUpcast(x: () -> Domesticated) -> () -> Feral {
return x
}
// CHECK-LABEL: sil hidden @_TF19function_conversion12funcToUpcastFFCS_5FeralT_FCS_12DomesticatedT_ : $@convention(thin) (@owned @callee_owned (@owned Feral) -> ()) -> @owned @callee_owned (@owned Domesticated) -> ()
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@callee_owned (@owned Feral) -> () to $@callee_owned (@owned Domesticated) -> () // user: %3
// CHECK: return [[FUNC]]
func funcToUpcast(x: Feral -> ()) -> Domesticated -> () {
return x
}
// ==== Optionals
struct Trivial {
let n: Int8
}
class C {
let n: Int8
init(n: Int8) {
self.n = n
}
}
struct Loadable {
let c: C
var n: Int8 {
return c.n
}
init(n: Int8) {
c = C(n: n)
}
}
struct AddrOnly {
let a: Any
var n: Int8 {
return a as! Int8
}
init(n: Int8) {
a = n
}
}
// CHECK-LABEL: sil hidden @_TF19function_conversion19convOptionalTrivialFFGSqVS_7Trivial_S0_T_
func convOptionalTrivial(t1: Trivial? -> Trivial) {
// CHECK: function_ref @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dS0__dGSqS0___
// CHECK: partial_apply
let _: Trivial -> Trivial? = t1
// CHECK: function_ref @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dGSQS0___dGSqS0___
// CHECK: partial_apply
let _: Trivial! -> Trivial? = t1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dS0__dGSqS0___ : $@convention(thin) (Trivial, @owned @callee_owned (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: enum $Optional<Trivial>
// CHECK-NEXT: apply %1(%2)
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dGSQS0___dGSqS0___ : $@convention(thin) (ImplicitlyUnwrappedOptional<Trivial>, @owned @callee_owned (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: unchecked_trivial_bit_cast %0 : $ImplicitlyUnwrappedOptional<Trivial> to $Optional<Trivial>
// CHECK-NEXT: apply %1(%2)
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_TF19function_conversion20convOptionalLoadableFFGSqVS_8Loadable_S0_T_
func convOptionalLoadable(l1: Loadable? -> Loadable) {
// CHECK: function_ref @_TTRXFo_oGSqV19function_conversion8Loadable__oS0__XFo_oS0__oGSqS0___
// CHECK: partial_apply
let _: Loadable -> Loadable? = l1
// CHECK: function_ref @_TTRXFo_oGSqV19function_conversion8Loadable__oS0__XFo_oGSQS0___oGSqS0___
// CHECK: partial_apply
let _: Loadable! -> Loadable? = l1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oGSqV19function_conversion8Loadable__oS0__XFo_oGSQS0___oGSqS0___ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Loadable>, @owned @callee_owned (@owned Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable>
// CHECK: unchecked_bitwise_cast %0 : $ImplicitlyUnwrappedOptional<Loadable> to $Optional<Loadable>
// CHECK-NEXT: apply %1(%2)
// CHECK-NEXT: enum $Optional<Loadable>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_TF19function_conversion20convOptionalAddrOnlyFFGSqVS_8AddrOnly_S0_T_
func convOptionalAddrOnly(a1: AddrOnly? -> AddrOnly) {
// CHECK: function_ref @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSqS0___iGSqS0___
// CHECK: partial_apply
let _: AddrOnly? -> AddrOnly? = a1
// CHECK: function_ref @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSQS0___iGSqS0___
// CHECK: partial_apply
let _: AddrOnly! -> AddrOnly? = a1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSqS0___iGSqS0___ : $@convention(thin) (@out Optional<AddrOnly>, @in Optional<AddrOnly>, @owned @callee_owned (@out AddrOnly, @in Optional<AddrOnly>) -> ()) -> ()
// CHECK: alloc_stack $AddrOnly
// CHECK-NEXT: apply %2(%3#1, %1)
// CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: dealloc_stack {{.*}} : $*@local_storage AddrOnly
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSQS0___iGSqS0___ : $@convention(thin) (@out Optional<AddrOnly>, @in ImplicitlyUnwrappedOptional<AddrOnly>, @owned @callee_owned (@out AddrOnly, @in Optional<AddrOnly>) -> ()) -> ()
// CHECK: alloc_stack $Optional<AddrOnly>
// CHECK-NEXT: unchecked_addr_cast %1 : $*ImplicitlyUnwrappedOptional<AddrOnly> to $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*Optional<AddrOnly>
// CHECK-NEXT: alloc_stack $AddrOnly
// CHECK-NEXT: apply %2(%6#1, %3#1)
// CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: dealloc_stack {{.*}} : $*@local_storage AddrOnly
// CHECK-NEXT: dealloc_stack {{.*}} : $*@local_storage Optional<AddrOnly>
// CHECK-NEXT: return
// ==== Existentials
protocol Q {
var n: Int8 { get }
}
protocol P : Q {}
extension Trivial : P {}
extension Loadable : P {}
extension AddrOnly : P {}
// CHECK-LABEL: sil hidden @_TF19function_conversion22convExistentialTrivialFTFPS_1Q_VS_7Trivial2t3FGSqPS0___S1__T_
func convExistentialTrivial(t2: Q -> Trivial, t3: Q? -> Trivial) {
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_dS1__iPS_1P__
// CHECK: partial_apply
let _: Trivial -> P = t2
// CHECK: function_ref @_TTRXFo_iGSqP19function_conversion1Q___dVS_7Trivial_XFo_dGSqS1___iPS_1P__
// CHECK: partial_apply
let _: Trivial? -> P = t3
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_iPS_1P__iPS2___
// CHECK: partial_apply
let _: P -> P = t2
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_dS1__iPS_1P__ : $@convention(thin) (@out P, Trivial, @owned @callee_owned (@in Q) -> Trivial) -> ()
// CHECK: alloc_stack $Q
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iGSqP19function_conversion1Q___dVS_7Trivial_XFo_dGSqS1___iPS_1P__
// CHECK: select_enum
// CHECK: cond_br
// CHECK: bb1:
// CHECK: unchecked_enum_data
// CHECK: init_existential_addr
// CHECK: init_enum_data_addr
// CHECK: copy_addr
// CHECK: inject_enum_addr
// CHECK: bb2:
// CHECK: inject_enum_addr
// CHECK: bb3:
// CHECK: apply
// CHECK: init_existential_addr
// CHECK: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_iPS_1P__iPS2___ : $@convention(thin) (@out P, @in P, @owned @callee_owned (@in Q) -> Trivial) -> ()
// CHECK: alloc_stack $Q
// CHECK-NEXT: open_existential_addr %1 : $*P
// CHECK-NEXT: init_existential_addr %3#1 : $*Q
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}}
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: deinit_existential_addr
// CHECK: return
// ==== Existential metatypes
// CHECK-LABEL: sil hidden @_TF19function_conversion23convExistentialMetatypeFFGSqPMPS_1Q__MVS_7TrivialT_
func convExistentialMetatype(em: Q.Type? -> Trivial.Type) {
// CHECK: function_ref @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXMtS1__dXPMTPS_1P__
// CHECK: partial_apply
let _: Trivial.Type -> P.Type = em
// CHECK: function_ref @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dGSqMS1___dXPMTPS_1P__
// CHECK: partial_apply
let _: Trivial.Type? -> P.Type = em
// CHECK: function_ref @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXPMTPS_1P__dXPMTPS2___
// CHECK: partial_apply
let _: P.Type -> P.Type = em
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXMtS1__dXPMTPS_1P__ : $@convention(thin) (@thin Trivial.Type, @owned @callee_owned (Optional<Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype %2 : $@thick Trivial.Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dGSqMS1___dXPMTPS_1P__ : $@convention(thin) (Optional<Trivial.Type>, @owned @callee_owned (Optional<Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: select_enum %0 : $Optional<Trivial.Type>
// CHECK-NEXT: cond_br
// CHECK: bb1:
// CHECK-NEXT: unchecked_enum_data %0 : $Optional<Trivial.Type>
// CHECK-NEXT: metatype $@thin Trivial.Type
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK: bb2:
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK: bb3({{.*}}):
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXPMTPS_1P__dXPMTPS2___ : $@convention(thin) (@thick P.Type, @owned @callee_owned (Optional<Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: open_existential_metatype %0 : $@thick P.Type to $@thick (@opened({{.*}}) P).Type
// CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}) P).Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// ==== Class metatype upcasts
class Parent {}
class Child : Parent {}
// Note: we add a Trivial => Trivial? conversion here to force a thunk
// to be generated
// CHECK-LABEL: sil hidden @_TF19function_conversion18convUpcastMetatypeFTFTMCS_6ParentGSqVS_7Trivial__MCS_5Child2c5FTGSqMS0__GSqS1___MS2__T_
func convUpcastMetatype(c4: (Parent.Type, Trivial?) -> Child.Type,
c5: (Parent.Type?, Trivial?) -> Child.Type) {
// CHECK: function_ref @_TTRXFo_dXMTC19function_conversion6ParentdGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c4
// CHECK: function_ref @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c5
// CHECK: function_ref @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dGSqMS2__dS1__dGSqMS0___
// CHECK: partial_apply
let _: (Child.Type?, Trivial) -> Parent.Type? = c5
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dXMTC19function_conversion6ParentdGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__ : $@convention(thin) (@thick Child.Type, Trivial, @owned @callee_owned (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__ : $@convention(thin) (@thick Child.Type, Trivial, @owned @callee_owned (Optional<Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dGSqMS2__dS1__dGSqMS0___ : $@convention(thin) (Optional<Child.Type>, Trivial, @owned @callee_owned (Optional<Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<Parent.Type>
// CHECK: unchecked_trivial_bit_cast %0 : $Optional<Child.Type> to $Optional<Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<Parent.Type>
// CHECK: return
// ==== Function to existential -- make sure we maximally abstract it
// CHECK-LABEL: sil hidden @_TF19function_conversion19convFuncExistentialFFP_FSiSiT_ : $@convention(thin) (@owned @callee_owned (@in protocol<>) -> @owned @callee_owned (Int) -> Int) -> ()
func convFuncExistential(f1: Any -> Int -> Int) {
// CHECK: function_ref @_TTRXFo_iP__oXFo_dSi_dSi__XFo_oXFo_dSi_dSi__iP__
// CHECK: partial_apply %3(%0)
let _: (Int -> Int) -> Any = f1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP__oXFo_dSi_dSi__XFo_oXFo_dSi_dSi__iP__ : $@convention(thin) (@out protocol<>, @owned @callee_owned (Int) -> Int, @owned @callee_owned (@in protocol<>) -> @owned @callee_owned (Int) -> Int) -> ()
// CHECK: alloc_stack $protocol<>
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK-NEXT: partial_apply
// CHECK-NEXT: init_existential_addr %3#1 : $*protocol<>, $Int -> Int
// CHECK-NEXT: store
// CHECK-NEXT: apply
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK-NEXT: partial_apply
// CHECK-NEXT: init_existential_addr %0 : $*protocol<>, $Int -> Int
// CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_owned (@out Int, @in Int) -> ()
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dSi_dSi_XFo_iSi_iSi_ : $@convention(thin) (@out Int, @in Int, @owned @callee_owned (Int) -> Int) -> ()
// CHECK: load %1 : $*Int
// CHECK-NEXT: apply %2(%3)
// CHECK-NEXT: store {{.*}} to %0
// CHECK: return
// ==== Class-bound archetype upcast
// CHECK-LABEL: sil hidden @_TF19function_conversion29convClassBoundArchetypeUpcast
func convClassBoundArchetypeUpcast<T : Parent>(f1: Parent -> (T, Trivial)) {
// CHECK: function_ref @_TTRGRxC19function_conversion6ParentrXFo_oS0__oTxVS_7Trivial__XFo_ox_oTS0_GSqS1____
// CHECK: partial_apply
let _: T -> (Parent, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRGRxC19function_conversion6ParentrXFo_oS0__oTxVS_7Trivial__XFo_ox_oTS0_GSqS1____ : $@convention(thin) <T where T : Parent> (@owned T, @owned @callee_owned (@owned Parent) -> @owned (T, Trivial)) -> @owned (Parent, Optional<Trivial>)
// CHECK: upcast %0 : $T to $Parent
// CHECK-NEXT: apply
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: upcast {{.*}} : $T to $Parent
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_TF19function_conversion37convClassBoundMetatypeArchetypeUpcast
func convClassBoundMetatypeArchetypeUpcast<T : Parent>(f1: Parent.Type -> (T.Type, Trivial)) {
// CHECK: function_ref @_TTRGRxC19function_conversion6ParentrXFo_dXMTS0__dTXMTxVS_7Trivial__XFo_dXMTx_dTXMTS0_GSqS1____
// CHECK: partial_apply
let _: T.Type -> (Parent.Type, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRGRxC19function_conversion6ParentrXFo_dXMTS0__dTXMTxVS_7Trivial__XFo_dXMTx_dTXMTS0_GSqS1____ : $@convention(thin) <T where T : Parent> (@thick T.Type, @owned @callee_owned (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>)
// CHECK: upcast %0 : $@thick T.Type to $@thick Parent.Type
// CHECK-NEXT: apply
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// ==== Make sure we destructure one-element tuples
// CHECK-LABEL: sil hidden @_TF19function_conversion15convTupleScalarFTFPS_1Q_T_2f2FT6parentPS0___T_2f3FT5tupleGSqTSiSi___T__T_
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dT__XFo_iPS_1P__dT__
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dT__XFo_iPS_1P__dT__
// CHECK: function_ref @_TTRXFo_dGSqTSiSi___dT__XFo_dSidSi_dT__
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP19function_conversion1Q__dT__XFo_iPS_1P__dT__ : $@convention(thin) (@in P, @owned @callee_owned (@in Q) -> ()) -> ()
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqTSiSi___dT__XFo_dSidSi_dT__ : $@convention(thin) (Int, Int, @owned @callee_owned (Optional<(Int, Int)>) -> ()) -> ()
func convTupleScalar(f1: Q -> (),
f2: (parent: Q) -> (),
f3: (tuple: (Int, Int)?) -> ()) {
let _: (parent: P) -> () = f1
let _: P -> () = f2
let _: (Int, Int) -> () = f3
}
// CHECK-LABEL: sil hidden @_TF19function_conversion21convTupleScalarOpaqueurFFt4argsGSax__T_GSqFt4argsGSax__T__
// CHECK: function_ref @_TTRGrXFo_oGSax__dT__XFo_it4argsGSax___iT__
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRGrXFo_oGSax__dT__XFo_it4argsGSax___iT__ : $@convention(thin) <T> (@out (), @in (args: T...), @owned @callee_owned (@owned Array<T>) -> ()) -> ()
func convTupleScalarOpaque<T>(f: (args: T...) -> ()) -> ((args: T...) -> ())? {
return f
}
|
ada10e7086ca8f73b1e850151916b782
| 48.815851 | 331 | 0.650695 | false | false | false | false |
wenfzhao/SimpleRouter
|
refs/heads/master
|
Example/SimpleRouter/AuthenticationMiddleware.swift
|
mit
|
1
|
//
// AuthenticationMiddleware.swift
// SimpleRouter
//
// Created by Wen Zhao on 3/3/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import SimpleRouter
class AuthenticationMiddleware: Middleware {
func handle(request: RouteRequest, closure: MiddlewareClosure) -> RouteRequest {
var response = request
print("Authenticating user......")
if (App.isLogin == false) {
print("User not authenticated")
var url = "/logout"
if request.url != "/logout" {
url = "/logout?_fromUrl=\(request.url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)"
}
Router.sharedInstance.routeURL(url)
} else {
response = closure(request)
}
print("After AuthenticationMiddleware......")
return response
}
}
|
41517f011285365c45efbf9003282568
| 29.7 | 153 | 0.624321 | false | false | false | false |
jphacks/TK_08
|
refs/heads/master
|
iOS/AirMeet/AirMeet/ChildTableViewCell.swift
|
mit
|
1
|
//
// ChildTableViewCell.swift
// AirMeet
//
// Created by koooootake on 2015/11/28.
// Copyright © 2015年 koooootake. All rights reserved.
//
import UIKit
class ChildTableViewCell: UITableViewCell {
@IBOutlet weak var imageImageView: UIImageView!
//@IBOutlet weak var backImageView: SABlurImageView!
@IBOutlet weak var backImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var blackImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
//backView.layer.borderWidth = 3.0
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
//super.setHighlighted(highlighted, animated: animated)
//self.blackImageView.backgroundColor = UIColor(white: 0.2, alpha: 0.1)
if highlighted{
self.blackImageView.backgroundColor = UIColor(white: 0.5, alpha: 0.3)
}else{
self.blackImageView.backgroundColor = UIColor(white: 0.0, alpha: 0.3)
}
}
override func setSelected(selected: Bool, animated: Bool) {
//super.setSelected(selected, animated: animated)
//self.blackImageView.backgroundColor = UIColor(white: 0.2, alpha: 0.5)
}
func setCell(childModel:ChildModel){
self.backImageView.image = childModel.backgroundImage
self.backImageView.layer.cornerRadius = 3.0
self.backImageView.layer.masksToBounds = true
//self.blackImageView.backgroundColor = UIColor(white: 0.2, alpha: 0.5)
//黒いのかぶせる
//let backCoverView:UIView = UIView(frame: self.backImageView.frame)
//backImageView.backgroundColor = UIColor(red: 128.0/255.0, green: 204.0/255.0, blue: 223.0/255.0, alpha: 1)
//self.backImageView.addSubview(backCoverView)
//ぶらー
//let blurEffect = UIBlurEffect(style: .Light)
//let lightBlurView = UIVisualEffectView(effect: blurEffect)
//lightBlurView.frame = self.backImageView.bounds
//self.backImageView.addSubview(lightBlurView)
//self.backImageView.addBlurEffect(50)
self.nameLabel.text = childModel.name
self.detailLabel.text = childModel.detail
//文字を擦ったかんじに
/*
let lightVibrancyView =
vibrancyEffectView(
fromBlurEffect: lightBlurView.effect as! UIBlurEffect,
frame: backImageView.bounds)
lightBlurView.contentView.addSubview(lightVibrancyView)
lightVibrancyView.contentView.addSubview(self.nameLabel)
lightVibrancyView.contentView.addSubview(self.detailLabel)
*/
self.imageImageView.image = childModel.image
//アイコンまる
self.imageImageView.layer.cornerRadius = imageImageView.frame.size.width/2.0
self.imageImageView.layer.masksToBounds = true
self.imageImageView.layer.borderColor = UIColor.whiteColor().CGColor
self.imageImageView.layer.borderWidth = 3.0
}
// VibrancyエフェクトのViewを生成
func vibrancyEffectView(fromBlurEffect effect: UIBlurEffect, frame: CGRect) -> UIVisualEffectView {
let vibrancyEffect = UIVibrancyEffect(forBlurEffect: effect)
let vibrancyView = UIVisualEffectView(effect: vibrancyEffect)
vibrancyView.frame = frame
return vibrancyView
}
}
|
5a8b31fb84427a8481d7b1026cd42d21
| 31.1 | 116 | 0.645709 | false | false | false | false |
onmyway133/Scale
|
refs/heads/master
|
Sources/Length.swift
|
mit
|
1
|
//
// Length.swift
// Scale
//
// Created by Khoa Pham
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
public enum LengthUnit: Double {
case millimeter = 0.001
case centimeter = 0.01
case decimeter = 0.1
case meter = 1
case dekameter = 10
case hectometer = 100
case kilometer = 1_000
case yard = 0.914_4
case parsec = 30_856_775_813_060_000
case mile = 1_609.344
case foot = 0.304_8
case fathom = 1.828_8
case inch = 0.025_4
case league = 4_828.032
static var defaultScale: Double {
return LengthUnit.meter.rawValue
}
}
public struct Length {
public let value: Double
public let unit: LengthUnit
public init(value: Double, unit: LengthUnit) {
self.value = value
self.unit = unit
}
public func to(unit: LengthUnit) -> Length {
return Length(value: self.value * self.unit.rawValue * LengthUnit.meter.rawValue / unit.rawValue, unit: unit)
}
}
public extension Double {
public var millimeter: Length {
return Length(value: self, unit: .millimeter)
}
public var centimeter: Length {
return Length(value: self, unit: .centimeter)
}
public var decimeter: Length {
return Length(value: self, unit: .decimeter)
}
public var meter: Length {
return Length(value: self, unit: .meter)
}
public var dekameter: Length {
return Length(value: self, unit: .dekameter)
}
public var hectometer: Length {
return Length(value: self, unit: .hectometer)
}
public var kilometer: Length {
return Length(value: self, unit: .kilometer)
}
public var yard: Length {
return Length(value: self, unit: .yard)
}
public var parsec: Length {
return Length(value: self, unit: .parsec)
}
public var mile: Length {
return Length(value: self, unit: .mile)
}
public var foot: Length {
return Length(value: self, unit: .foot)
}
public var fathom: Length {
return Length(value: self, unit: .fathom)
}
public var inch: Length {
return Length(value: self, unit: .inch)
}
public var league: Length {
return Length(value: self, unit: .league)
}
}
public func compute(_ left: Length, right: Length, operation: (Double, Double) -> Double) -> Length {
let (min, max) = left.unit.rawValue < right.unit.rawValue ? (left, right) : (right, left)
let result = operation(min.value, max.to(unit: min.unit).value)
return Length(value: result, unit: min.unit)
}
public func +(left: Length, right: Length) -> Length {
return compute(left, right: right, operation: +)
}
public func -(left: Length, right: Length) -> Length {
return compute(left, right: right, operation: -)
}
public func *(left: Length, right: Length) -> Length {
return compute(left, right: right, operation: *)
}
public func /(left: Length, right: Length) throws -> Length {
guard right.value != 0 else {
throw ScaleError.dividedByZero
}
return compute(left, right: right, operation: /)
}
|
2dba10de22f0cbe166339316e85ea2e6
| 23.348837 | 117 | 0.624642 | false | false | false | false |
seandavidmcgee/HumanKontactBeta
|
refs/heads/master
|
src/HumanKontact Extension/HKWatchPhone.swift
|
mit
|
1
|
//
// HKPhoneNumber.swift
// keyboardTest
//
// Created by Sean McGee on 6/30/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import WatchKit
import Foundation
import Contacts
import RealmSwift
class HKPhoneNumber: Object {
dynamic var uuid = NSUUID().UUIDString
dynamic var number = ""
dynamic var formattedNumber: String = ""
dynamic var label = ""
override class func primaryKey() -> String {
return "uuid"
}
}
class ABPhoneUtility: NSObject {
class func normalizedPhoneStringFromString(phoneString: NSString?) -> NSString {
let phoneNumber: String! = phoneString as? String
let strippedPhoneNumber = phoneNumber.stringByReplacingOccurrencesOfString("[^0-9 ]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil)
var cleanNumber = strippedPhoneNumber.removeWhitespace()
cleanNumber = cleanNumber.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return cleanNumber.copy() as! NSString
}
class func normalizedPhoneLabelFromString(phoneString: NSString?) -> NSString {
let phoneLabel: String! = phoneString as? String
let strippedPhoneLabel = phoneLabel.stringByReplacingOccurrencesOfString("[^a-zA-Z ]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil)
var cleanLabel = strippedPhoneLabel.removeWhitespace()
cleanLabel = cleanLabel.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return cleanLabel.copy() as! NSString
}
}
|
4a0327ba35fc5419bfc3a42545bdcf71
| 37.880952 | 178 | 0.731782 | false | false | false | false |
BjornRuud/HTTPSession
|
refs/heads/master
|
Cocoapods/Pods/Swifter/Sources/HttpRequest.swift
|
apache-2.0
|
4
|
//
// HttpRequest.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public class HttpRequest {
public var path: String = ""
public var queryParams: [(String, String)] = []
public var method: String = ""
public var headers: [String: String] = [:]
public var body: [UInt8] = []
public var address: String? = ""
public var params: [String: String] = [:]
public func hasTokenForHeader(_ headerName: String, token: String) -> Bool {
guard let headerValue = headers[headerName] else {
return false
}
return headerValue.split(",").filter({ $0.trim().lowercased() == token }).count > 0
}
public func parseUrlencodedForm() -> [(String, String)] {
guard let contentTypeHeader = headers["content-type"] else {
return []
}
let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
guard let contentType = contentTypeHeaderTokens.first, contentType == "application/x-www-form-urlencoded" else {
return []
}
return String.fromUInt8(body).split("&").map { param -> (String, String) in
let tokens = param.split("=")
if let name = tokens.first, let value = tokens.last, tokens.count == 2 {
return (name.replace(old: "+", " ").removePercentEncoding(),
value.replace(old: "+", " ").removePercentEncoding())
}
return ("","")
}
}
public struct MultiPart {
public let headers: [String: String]
public let body: [UInt8]
public var name: String? {
return valueFor("content-disposition", parameter: "name")?.unquote()
}
public var fileName: String? {
return valueFor("content-disposition", parameter: "filename")?.unquote()
}
private func valueFor(_ headerName: String, parameter: String) -> String? {
return headers.reduce([String]()) { (combined, header: (key: String, value: String)) -> [String] in
guard header.key == headerName else {
return combined
}
let headerValueParams = header.value.split(";").map { $0.trim() }
return headerValueParams.reduce(combined, { (results, token) -> [String] in
let parameterTokens = token.split(1, separator: "=")
if parameterTokens.first == parameter, let value = parameterTokens.last {
return results + [value]
}
return results
})
}.first
}
}
public func parseMultiPartFormData() -> [MultiPart] {
guard let contentTypeHeader = headers["content-type"] else {
return []
}
let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
guard let contentType = contentTypeHeaderTokens.first, contentType == "multipart/form-data" else {
return []
}
var boundary: String? = nil
contentTypeHeaderTokens.forEach({
let tokens = $0.split("=")
if let key = tokens.first, key == "boundary" && tokens.count == 2 {
boundary = tokens.last
}
})
if let boundary = boundary, boundary.utf8.count > 0 {
return parseMultiPartFormData(body, boundary: "--\(boundary)")
}
return []
}
private func parseMultiPartFormData(_ data: [UInt8], boundary: String) -> [MultiPart] {
var generator = data.makeIterator()
var result = [MultiPart]()
while let part = nextMultiPart(&generator, boundary: boundary, isFirst: result.isEmpty) {
result.append(part)
}
return result
}
private func nextMultiPart(_ generator: inout IndexingIterator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? {
if isFirst {
guard nextMultiPartLine(&generator) == boundary else {
return nil
}
} else {
let /* ignore */ _ = nextMultiPartLine(&generator)
}
var headers = [String: String]()
while let line = nextMultiPartLine(&generator), !line.isEmpty {
let tokens = line.split(":")
if let name = tokens.first, let value = tokens.last, tokens.count == 2 {
headers[name.lowercased()] = value.trim()
}
}
guard let body = nextMultiPartBody(&generator, boundary: boundary) else {
return nil
}
return MultiPart(headers: headers, body: body)
}
private func nextMultiPartLine(_ generator: inout IndexingIterator<[UInt8]>) -> String? {
var result = String()
while let value = generator.next() {
if value > HttpRequest.CR {
result.append(Character(UnicodeScalar(value)))
}
if value == HttpRequest.NL {
break
}
}
return result
}
static let CR = UInt8(13)
static let NL = UInt8(10)
private func nextMultiPartBody(_ generator: inout IndexingIterator<[UInt8]>, boundary: String) -> [UInt8]? {
var body = [UInt8]()
let boundaryArray = [UInt8](boundary.utf8)
var matchOffset = 0;
while let x = generator.next() {
matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 )
body.append(x)
if matchOffset == boundaryArray.count {
body.removeSubrange(CountableRange<Int>(body.count-matchOffset ..< body.count))
if body.last == HttpRequest.NL {
body.removeLast()
if body.last == HttpRequest.CR {
body.removeLast()
}
}
return body
}
}
return nil
}
}
|
b44bd5c107336cb2ce5ee5988550be04
| 36.549383 | 125 | 0.540852 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
refs/heads/master
|
Floral/Pods/Hero/Sources/Extensions/CG+Hero.swift
|
mit
|
3
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import MetalKit
let π = CGFloat.pi
internal struct KeySet<Key: Hashable, Value: Hashable> {
var dict: [Key: Set<Value>] = [:]
internal subscript(key: Key) -> Set<Value> {
mutating get {
if dict[key] == nil {
dict[key] = Set<Value>()
}
return dict[key]!
}
set {
dict[key] = newValue
}
}
}
internal extension CGSize {
internal var center: CGPoint {
return CGPoint(x: width / 2, y: height / 2)
}
internal var point: CGPoint {
return CGPoint(x: width, y: height)
}
internal func transform(_ t: CGAffineTransform) -> CGSize {
return self.applying(t)
}
internal func transform(_ t: CATransform3D) -> CGSize {
return self.applying(CATransform3DGetAffineTransform(t))
}
}
internal extension CGRect {
internal var center: CGPoint {
return CGPoint(x: origin.x + width / 2, y: origin.y + height / 2)
}
internal var bounds: CGRect {
return CGRect(origin: CGPoint.zero, size: size)
}
init(center: CGPoint, size: CGSize) {
self.init(x: center.x - size.width / 2, y: center.y - size.height / 2, width: size.width, height: size.height)
}
}
extension CGFloat {
internal func clamp(_ a: CGFloat, _ b: CGFloat) -> CGFloat {
return self < a ? a : (self > b ? b : self)
}
}
extension TimeInterval {
internal func clamp(_ a: TimeInterval, _ b: TimeInterval) -> TimeInterval {
return self < a ? a : (self > b ? b : self)
}
}
extension CGPoint {
internal func translate(_ dx: CGFloat, dy: CGFloat) -> CGPoint {
return CGPoint(x: self.x + dx, y: self.y + dy)
}
internal func transform(_ t: CGAffineTransform) -> CGPoint {
return self.applying(t)
}
internal func transform(_ t: CATransform3D) -> CGPoint {
return self.applying(CATransform3DGetAffineTransform(t))
}
internal func distance(_ b: CGPoint) -> CGFloat {
return sqrt(pow(self.x - b.x, 2) + pow(self.y - b.y, 2))
}
internal static func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
internal static func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
internal static func / (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x / right, y: left.y / right)
}
internal static func / (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
internal static func * (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x * right, y: left.y * right)
}
internal static func * (left: CGPoint, right: CGSize) -> CGPoint {
return CGPoint(x: left.x * right.width, y: left.y * right.height)
}
internal static func * (left: CGFloat, right: CGPoint) -> CGPoint {
return right * left
}
internal static func * (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
internal static prefix func - (point: CGPoint) -> CGPoint {
return .zero - point
}
internal static func abs(_ p: CGPoint) -> CGPoint {
return CGPoint(x: Swift.abs(p.x), y: Swift.abs(p.y))
}
}
extension CGSize {
internal static func * (left: CGSize, right: CGFloat) -> CGSize {
return CGSize(width: left.width * right, height: left.height * right)
}
internal static func * (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width * right.width, height: left.height * right.height)
}
internal static func / (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width / right.width, height: left.height / right.height)
}
internal static func / (left: CGPoint, right: CGSize) -> CGPoint {
return CGPoint(x: left.x / right.width, y: left.y / right.height)
}
}
extension CATransform3D: Equatable {
public static func == (lhs: CATransform3D, rhs: CATransform3D) -> Bool {
var lhs = lhs
var rhs = rhs
return memcmp(&lhs, &rhs, MemoryLayout<CATransform3D>.size) == 0
}
}
|
a5fb6150d58c0770112072da63b494cb
| 32.597403 | 114 | 0.666216 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Card/CardAuthorization/CardAuthorizationScreenPresenter.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import FeatureCardPaymentDomain
import Localization
import PlatformKit
import ToolKit
public final class CardAuthorizationScreenPresenter: RibBridgePresenter {
let title = LocalizationConstants.AuthorizeCardScreen.title
var authorizationState: PartnerAuthorizationData.State {
data.state
}
private let eventRecorder: AnalyticsEventRecorderAPI
private let data: PartnerAuthorizationData
private var hasRedirected = false
private let interactor: CardAuthorizationScreenInteractor
// MARK: - Setup
public init(
interactor: CardAuthorizationScreenInteractor,
data: PartnerAuthorizationData,
eventRecorder: AnalyticsEventRecorderAPI = resolve()
) {
self.eventRecorder = eventRecorder
self.interactor = interactor
self.data = data
super.init(interactable: interactor)
}
public func redirect() {
// Might get called multiple times from the `WKNavigationDelegate`
guard !hasRedirected else { return }
hasRedirected = true
eventRecorder.record(event: AnalyticsEvents.SimpleBuy.sbThreeDSecureComplete)
interactor.cardAuthorized(with: data.paymentMethodId)
}
}
|
de6a840ec0d2ddd2029efcfedb731e60
| 28.155556 | 85 | 0.73628 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
refs/heads/master
|
Steps4Impact/Settings/Cells/AppInfoCell.swift
|
bsd-3-clause
|
1
|
/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
import SnapKit
struct AppInfoCellContext: CellContext {
let identifier: String = AppInfoCell.identifier
let title: String
let body: String
}
protocol AppInfoCellDelegate: AnyObject {
func appInfoCellToggleStaging()
}
class AppInfoCell: ConfigurableTableViewCell {
static let identifier = "AppInfoCell"
private let cardView = CardViewV2()
private let titleLabel = UILabel(typography: .title)
private let bodyLabel = UILabel(typography: .bodyRegular)
weak var delegate: AppInfoCellDelegate?
override func commonInit() {
super.commonInit()
cardView.addGestureRecognizer(UILongPressGestureRecognizer(
target: self,
action: #selector(cardLongPressed)))
contentView.addSubview(cardView) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p24)
$0.top.bottom.equalToSuperview().inset(Style.Padding.p12)
}
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = Style.Padding.p32
stackView.addArrangedSubviews(titleLabel, bodyLabel)
cardView.addSubview(stackView) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.top.bottom.equalToSuperview().inset(Style.Padding.p32)
}
}
func configure(context: CellContext) {
guard let context = context as? AppInfoCellContext else { return }
titleLabel.text = context.title
bodyLabel.text = context.body
}
@objc
func cardLongPressed() {
delegate?.appInfoCellToggleStaging()
}
}
|
80cf0e354a1bb9983ee91a2f8e37db58
| 34.117647 | 79 | 0.748409 | false | false | false | false |
mirego/taylor-ios
|
refs/heads/master
|
Taylor/UI/UIImage.swift
|
bsd-3-clause
|
1
|
// Copyright (c) 2016, Mirego
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// - Neither the name of the Mirego nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import UIKit
public extension UIImage
{
@available(*, deprecated, message: "Use image(from: color) instead")
class func imageWithTintColor(_ color: UIColor) -> UIImage? {
return UIImage.image(from: color)
}
/**
Creates a new UIImage with the specified tint color.
- parameter color: The image tint color
- returns: New instance of UIImage
*/
class func image(from color: UIColor?) -> UIImage? {
if let color = color {
let rect = CGRect(origin: CGPoint.zero, size: CGSize(width: 1, height: 1))
UIGraphicsBeginImageContext(rect.size)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
return nil
}
/**
Creates a new instance of the image using the specified tint color.
- parameter color: The image tint color
- returns: New instance of UIImage
*/
func imageWithTintColor(_ color: UIColor) -> UIImage? {
let sourceImage = withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, sourceImage.scale)
color.set()
sourceImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
/**
Creates a new instance of an image resized with the specified ratio
- parameter ratio: The desired ratio
- returns: New instance of UIImage
*/
func resize(ratio: CGFloat, isOpaque: Bool) -> UIImage? {
return resizeImage(to: size.applying(CGAffineTransform(scaleX: ratio, y: ratio)), isOpaque: isOpaque)
}
private func resizeImage(to size: CGSize, isOpaque: Bool) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, isOpaque, scale)
draw(in: CGRect(origin: .zero, size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
|
b8ceefeedad81318efb9a14741b2dfe0
| 39.147368 | 109 | 0.701101 | false | false | false | false |
ceecer1/open-muvr
|
refs/heads/master
|
ios/Lift/DemoSessionController.swift
|
apache-2.0
|
5
|
import Foundation
struct DataFile {
var path: String
var size: NSNumber
var name: String
}
class DemoSessionTableModel : NSObject, UITableViewDataSource {
private var dataFiles: [DataFile]
init(muscleGroupKeys: [String]) {
dataFiles = NSBundle.mainBundle().pathsForResourcesOfType(".dat", inDirectory: nil)
.map { p -> String in return p as String }
.filter { p in return !muscleGroupKeys.filter { k in return p.lastPathComponent.hasPrefix(k) }.isEmpty }
.map { path in
let attrs = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: nil)!
let size: NSNumber = attrs[NSFileSize] as NSNumber
return DataFile(path: path, size: size, name: path.lastPathComponent)
}
super.init()
}
// MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataFiles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let data = dataFiles[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("default") as UITableViewCell
cell.textLabel!.text = data.name
let fmt = NSNumberFormatter()
fmt.numberStyle = NSNumberFormatterStyle.DecimalStyle
let sizeString = fmt.stringFromNumber(data.size)!
cell.detailTextLabel!.text = "\(sizeString) B"
return cell
}
func filePathAtIndexPath(indexPath: NSIndexPath) -> String? {
return dataFiles[indexPath.row].path
}
}
class DemoSessionController : UIViewController, UITableViewDelegate, ExerciseSessionSettable {
@IBOutlet var tableView: UITableView!
@IBOutlet var stopSessionButton: UIBarButtonItem!
private var tableModel: DemoSessionTableModel?
private var session: ExerciseSession?
private var timer: NSTimer?
private var startTime: NSDate?
// MARK: main
override func viewWillDisappear(animated: Bool) {
timer!.invalidate()
navigationItem.prompt = nil
session?.end(const(()))
}
@IBAction
func stopSession() {
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Really?"
stopSessionButton.tag = 3
} else {
navigationItem.prompt = nil
navigationController!.popToRootViewControllerAnimated(true)
}
}
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = tableModel!
stopSessionButton.title = "Stop"
stopSessionButton.tag = 0
startTime = NSDate()
tabBarController?.tabBar.hidden = true
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true)
}
func tick() {
let elapsed = Int(NSDate().timeIntervalSinceDate(self.startTime!))
let minutes: Int = elapsed / 60
let seconds: Int = elapsed - minutes * 60
navigationItem.prompt = NSString(format: "Elapsed %d:%02d", minutes, seconds)
stopSessionButton.tag -= 1
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Stop"
}
}
// MARK: ExerciseSessionSettable
func setExerciseSession(session: ExerciseSession) {
self.session = session
tableModel = DemoSessionTableModel(muscleGroupKeys: session.props.muscleGroupKeys)
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
fatalError("This needs work")
// let path = tableModel!.filePathAtIndexPath(indexPath)
// let data = NSFileManager.defaultManager().contentsAtPath(path!)!
// let mp = MutableMultiPacket().append(DeviceInfo.Location.Wrist, data: data)
// session?.submitData(mp, const(()))
// tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
|
98975de7440305b9eea2497b3cb65a89
| 34.922414 | 119 | 0.654345 | false | false | false | false |
sora0077/LayoutKit
|
refs/heads/master
|
LayoutKitDemo/NormalSection.swift
|
mit
|
1
|
//
// NormalSection.swift
// LayoutKit
//
// Created by 林 達也 on 2015/01/15.
// Copyright (c) 2015年 林 達也. All rights reserved.
//
import UIKit
import LayoutKit
class NormalSection<T: UITableViewHeaderFooterView>: TableHeaderFooter<T> {
private let title: String
init(title: String, height: CGFloat = 40) {
self.title = title
super.init()
self.size.height = height
}
override func viewWillAppear() {
self.renderer?.contentView.backgroundColor = UIColor.blueColor()
// self.renderer?.textLabel.text = self.title
}
}
|
22088c8dac54fc875a1f1b07c9e13a95
| 17.903226 | 75 | 0.651877 | false | false | false | false |
zisko/swift
|
refs/heads/master
|
stdlib/public/core/StringObject.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// TODO: Comments. Supposed to abstract bit-twiddling operations. Meant to be a
// completely transparent struct. That is, it's just a trivial encapsulation to
// host many operations that would otherwise be scattered throughout StringGuts
// implementation.
//
@_fixed_layout
public // @testable
struct _StringObject {
// TODO: Proper built-in string object support.
#if arch(i386) || arch(arm)
// BridgeObject lacks support for tagged pointers on 32-bit platforms, and
// there are no free bits available to implement it. We use a single-word
// enum instead, with an additional word for holding tagged values and (in the
// non-tagged case) spilled flags.
@_fixed_layout
@_versioned
internal enum _Variant {
case strong(AnyObject) // _bits stores flags
case unmanagedSingleByte // _bits is the start address
case unmanagedDoubleByte // _bits is the start address
case smallSingleByte // _bits is the payload
case smallDoubleByte // _bits is the payload
// TODO small strings
}
@_versioned
internal
var _variant: _Variant
@_versioned
internal
var _bits: UInt
#else
// On 64-bit platforms, we use BridgeObject for now. This might be very
// slightly suboptimal and different than hand-optimized bit patterns, but
// provides us the runtime functionality we want.
@_versioned
internal
var _object: Builtin.BridgeObject
#endif
#if arch(i386) || arch(arm)
@_versioned
@_inlineable
@inline(__always)
internal
init(_ variant: _Variant, _ bits: UInt) {
self._variant = variant
self._bits = bits
_invariantCheck()
}
#else
@_versioned
@_inlineable
@inline(__always)
internal
init(_ object: Builtin.BridgeObject) {
self._object = object
_invariantCheck()
}
#endif
}
extension _StringObject {
#if arch(i386) || arch(arm)
public typealias _RawBitPattern = UInt64
#else
public typealias _RawBitPattern = UInt
#endif
@_versioned
@_inlineable
internal
var rawBits: _RawBitPattern {
@inline(__always)
get {
#if arch(i386) || arch(arm)
let variantBits: UInt = Builtin.reinterpretCast(_variant)
return _RawBitPattern(_bits) &<< 32 | _RawBitPattern(variantBits)
#else
return Builtin.reinterpretCast(_object)
#endif
}
}
@_versioned
@_inlineable
@inline(__always)
// TODO: private
internal
init(taggedRawBits: _RawBitPattern) {
#if arch(i386) || arch(arm)
self.init(
Builtin.reinterpretCast(UInt(truncatingIfNeeded: taggedRawBits)),
UInt(truncatingIfNeeded: taggedRawBits &>> 32))
#else
self.init(_bridgeObject(fromTagged: taggedRawBits))
_sanityCheck(self.isValue)
#endif
}
@_versioned
@_inlineable
@inline(__always)
// TODO: private
internal
init(nonTaggedRawBits: _RawBitPattern) {
#if arch(i386) || arch(arm)
self.init(
Builtin.reinterpretCast(UInt(truncatingIfNeeded: nonTaggedRawBits)),
UInt(truncatingIfNeeded: nonTaggedRawBits &>> 32))
#else
self.init(Builtin.reinterpretCast(nonTaggedRawBits))
_sanityCheck(!self.isValue)
#endif
}
// For when you need to hack around ARC. Note that by using this initializer,
// we are giving up on compile-time constant folding of ARC of values. Thus,
// this should only be called from the callee of a non-inlineable function
// that has no knowledge of the value-ness of the object.
@_versioned
@_inlineable
@inline(__always)
// TODO: private
internal
init(noReallyHereAreTheRawBits bits: _RawBitPattern) {
#if arch(i386) || arch(arm)
self.init(
Builtin.reinterpretCast(UInt(truncatingIfNeeded: bits)),
UInt(truncatingIfNeeded: bits &>> 32))
#else
self.init(Builtin.reinterpretCast(bits))
#endif
}
}
// ## _StringObject bit layout
//
// x86-64 and arm64: (one 64-bit word)
// +---+---+---|---+------+----------------------------------------------------+
// + t | v | o | w | uuuu | payload (56 bits) |
// +---+---+---|---+------+----------------------------------------------------+
// msb lsb
//
// i386 and arm: (two 32-bit words)
// _variant _bits
// +------------------------------------+ +------------------------------------+
// + .strong(AnyObject) | | v | o | w | unused (29 bits) |
// +------------------------------------+ +------------------------------------+
// + .unmanaged{Single,Double}Byte | | start address (32 bits) |
// +------------------------------------+ +------------------------------------+
// + .small{Single,Double}Byte | | payload (32 bits) |
// +------------------------------------+ +------------------------------------+
// msb lsb msb lsb
//
// where t: is-a-value, i.e. a tag bit that says not to perform ARC
// v: sub-variant bit, i.e. set for isCocoa or isSmall
// o: is-opaque, i.e. opaque vs contiguously stored strings
// w: width indicator bit (0: ASCII, 1: UTF-16)
// u: unused bits
//
// payload is:
// isNative: the native StringStorage object
// isCocoa: the Cocoa object
// isOpaque & !isCocoa: the _OpaqueString object
// isUnmanaged: the pointer to code units
// isSmall: opaque bits used for inline storage // TODO: use them!
//
extension _StringObject {
#if arch(i386) || arch(arm)
@_versioned
@_inlineable
internal
static var _isCocoaBit: UInt {
@inline(__always)
get {
return 0x8000_0000
}
}
@_versioned
@_inlineable
internal
static var _isOpaqueBit: UInt {
@inline(__always)
get {
return 0x4000_0000
}
}
@_versioned
@_inlineable
internal
static var _twoByteBit: UInt {
@inline(__always)
get {
return 0x2000_0000
}
}
#else // !(arch(i386) || arch(arm))
@_versioned
@_inlineable
internal
static var _isValueBit: UInt {
@inline(__always)
get {
// NOTE: deviating from ObjC tagged pointer bits, as we just want to avoid
// swift runtime management, and top bit suffices for that.
return 0x80_00_0000_0000_0000
}
}
// After deciding isValue, which of the two variants (on both sides) are we.
// That is, native vs objc or unsafe vs small.
@_versioned
@_inlineable
internal
static var _subVariantBit: UInt {
@inline(__always)
get {
return 0x40_00_0000_0000_0000
}
}
@_versioned
@_inlineable
internal
static var _isOpaqueBit: UInt {
@inline(__always)
get {
return 0x20_00_0000_0000_0000
}
}
@_versioned
@_inlineable
internal
static var _twoByteBit: UInt {
@inline(__always)
get {
return 0x10_00_0000_0000_0000
}
}
// There are 4 sub-variants depending on the isValue and subVariant bits
@_versioned
@_inlineable
internal
static var _variantMask: UInt {
@inline(__always)
get { return UInt(Builtin.stringObjectOr_Int64(
_isValueBit._value, _subVariantBit._value)) }
}
@_versioned
@_inlineable
internal
static var _payloadMask: UInt {
@inline(__always)
get {
return 0x00FF_FFFF_FFFF_FFFF
}
}
@_versioned
@_inlineable
internal
var _variantBits: UInt {
@inline(__always)
get {
return rawBits & _StringObject._variantMask
}
}
#endif // arch(i386) || arch(arm)
@_versioned
@_inlineable
internal
var referenceBits: UInt {
@inline(__always)
get {
#if arch(i386) || arch(arm)
guard case let .strong(object) = _variant else {
_sanityCheckFailure("internal error: expected a non-tagged String")
}
return Builtin.reinterpretCast(object)
#else
_sanityCheck(isNative || isCocoa)
return rawBits & _StringObject._payloadMask
#endif
}
}
@_versioned
@_inlineable
internal
var payloadBits: UInt {
@inline(__always)
get {
#if arch(i386) || arch(arm)
if case .strong(_) = _variant {
_sanityCheckFailure("internal error: expected a tagged String")
}
return _bits
#else
_sanityCheck(!isNative && !isCocoa)
return rawBits & _StringObject._payloadMask
#endif
}
}
}
//
// Empty strings
//
@_versioned // FIXME(sil-serialize-all)
internal var _emptyStringStorage: UInt32 = 0
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _emptyStringAddressBits: UInt {
let p = UnsafeRawPointer(Builtin.addressof(&_emptyStringStorage))
return UInt(bitPattern: p)
}
extension _StringObject {
#if arch(i386) || arch(arm)
@_versioned
@_inlineable
internal
var isEmptySingleton: Bool {
guard _bits == _emptyStringAddressBits else { return false }
switch _variant {
case .unmanagedSingleByte, .unmanagedDoubleByte:
return true
default:
return false
}
}
@_versioned
@_inlineable
@inline(__always)
internal
init() {
self.init(.unmanagedSingleByte, _emptyStringAddressBits)
}
#else
@_versioned
@_inlineable
internal
static var _emptyStringBitPattern: UInt {
@inline(__always)
get { return UInt(Builtin.stringObjectOr_Int64(
_isValueBit._value, _emptyStringAddressBits._value)) }
}
@_versioned
@_inlineable
internal
var isEmptySingleton: Bool {
@inline(__always)
get { return rawBits == _StringObject._emptyStringBitPattern }
}
@_versioned
@_inlineable
@inline(__always)
internal
init() {
self.init(taggedRawBits: _StringObject._emptyStringBitPattern)
}
#endif
}
//
// Private convenience helpers to layer on top of BridgeObject
//
// TODO: private!
//
extension _StringObject {
@_versioned
@_inlineable
internal // TODO: private!
var asNativeObject: AnyObject {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(let object):
_sanityCheck(_bits & _StringObject._isCocoaBit == 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(type(of: object)))
return object
default:
_sanityCheckFailure("asNativeObject on unmanaged _StringObject")
}
#else
_sanityCheck(isNative)
_sanityCheck(
_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(referenceBits) as AnyObject)))
return Builtin.reinterpretCast(referenceBits)
#endif
}
}
#if _runtime(_ObjC)
@_versioned
@_inlineable
internal // TODO: private!
var asCocoaObject: _CocoaString {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(let object):
_sanityCheck(_bits & _StringObject._isCocoaBit != 0)
_sanityCheck(!_usesNativeSwiftReferenceCounting(type(of: object)))
return object
default:
_sanityCheckFailure("asCocoaObject on unmanaged _StringObject")
}
#else
_sanityCheck(isCocoa)
_sanityCheck(
!_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(referenceBits) as AnyObject)))
return Builtin.reinterpretCast(referenceBits)
#endif
}
}
#endif
@_versioned
@_inlineable
internal // TODO: private!
var asOpaqueObject: _OpaqueString {
@inline(__always)
get {
_sanityCheck(isOpaque)
let object = Builtin.reinterpretCast(referenceBits) as AnyObject
return object as! _OpaqueString
}
}
@_versioned
@_inlineable
internal
var asUnmanagedRawStart: UnsafeRawPointer {
@inline(__always)
get {
_sanityCheck(isUnmanaged)
#if arch(i386) || arch(arm)
return UnsafeRawPointer(bitPattern: _bits)._unsafelyUnwrappedUnchecked
#else
return UnsafeRawPointer(
bitPattern: payloadBits
)._unsafelyUnwrappedUnchecked
#endif
}
}
}
//
// Queries on a StringObject
//
extension _StringObject {
//
// Determine which of the 4 major variants we are
//
@_versioned
@_inlineable
internal
var isNative: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
guard case .strong(_) = _variant else { return false }
return _bits & _StringObject._isCocoaBit == 0
#else
return _variantBits == 0
#endif
}
}
@_versioned
@_inlineable
internal
var isCocoa: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
guard case .strong(_) = _variant else { return false }
return _bits & _StringObject._isCocoaBit != 0
#else
return _variantBits == _StringObject._subVariantBit
#endif
}
}
public // @testable
var owner: AnyObject? { // For testing only
#if arch(i386) || arch(arm)
guard case .strong(let object) = _variant else { return nil }
return object
#else
if _fastPath(isNative || isCocoa) {
return Builtin.reinterpretCast(referenceBits)
}
return nil
#endif
}
@_versioned
@_inlineable
internal
var isValue: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(_): return false
default:
return true
}
#else
return rawBits & _StringObject._isValueBit != 0
#endif
}
}
@_versioned
@_inlineable
internal
var isUnmanaged: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .unmanagedSingleByte, .unmanagedDoubleByte:
return true
default:
return false
}
#else
return _variantBits == _StringObject._isValueBit
#endif
}
}
@_versioned
@_inlineable
internal
var isSmall: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .smallSingleByte, .smallDoubleByte:
return true
default:
return false
}
#else
return _variantBits == _StringObject._variantMask
#endif
}
}
//
// Frequently queried properties
//
@_versioned
@_inlineable
internal
var isContiguous: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(_):
return _bits & _StringObject._isOpaqueBit == 0
case .unmanagedSingleByte, .unmanagedDoubleByte:
return true
case .smallSingleByte, .smallDoubleByte:
return false
}
#else
return rawBits & _StringObject._isOpaqueBit == 0
#endif
}
}
@_versioned
@_inlineable
internal
var isOpaque: Bool {
@inline(__always)
get { return !isContiguous }
}
@_versioned
@_inlineable
internal
var isContiguousCocoa: Bool {
@inline(__always)
get { return isContiguous && isCocoa }
}
@_versioned
@_inlineable
internal
var isNoncontiguousCocoa: Bool {
@inline(__always)
get { return isCocoa && isOpaque }
}
@_inlineable
public // @testable
var isSingleByte: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(_):
return _bits & _StringObject._twoByteBit == 0
case .unmanagedSingleByte, .smallSingleByte:
return true
case .unmanagedDoubleByte, .smallDoubleByte:
return false
}
#else
return rawBits & _StringObject._twoByteBit == 0
#endif
}
}
@_inlineable
public // @testable
var byteWidth: Int {
@inline(__always)
get { return isSingleByte ? 1 : 2 }
}
@_versioned
@_inlineable
var bitWidth: Int {
@inline(__always)
get { return byteWidth &<< 3 }
}
@_inlineable
public // @testable
var isContiguousASCII: Bool {
@inline(__always)
get { return isContiguous && isSingleByte }
}
@_inlineable
public // @testable
var isContiguousUTF16: Bool {
@inline(__always)
get { return isContiguous && !isSingleByte }
}
@_versioned
@_inlineable
@inline(__always)
internal
func nativeStorage<CodeUnit>(
of codeUnit: CodeUnit.Type = CodeUnit.self
) -> _SwiftStringStorage<CodeUnit>
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(isNative)
_sanityCheck(CodeUnit.bitWidth == self.bitWidth)
// TODO: Is this the way to do it?
return _unsafeUncheckedDowncast(
asNativeObject, to: _SwiftStringStorage<CodeUnit>.self)
}
@_inlineable
public // @testable
var nativeRawStorage: _SwiftRawStringStorage {
@inline(__always) get {
_sanityCheck(isNative)
return _unsafeUncheckedDowncast(
asNativeObject, to: _SwiftRawStringStorage.self)
}
}
}
extension _StringObject {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func _invariantCheck() {
#if INTERNAL_CHECKS_ENABLED
_sanityCheck(MemoryLayout<_StringObject>.size == 8)
_sanityCheck(isContiguous || isOpaque)
_sanityCheck(isOpaque || isContiguousASCII || isContiguousUTF16)
if isNative {
_sanityCheck(isContiguous)
if isSingleByte {
_sanityCheck(isContiguousASCII)
_sanityCheck(asNativeObject is _SwiftStringStorage<UInt8>)
} else {
_sanityCheck(asNativeObject is _SwiftStringStorage<UInt16>)
}
} else if isUnmanaged {
_sanityCheck(isContiguous)
_sanityCheck(payloadBits > 0) // TODO: inside address space
} else if isCocoa {
#if _runtime(_ObjC)
let object = asCocoaObject
_sanityCheck(
!_usesNativeSwiftReferenceCounting(type(of: object as AnyObject)))
#else
_sanityCheckFailure("Cocoa objects aren't supported on this platform")
#endif
} else if isSmall {
_sanityCheck(isOpaque)
} else {
fatalError("Unimplemented string form")
}
#endif
}
}
//
// Conveniently construct, tag, flag, etc. StringObjects
//
extension _StringObject {
@_versioned
@_inlineable
@inline(__always)
internal
init(
_payloadBits: UInt,
isValue: Bool,
isSmallOrObjC: Bool,
isOpaque: Bool,
isTwoByte: Bool
) {
#if arch(i386) || arch(arm)
var variant: _Variant
var bits: UInt
if isValue {
if isSmallOrObjC {
_sanityCheck(isOpaque)
self.init(
isTwoByte ? .smallDoubleByte : .smallSingleByte,
_payloadBits)
} else {
_sanityCheck(!isOpaque)
self.init(
isTwoByte ? .unmanagedDoubleByte : .unmanagedSingleByte,
_payloadBits)
}
} else {
var bits: UInt = 0
if isSmallOrObjC {
bits |= _StringObject._isCocoaBit
}
if isOpaque {
bits |= _StringObject._isOpaqueBit
}
if isTwoByte {
bits |= _StringObject._twoByteBit
}
self.init(.strong(Builtin.reinterpretCast(_payloadBits)), bits)
}
#else
_sanityCheck(_payloadBits & ~_StringObject._payloadMask == 0)
var rawBits = _payloadBits & _StringObject._payloadMask
if isValue {
var rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBits._value, _StringObject._isValueBit._value)
if isSmallOrObjC {
rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBitsBuiltin, _StringObject._subVariantBit._value)
}
if isOpaque {
rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBitsBuiltin, _StringObject._isOpaqueBit._value)
}
if isTwoByte {
rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBitsBuiltin, _StringObject._twoByteBit._value)
}
rawBits = UInt(rawBitsBuiltin)
self.init(taggedRawBits: rawBits)
} else {
if isSmallOrObjC {
rawBits |= _StringObject._subVariantBit
}
if isOpaque {
rawBits |= _StringObject._isOpaqueBit
}
if isTwoByte {
rawBits |= _StringObject._twoByteBit
}
self.init(nonTaggedRawBits: rawBits)
}
#endif
_sanityCheck(isSmall == (isValue && isSmallOrObjC))
_sanityCheck(isUnmanaged == (isValue && !isSmallOrObjC))
_sanityCheck(isCocoa == (!isValue && isSmallOrObjC))
_sanityCheck(isNative == (!isValue && !isSmallOrObjC))
}
@_versioned
@_inlineable
@inline(__always)
internal
init(
_someObject: AnyObject,
isCocoa: Bool,
isContiguous: Bool,
isSingleByte: Bool
) {
defer { _fixLifetime(_someObject) }
self.init(
_payloadBits: Builtin.reinterpretCast(_someObject),
isValue: false,
isSmallOrObjC: isCocoa,
isOpaque: !isContiguous,
isTwoByte: !isSingleByte)
}
@_versioned
@_inlineable
@inline(__always)
internal
init(nativeObject: AnyObject, isSingleByte: Bool) {
self.init(
_someObject: nativeObject,
isCocoa: false,
isContiguous: true,
isSingleByte: isSingleByte)
}
#if _runtime(_ObjC)
@_versioned
@_inlineable
@inline(__always)
internal
init(cocoaObject: AnyObject, isSingleByte: Bool, isContiguous: Bool) {
// TODO: is it possible to sanity check? maybe `is NSObject`?
self.init(
_someObject: cocoaObject,
isCocoa: true,
isContiguous: isContiguous,
isSingleByte: isSingleByte)
}
#else
@_versioned
@_inlineable
@inline(__always)
internal
init<S: _OpaqueString>(opaqueString: S) {
self.init(
_someObject: opaqueString,
isCocoa: false,
isContiguous: false,
isSingleByte: false)
}
#endif
@_versioned
@_inlineable
@inline(__always)
internal
init(smallStringPayload: UInt, isSingleByte: Bool) {
self.init(
_payloadBits: smallStringPayload,
isValue: true,
isSmallOrObjC: true,
isOpaque: true,
isTwoByte: !isSingleByte)
}
@_versioned
@_inlineable
@inline(__always)
internal
init<CodeUnit>(
unmanaged: UnsafePointer<CodeUnit>
) where CodeUnit : FixedWidthInteger & UnsignedInteger {
self.init(
_payloadBits: UInt(bitPattern: unmanaged),
isValue: true,
isSmallOrObjC: false,
isOpaque: false,
isTwoByte: CodeUnit.bitWidth == 16)
_sanityCheck(isSingleByte == (CodeUnit.bitWidth == 8))
}
@_versioned
@_inlineable
@inline(__always)
internal
init<CodeUnit>(
_ storage: _SwiftStringStorage<CodeUnit>
) where CodeUnit : FixedWidthInteger & UnsignedInteger {
self.init(nativeObject: storage, isSingleByte: CodeUnit.bitWidth == 8)
_sanityCheck(isSingleByte == (CodeUnit.bitWidth == 8))
}
}
|
fa7cd06f2877bb4032b14fce66c08de5
| 23.598263 | 80 | 0.625292 | false | false | false | false |
Moya/ReactiveMoya
|
refs/heads/master
|
Example/ReactiveMoyaExample/ReactiveMoyaViewController.swift
|
mit
|
3
|
import UIKit
import ReactiveCocoa
import Result
import Moya
let ReactiveGithubProvider = ReactiveCocoaMoyaProvider<Github>()
class ReactiveMoyaViewController: UITableViewController, UIGestureRecognizerDelegate {
let repos = MutableProperty<NSArray>(NSArray())
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
// MARK: - API
func downloadRepositories(username: String) {
ReactiveGithubProvider.requestJSONArray(.UserRepositories(username))
|> start(error: { (error: NSError) in
self.showErrorAlert("Github Fetch", error: error)
},
next: { (result: NSArray) in
self.repos.put(result)
self.title = "\(username)'s repos"
})
}
func downloadZen() {
ReactiveGithubProvider.requestString(.Zen)
|> start(error: { (error: NSError) in
self.showErrorAlert("Zen", error: error)
},
next: { (string: String) in
self.showAlert("Zen", message: string)
})
}
// MARK: - Actions
// MARK: IBActions
@IBAction
func searchPressed(sender: UIBarButtonItem) {
showInputPrompt("Username", message: "Enter a github username", action: { username in
self.downloadRepositories(username)
})
}
@IBAction
func zenPressed(sender: UIBarButtonItem) {
downloadZen()
}
// MARK: - Delegates
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repos.value.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
if let object = repos.value[indexPath.row] as? NSDictionary {
cell.textLabel?.text = object["name"] as? String
}
return cell
}
// MARK: - Setup
private func setup() {
self.navigationController?.interactivePopGestureRecognizer.delegate = self
// When repos changes and is non-nil, reload the table view
repos.producer
|> start(next: { _ in
self.tableView.reloadData()
})
// Download all repositories for "justinmakaila"
downloadRepositories("justinmakaila")
}
}
|
3bc73085e48441a6045f7ce38f0a7633
| 29.764706 | 118 | 0.590822 | false | false | false | false |
Jubilant-Appstudio/Scuba
|
refs/heads/master
|
EasyPass/Carthage/Checkouts/IQKeyboardManager/IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift
|
mit
|
2
|
//
// IQToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/** @abstract IQToolbar for IQKeyboardManager. */
open class IQToolbar: UIToolbar , UIInputViewAudioFeedback {
private static var _classInitialize: Void = classInitialize()
private class func classInitialize() {
let appearanceProxy = self.appearance()
appearanceProxy.barTintColor = nil
let positions : [UIBarPosition] = [.any,.bottom,.top,.topAttached];
for position in positions {
appearanceProxy.setBackgroundImage(nil, forToolbarPosition: position, barMetrics: .default)
appearanceProxy.setShadowImage(nil, forToolbarPosition: .any)
}
//Background color
appearanceProxy.backgroundColor = nil
}
/**
Previous bar button of toolbar.
*/
private var privatePreviousBarButton: IQBarButtonItem?
open var previousBarButton : IQBarButtonItem {
get {
if privatePreviousBarButton == nil {
privatePreviousBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
privatePreviousBarButton?.accessibilityLabel = "Toolbar Previous Button"
}
return privatePreviousBarButton!
}
set (newValue) {
privatePreviousBarButton = newValue
}
}
/**
Next bar button of toolbar.
*/
private var privateNextBarButton: IQBarButtonItem?
open var nextBarButton : IQBarButtonItem {
get {
if privateNextBarButton == nil {
privateNextBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
privateNextBarButton?.accessibilityLabel = "Toolbar Next Button"
}
return privateNextBarButton!
}
set (newValue) {
privateNextBarButton = newValue
}
}
/**
Title bar button of toolbar.
*/
private var privateTitleBarButton: IQTitleBarButtonItem?
open var titleBarButton : IQTitleBarButtonItem {
get {
if privateTitleBarButton == nil {
privateTitleBarButton = IQTitleBarButtonItem(title: nil)
privateTitleBarButton?.accessibilityLabel = "Toolbar Title Button"
}
return privateTitleBarButton!
}
set (newValue) {
privateTitleBarButton = newValue
}
}
/**
Done bar button of toolbar.
*/
private var privateDoneBarButton: IQBarButtonItem?
open var doneBarButton : IQBarButtonItem {
get {
if privateDoneBarButton == nil {
privateDoneBarButton = IQBarButtonItem(title: nil, style: .done, target: nil, action: nil)
privateDoneBarButton?.accessibilityLabel = "Toolbar Done Button"
}
return privateDoneBarButton!
}
set (newValue) {
privateDoneBarButton = newValue
}
}
override init(frame: CGRect) {
_ = IQToolbar._classInitialize
super.init(frame: frame)
sizeToFit()
autoresizingMask = UIViewAutoresizing.flexibleWidth
tintColor = UIColor.black
self.isTranslucent = true
}
required public init?(coder aDecoder: NSCoder) {
_ = IQToolbar._classInitialize
super.init(coder: aDecoder)
sizeToFit()
autoresizingMask = UIViewAutoresizing.flexibleWidth
tintColor = UIColor.black
self.isTranslucent = true
}
override open func sizeThatFits(_ size: CGSize) -> CGSize {
var sizeThatFit = super.sizeThatFits(size)
sizeThatFit.height = 44
return sizeThatFit
}
override open var tintColor: UIColor! {
didSet {
if let unwrappedItems = items {
for item in unwrappedItems {
item.tintColor = tintColor
}
}
}
}
override open var barStyle: UIBarStyle {
didSet {
if barStyle == .default {
titleBarButton.selectableTextColor = UIColor.init(red: 0.0, green: 0.5, blue: 1.0, alpha: 1)
} else {
titleBarButton.selectableTextColor = UIColor.yellow
}
}
}
override open func layoutSubviews() {
super.layoutSubviews()
//If running on Xcode9 (iOS11) only then we'll validate for iOS version, otherwise for older versions of Xcode (iOS10 and below) we'll just execute the tweak
#if swift(>=3.2)
if #available(iOS 11, *) {
return
} else {
var leftRect = CGRect.null
var rightRect = CGRect.null
var isTitleBarButtonFound = false
let sortedSubviews = self.subviews.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in
let x1 = view1.frame.minX
let y1 = view1.frame.minY
let x2 = view2.frame.minX
let y2 = view2.frame.minY
if x1 != x2 {
return x1 < x2
} else {
return y1 < y2
}
})
for barButtonItemView in sortedSubviews {
if isTitleBarButtonFound == true {
rightRect = barButtonItemView.frame
break
} else if type(of: barButtonItemView) === UIView.self {
isTitleBarButtonFound = true
//If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem)
} else if barButtonItemView.isKind(of: UIControl.self) == true {
leftRect = barButtonItemView.frame
}
}
var x : CGFloat = 16
if (leftRect.isNull == false) {
x = leftRect.maxX + 16
}
let width : CGFloat = self.frame.width - 32 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
if let unwrappedItems = items {
for item in unwrappedItems {
if let newItem = item as? IQTitleBarButtonItem {
let titleRect = CGRect(x: x, y: 0, width: width, height: self.frame.size.height)
newItem.customView?.frame = titleRect
break
}
}
}
}
#else
var leftRect = CGRect.null
var rightRect = CGRect.null
var isTitleBarButtonFound = false
let sortedSubviews = self.subviews.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in
let x1 = view1.frame.minX
let y1 = view1.frame.minY
let x2 = view2.frame.minX
let y2 = view2.frame.minY
if x1 != x2 {
return x1 < x2
} else {
return y1 < y2
}
})
for barButtonItemView in sortedSubviews {
if isTitleBarButtonFound == true {
rightRect = barButtonItemView.frame
break
} else if type(of: barButtonItemView) === UIView.self {
isTitleBarButtonFound = true
//If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem)
} else if barButtonItemView.isKind(of: UIControl.self) == true {
leftRect = barButtonItemView.frame
}
}
var x : CGFloat = 16
if (leftRect.isNull == false) {
x = leftRect.maxX + 16
}
let width : CGFloat = self.frame.width - 32 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
if let unwrappedItems = items {
for item in unwrappedItems {
if let newItem = item as? IQTitleBarButtonItem {
let titleRect = CGRect(x: x, y: 0, width: width, height: self.frame.size.height)
newItem.customView?.frame = titleRect
break
}
}
}
#endif
}
open var enableInputClicksWhenVisible: Bool {
return true
}
}
|
61df2d4096c06ea61e956b63a06497e1
| 32.479452 | 165 | 0.561477 | false | false | false | false |
quire-io/SwiftyChrono
|
refs/heads/master
|
Tests/SwiftyChronoTests/TestUtil.swift
|
mit
|
1
|
//
// TestUtil.swift
// SwiftyChrono
//
// Created by Jerry Chen on 1/23/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
import XCTest
import JavaScriptCore
extension XCTestCase {
func ok(_ result: Bool) {
XCTAssert(result)
}
func ok(_ result: Bool, _ message: String) {
XCTAssert(result, message)
}
public struct JSON {
static func stringify(_ value: Any) -> String {
if let data = try? JSONSerialization.data(withJSONObject: value, options: .prettyPrinted) {
return String(data: data, encoding: String.Encoding.utf8) ?? ""
} else {
return ""
}
}
}
}
extension Chrono {
func parse(_ text: String, _ refDate: Date = Date(), _ opt: [OptionType: Int] = [:]) -> [ParsedResult] {
return parse(text: text, refDate: refDate, opt: opt)
}
}
extension Date {
init(valueString: String) {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" // ISO 8601
let date = dateFormatter.date(from: valueString)
if let date = date {
self = date
} else {
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"; //RFC2822-Format
self = dateFormatter.date(from: valueString) ?? Date()
}
}
/// ATTENTION: this is Javascript compatible init function.
/// the range of month is between 0 ~ 11
init(_ year: Int, _ month: Int, _ date: Int = 1, _ hours: Int = 0, _ minutes: Int = 0, _ seconds: Int = 0, _ milliseconds: Int = 0) {
let component = DateComponents(calendar: cal, timeZone: TimeZone.current, year: year, month: month + 1, day: date, hour: hours, minute: minutes, second: seconds, nanosecond: millisecondsToNanoSeconds(milliseconds))
self = component.date ?? Date()
}
static let iso8601Formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
var iso8601: String {
return Date.iso8601Formatter.string(from: self)
}
}
extension Array {
var length: Int {
return Int(count)
}
}
extension String {
var dateFromISO8601: Date? {
return Date.iso8601Formatter.date(from: self)
}
}
//MARK: JS
@objc protocol JSParsedResult: JSExport {
var ref: Date { get }
var index: Int { get }
var text: String { get }
var start: JSParsedComponents { get }
var end: JSParsedComponents? { get }
}
@objc protocol JSParsedComponents: JSExport {
func date() -> Date
func get(_ key: String) -> Int
func isCertain(_ key: String) -> Bool
}
class TestParsedResult: NSObject, JSParsedResult {
private let parsedResult: ParsedResult
init(_ parsedResult: ParsedResult) {
self.parsedResult = parsedResult
}
var ref: Date { return parsedResult.ref }
var index: Int { return parsedResult.index }
var text: String { return parsedResult.text }
private var _start: JSParsedComponents? = nil
var start: JSParsedComponents {
if _start == nil {
_start = TestParsedComponents(parsedResult.start)
}
return _start!
}
private var _end: JSParsedComponents? = nil
var end: JSParsedComponents? {
if _end == nil { // will query every time if parsedResult.end is nil. but it's not a big deal in test case, we keep it simple.
_end = parsedResult.end != nil ? TestParsedComponents(parsedResult.end!) : nil
}
return _end
}
}
class TestParsedComponents: NSObject, JSParsedComponents {
private let parsedComponents: ParsedComponents
init(_ parsedComponents: ParsedComponents) {
self.parsedComponents = parsedComponents
}
func date() -> Date {
return parsedComponents.date
}
func get(_ key: String) -> Int {
return parsedComponents[keyToComponentUnit(key)] ?? 0
}
func isCertain(_ key: String) -> Bool {
return parsedComponents.isCertain(component: keyToComponentUnit(key))
}
}
private func keyToComponentUnit(_ key: String) -> ComponentUnit {
let k: ComponentUnit
switch key {
case "year":
k = .year
case "month":
k = .month
case "day":
k = .day
case "hour":
k = .hour
case "minute":
k = .minute
case "second":
k = .second
case "millisecond":
k = .millisecond
case "weekday":
k = .weekday
case "timezoneOffset":
fallthrough
case "timeZoneOffset":
k = .timeZoneOffset
case "meridiem":
k = .meridiem
default:
assert(false, "won't enter in this case...")
k = .year
}
return k
}
|
0131418739314b99c89beda6f26661ed
| 26.852459 | 222 | 0.606828 | false | false | false | false |
hsavit1/LeetCode-Solutions-in-Swift
|
refs/heads/master
|
Solutions/Solutions/Hard/Hard_041_First_Missing_Positive.swift
|
mit
|
4
|
/*
https://leetcode.com/problems/first-missing-positive/
#41 First Missing Positive
Level: hard
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Inspired by @makuiyu at https://leetcode.com/discuss/24013/my-short-c-solution-o-1-space-and-o-n-time
*/
import Foundation
struct Hard_041_First_Missing_Positive {
static func firstMissingPositive(var nums: [Int]) -> Int {
for var i = 0; i < nums.count; i++ {
while nums[i] > 0 && nums[i] <= nums.count && nums[nums[i]-1] != nums[i] {
swap(&nums[i], &nums[nums[i]-1])
}
}
for var i = 0; i < nums.count; i++ {
if(nums[i] != i+1) {
return i + 1;
}
}
return nums.count + 1;
}
}
|
98511543dba8434d3d95d8327596b535
| 23.594595 | 101 | 0.578658 | false | false | false | false |
manavgabhawala/swift
|
refs/heads/master
|
test/SILGen/objc_witnesses.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
protocol Fooable {
func foo() -> String!
}
// Witnesses Fooable.foo with the original ObjC-imported -foo method .
extension Foo: Fooable {}
class Phoûx : NSObject, Fooable {
@objc func foo() -> String! {
return "phoûx!"
}
}
// witness for Foo.foo uses the foreign-to-native thunk:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T0So3FooC14objc_witnesses7FooableA2cDP3foo{{[_0-9a-zA-Z]*}}FTW
// CHECK: function_ref @_T0So3FooC3foo{{[_0-9a-zA-Z]*}}FTO
// *NOTE* We have an extra copy here for the time being right
// now. This will change once we teach SILGen how to not emit the
// extra copy.
//
// witness for Phoûx.foo uses the Swift vtable
// CHECK-LABEL: _T014objc_witnesses008Phox_xraC3foo{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[IN_ADDR:%.*]] :
// CHECK: [[STACK_SLOT:%.*]] = alloc_stack $Phoûx
// CHECK: copy_addr [[IN_ADDR]] to [initialization] [[STACK_SLOT]]
// CHECK: [[VALUE:%.*]] = load [take] [[STACK_SLOT]]
// CHECK: [[BORROWED_VALUE:%.*]] = begin_borrow [[VALUE]]
// CHECK: [[CLS_METHOD:%.*]] = class_method [[BORROWED_VALUE]] : $Phoûx, #Phoûx.foo!1
// CHECK: apply [[CLS_METHOD]]([[BORROWED_VALUE]])
// CHECK: end_borrow [[BORROWED_VALUE]] from [[VALUE]]
// CHECK: destroy_value [[VALUE]]
// CHECK: dealloc_stack [[STACK_SLOT]]
protocol Bells {
init(bellsOn: Int)
}
extension Gizmo : Bells {
}
// CHECK: sil hidden [transparent] [thunk] @_T0So5GizmoC14objc_witnesses5BellsA2cDP{{[_0-9a-zA-Z]*}}fCTW
// CHECK: bb0([[SELF:%[0-9]+]] : $*Gizmo, [[I:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick Gizmo.Type):
// CHECK: [[INIT:%[0-9]+]] = function_ref @_T0So5GizmoC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[I]], [[META]]) : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo>
// CHECK: switch_enum [[IUO_RESULT]]
// CHECK: bb2([[UNWRAPPED_RESULT:%.*]] : $Gizmo):
// CHECK: store [[UNWRAPPED_RESULT]] to [init] [[SELF]] : $*Gizmo
// Test extension of a native @objc class to conform to a protocol with a
// subscript requirement. rdar://problem/20371661
protocol Subscriptable {
subscript(x: Int) -> Any { get }
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T0So7NSArrayC14objc_witnesses13SubscriptableA2cDP9subscriptypSicfgTW : $@convention(witness_method) (Int, @in_guaranteed NSArray) -> @out Any {
// CHECK: function_ref @_T0So7NSArrayC9subscriptypSicfgTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any
// CHECK-LABEL: sil shared [thunk] @_T0So7NSArrayC9subscriptypSicfgTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any {
// CHECK: class_method [volatile] {{%.*}} : $NSArray, #NSArray.subscript!getter.1.foreign
extension NSArray: Subscriptable {}
// witness is a dynamic thunk:
protocol Orbital {
var quantumNumber: Int { get set }
}
class Electron : Orbital {
dynamic var quantumNumber: Int = 0
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T014objc_witnesses8ElectronCAA7OrbitalA2aDP13quantumNumberSifgTW
// CHECK-LABEL: sil shared [transparent] [thunk] @_T014objc_witnesses8ElectronC13quantumNumberSifgTD
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T014objc_witnesses8ElectronCAA7OrbitalA2aDP13quantumNumberSifsTW
// CHECK-LABEL: sil shared [transparent] [thunk] @_T014objc_witnesses8ElectronC13quantumNumberSifsTD
// witness is a dynamic thunk and is public:
public protocol Lepton {
var spin: Float { get }
}
public class Positron : Lepton {
public dynamic var spin: Float = 0.5
}
// CHECK-LABEL: sil [transparent] [fragile] [thunk] @_T014objc_witnesses8PositronCAA6LeptonA2aDP4spinSffgTW
// CHECK-LABEL: sil shared [transparent] [fragile] [thunk] @_T014objc_witnesses8PositronC4spinSffgTD
|
eeb0d3ec9a4a209d09d17ec73f7d43cd
| 40.193878 | 194 | 0.67674 | false | false | false | false |
melbrng/TrackApp
|
refs/heads/master
|
Track/Track/Track.swift
|
mit
|
1
|
//
// Track.swift
// TrackAppPrototype
//
// Created by Melissa Boring on 7/10/16.
// Copyright © 2016 melbo. All rights reserved.
//
import Foundation
import UIKit
import MapKit
class Track {
var trackImage = UIImage()
var trackName: String
var trackDescription: String
var trackUID: String?
var trackImagePath: String?
init(name: String, desc: String) {
self.trackName = name
self.trackDescription = desc
}
init(name: String, desc: String, image: UIImage, imagePath: String) {
self.trackName = name
self.trackDescription = desc
self.trackImage = image
self.trackImagePath = imagePath
}
init(name: String, desc: String, uid: String, imagePath: String) {
self.trackName = name
self.trackDescription = desc
self.trackUID = uid
self.trackImagePath = imagePath
}
}
|
ed41cfea09fc126e6c6daf1d1b3c1d75
| 21.825 | 73 | 0.631982 | false | false | false | false |
parkera/swift
|
refs/heads/master
|
test/SILOptimizer/Inputs/cross-module.swift
|
apache-2.0
|
2
|
import Submodule
@_implementationOnly import PrivateSubmodule
private enum PE<T> {
case A
case B(T)
}
public struct Container {
private final class Base {
}
@inline(never)
public func testclass<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testclass_gen<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
public func testenum<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testenum_gen<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
public init() { }
}
private class PrivateBase<T> {
var t: T
func foo() -> Int { return 27 }
init(_ t: T) { self.t = t }
}
private class PrivateDerived<T> : PrivateBase<T> {
override func foo() -> Int { return 28 }
}
@inline(never)
private func getClass<T>(_ t : T) -> PrivateBase<T> {
return PrivateDerived<T>(t)
}
@inline(never)
public func createClass<T>(_ t: T) -> Int {
return getClass(t).foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func createClass_gen<T>(_ t: T) -> Int {
return getClass(t).foo()
}
private struct PrivateError: Error { }
public func returnPrivateError<V>(_ v: V) -> Error {
return PrivateError()
}
struct InternalError: Error { }
public func returnInternalError<V>(_ v: V) -> Error {
return InternalError()
}
private protocol PrivateProtocol {
func foo() -> Int
}
open class OpenClass<T> {
public init() { }
@inline(never)
fileprivate func bar(_ t: T) {
print(t)
}
}
extension OpenClass {
@inline(never)
public func testit() -> Bool {
return self is PrivateProtocol
}
}
@inline(never)
public func checkIfClassConforms<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func checkIfClassConforms_gen<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
public func callClassMethod<T>(_ t: T) {
let k = OpenClass<T>()
k.bar(t)
}
extension Int : PrivateProtocol {
func foo() -> Int { return self }
}
@inline(never)
@_semantics("optimize.no.crossmodule")
private func printFooExistential(_ p: PrivateProtocol) {
print(p.foo())
}
@inline(never)
private func printFooGeneric<T: PrivateProtocol>(_ p: T) {
print(p.foo())
}
@inline(never)
public func callFoo<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFoo_gen<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
fileprivate protocol PrivateProto {
func foo()
}
public class FooClass: PrivateProto {
func foo() {
print(321)
}
}
final class Internalclass {
public var publicint: Int = 27
}
final public class Outercl {
var ic: Internalclass = Internalclass()
}
@inline(never)
public func classWithPublicProperty<T>(_ t: T) -> Int {
return createInternal().ic.publicint
}
@inline(never)
func createInternal() -> Outercl {
return Outercl()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
fileprivate func callProtocolFoo<T: PrivateProto>(_ t: T) {
t.foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFooViaConformance<T>(_ t: T) {
let c = FooClass()
callProtocolFoo(c)
}
@inline(never)
public func callGenericSubmoduleFunc<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callGenericSubmoduleFunc_gen<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
public func genericClosure<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func genericClosure_gen<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
struct Abc {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Myclass {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Derived : Myclass {
override var x: Int { return 29 }
override var y: Int { return 30 }
}
@inline(never)
func getStructKeypath<T>(_ t: T) -> KeyPath<Abc, Int> {
return \Abc.x
}
@inline(never)
public func useStructKeypath<T>(_ t: T) -> Int {
let abc = Abc()
return abc[keyPath: getStructKeypath(t)]
}
@inline(never)
func getClassKeypath<T>(_ t: T) -> KeyPath<Myclass, Int> {
return \Myclass.x
}
@inline(never)
public func useClassKeypath<T>(_ t: T) -> Int {
let c = Derived()
return c[keyPath: getClassKeypath(t)]
}
@inline(never)
func unrelated<U>(_ u: U) {
print(u)
}
@inline(never)
public func callUnrelated<T>(_ t: T) -> T {
unrelated(43)
return t
}
public func callImplementationOnly<T>(_ t: T) -> T {
let p = PrivateStr(i: 27)
print(p.test())
return t
}
public let globalLet = 529387
|
c814538301af29604d8697a067169cde
| 17.431655 | 59 | 0.653396 | false | false | false | false |
vgatto/protobuf-swift
|
refs/heads/master
|
src/ProtocolBuffers/runtime-pb-swift/ExtendableMessage.swift
|
apache-2.0
|
2
|
// Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google 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
typealias ExtensionsValueType = protocol<Hashable, Equatable>
public class ExtendableMessage : GeneratedMessage
{
private var extensionMap:[Int32:Any] = [Int32:Any]()
public var extensionRegistry:[Int32:ConcreateExtensionField] = [Int32:ConcreateExtensionField]()
required public init()
{
super.init()
}
//Override
override public class func className() -> String
{
return "ExtendableMessage"
}
override public func className() -> String
{
return "ExtendableMessage"
}
override public func classMetaType() -> GeneratedMessage.Type
{
return ExtendableMessage.self
}
//
public func isInitialized(object:Any) -> Bool
{
switch object
{
case let array as Array<Any>:
for child in array
{
if (!isInitialized(child))
{
return false
}
}
case let array as Array<GeneratedMessage>:
for child in array
{
if (!isInitialized(child))
{
return false
}
}
case let message as GeneratedMessage:
return message.isInitialized()
default:
return true
}
return true
}
public func extensionsAreInitialized() -> Bool {
var arr = Array(extensionMap.values)
return isInitialized(arr)
}
internal func ensureExtensionIsRegistered(extensions:ConcreateExtensionField)
{
extensionRegistry[extensions.fieldNumber] = extensions
}
public func getExtension(extensions:ConcreateExtensionField) -> Any
{
ensureExtensionIsRegistered(extensions)
if var value = extensionMap[extensions.fieldNumber]
{
return value
}
return extensions.defaultValue
}
public func hasExtension(extensions:ConcreateExtensionField) -> Bool
{
if let ext = extensionMap[extensions.fieldNumber]
{
return true
}
return false
}
public func writeExtensionsToCodedOutputStream(output:CodedOutputStream, startInclusive:Int32, endExclusive:Int32)
{
var keys = Array(extensionMap.keys)
keys.sort { $0 < $1 }
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let extensions = extensionRegistry[fieldNumber]!
let value = extensionMap[fieldNumber]!
extensions.writeValueIncludingTagToCodedOutputStream(value, output: output)
}
}
}
public func writeExtensionDescription(inout output:String, startInclusive:Int32 ,endExclusive:Int32, indent:String) {
var keys = Array(extensionMap.keys)
keys.sort { $0 < $1 }
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let extensions = extensionRegistry[fieldNumber]!
let value = extensionMap[fieldNumber]!
extensions.writeDescriptionOf(value, output: &output, indent: indent)
}
}
}
public func isEqualExtensionsInOther(otherMessage:ExtendableMessage, startInclusive:Int32, endExclusive:Int32) -> Bool {
var keys = Array(extensionMap.keys)
keys.sort { $0 < $1 }
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let value = extensionMap[fieldNumber]!
let otherValue = otherMessage.extensionMap[fieldNumber]!
return compare(value, rhs: otherValue)
}
}
return true
}
private func compare(lhs:Any, rhs:Any) -> Bool
{
switch (lhs,rhs)
{
case (let value as Int32, let value2 as Int32):
return value == value2
case (let value as Int64, let value2 as Int64):
return value == value2
case (let value as Double, let value2 as Double):
return value == value2
case (let value as Float, let value2 as Float):
return value == value2
case (let value as Bool, let value2 as Bool):
return value == value2
case (let value as String, let value2 as String):
return value == value2
case (let value as NSData, let value2 as NSData):
return value == value2
case (let value as UInt32, let value2 as UInt32):
return value == value2
case (let value as UInt64, let value2 as UInt64):
return value == value2
case (let value as GeneratedMessage, let value2 as GeneratedMessage):
return value == value2
case (let value as [Int32], let value2 as [Int32]):
return value == value2
case (let value as [Int64], let value2 as [Int64]):
return value == value2
case (let value as [Double], let value2 as [Double]):
return value == value2
case (let value as [Float], let value2 as [Float]):
return value == value2
case (let value as [Bool], let value2 as [Bool]):
return value == value2
case (let value as [String], let value2 as [String]):
return value == value2
case (let value as Array<NSData>, let value2 as Array<NSData>):
return value == value2
case (let value as [UInt32], let value2 as [UInt32]):
return value == value2
case (let value as [UInt64], let value2 as [UInt64]):
return value == value2
case (let value as [GeneratedMessage], let value2 as [GeneratedMessage]):
return value == value2
default:
return false
}
}
private func getHash<T>(lhs:T) -> Int!
{
switch lhs
{
case let value as Int32:
return getHashValue(value)
case let value as Int64:
return getHashValue(value)
case let value as UInt32:
return getHashValue(value)
case let value as UInt64:
return getHashValue(value)
case let value as Float:
return getHashValue(value)
case let value as Double:
return getHashValue(value)
case let value as Bool:
return getHashValue(value)
case let value as String:
return getHashValue(value)
case let value as GeneratedMessage:
return getHashValue(value)
case let value as NSData:
return value.hashValue
case let value as [Int32]:
return getHashValueRepeated(value)
case let value as [Int64]:
return getHashValueRepeated(value)
case let value as [UInt32]:
return getHashValueRepeated(value)
case let value as [UInt64]:
return getHashValueRepeated(value)
case let value as [Float]:
return getHashValueRepeated(value)
case let value as [Double]:
return getHashValueRepeated(value)
case let value as [Bool]:
return getHashValueRepeated(value)
case let value as [String]:
return getHashValueRepeated(value)
case let value as Array<NSData>:
return getHashValueRepeated(value)
case let value as [GeneratedMessage]:
return getHashValueRepeated(value)
default:
return nil
}
}
private func getHashValueRepeated<T where T:CollectionType, T.Generator.Element:protocol<Hashable,Equatable>>(lhs:T) -> Int!
{
var hashCode:Int = 0
for vv in lhs
{
hashCode = (hashCode &* 31) &+ vv.hashValue
}
return hashCode
}
private func getHashValue<T where T:protocol<Hashable,Equatable>>(lhs:T) -> Int!
{
return lhs.hashValue
}
public func hashExtensionsFrom(startInclusive:Int32, endExclusive:Int32) -> Int {
var hashCode:Int = 0
var keys = Array(extensionMap.keys)
keys.sort { $0 < $1 }
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let value = extensionMap[fieldNumber]!
hashCode = (hashCode &* 31) &+ getHash(value)!
}
}
return hashCode
}
public func extensionsSerializedSize() ->Int32 {
var size:Int32 = 0
for fieldNumber in extensionMap.keys {
let extensions = extensionRegistry[fieldNumber]!
let value = extensionMap[fieldNumber]!
size += extensions.computeSerializedSizeIncludingTag(value)
}
return size
}
}
public class ExtendableMessageBuilder:GeneratedMessageBuilder
{
override public var internalGetResult:ExtendableMessage {
get
{
NSException(name:"ImproperSubclassing", reason:"", userInfo: nil).raise()
return ExtendableMessage()
}
}
override public func checkInitialized()
{
let result = internalGetResult
if (!result.isInitialized())
{
NSException(name:"UninitializedMessage", reason:"", userInfo: nil).raise()
}
}
override public func checkInitializedParsed()
{
let result = internalGetResult
if (!result.isInitialized())
{
NSException(name:"InvalidProtocolBuffer", reason:"", userInfo: nil).raise()
}
}
override public func isInitialized() -> Bool
{
return internalGetResult.isInitialized()
}
override public func mergeUnknownFields(unknownFields: UnknownFieldSet) -> Self
{
let result:GeneratedMessage = internalGetResult
result.unknownFields = UnknownFieldSet.builderWithUnknownFields(result.unknownFields).mergeUnknownFields(unknownFields).build()
return self
}
override public func parseUnknownField(input:CodedInputStream ,unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, tag:Int32) -> Bool {
var message = internalGetResult
var wireType = WireFormat.wireFormatGetTagWireType(tag)
var fieldNumber:Int32 = WireFormat.wireFormatGetTagFieldNumber(tag)
var extensions = extensionRegistry.getExtension(message.classMetaType(), fieldNumber: fieldNumber)
if extensions != nil {
if extensions!.wireType.rawValue == wireType {
extensions!.mergeFromCodedInputStream(input, unknownFields:unknownFields, extensionRegistry:extensionRegistry, builder:self, tag:tag)
return true
}
}
return super.parseUnknownField(input, unknownFields: unknownFields, extensionRegistry: extensionRegistry, tag: tag)
}
public func getExtension(extensions:ConcreateExtensionField) -> Any
{
return internalGetResult.getExtension(extensions)
}
public func hasExtension(extensions:ConcreateExtensionField) -> Bool {
return internalGetResult.hasExtension(extensions)
}
public func setExtension(extensions:ConcreateExtensionField, value:Any) -> Self {
var message = internalGetResult
message.ensureExtensionIsRegistered(extensions)
if (extensions.isRepeated) {
NSException(name:"IllegalArgument", reason:"Must call addExtension() for repeated types.", userInfo: nil).raise()
}
message.extensionMap[extensions.fieldNumber] = value
return self
}
public func addExtension<T>(extensions:ConcreateExtensionField, value:T) -> ExtendableMessageBuilder {
var message = internalGetResult
message.ensureExtensionIsRegistered(extensions)
if (!extensions.isRepeated) {
NSException(name:"IllegalArgument", reason:"Must call setExtension() for singular types.", userInfo: nil).raise()
}
var fieldNumber = extensions.fieldNumber
if let val = value as? GeneratedMessage
{
var list:[GeneratedMessage]! = message.extensionMap[fieldNumber] as? [GeneratedMessage] ?? []
list.append(val)
message.extensionMap[fieldNumber] = list
}
else
{
var list:[T]! = message.extensionMap[fieldNumber] as? [T] ?? []
list.append(value)
message.extensionMap[fieldNumber] = list
}
return self
}
public func setExtension<T>(extensions:ConcreateExtensionField, index:Int32, value:T) -> Self {
var message = internalGetResult
message.ensureExtensionIsRegistered(extensions)
if (!extensions.isRepeated) {
NSException(name:"IllegalArgument", reason:"Must call setExtension() for singular types.", userInfo: nil).raise()
}
var fieldNumber = extensions.fieldNumber
if let val = value as? GeneratedMessage
{
var list:[GeneratedMessage]! = message.extensionMap[fieldNumber] as? [GeneratedMessage] ?? []
list[Int(index)] = val
message.extensionMap[fieldNumber] = list
}
else
{
var list:[T]! = message.extensionMap[fieldNumber] as? [T] ?? []
list[Int(index)] = value
message.extensionMap[fieldNumber] = list
}
return self
}
public func clearExtension(extensions:ConcreateExtensionField) -> Self {
var message = internalGetResult
message.ensureExtensionIsRegistered(extensions)
message.extensionMap.removeValueForKey(extensions.fieldNumber)
return self
}
private func mergeRepeatedExtensionFields<T where T:CollectionType>(var otherList:T, var extensionMap:[Int32:Any], fieldNumber:Int32) -> [T.Generator.Element]
{
var list:[T.Generator.Element]! = extensionMap[fieldNumber] as? [T.Generator.Element] ?? []
list! += otherList
return list!
}
public func mergeExtensionFields(other:ExtendableMessage) {
var thisMessage = internalGetResult
if (thisMessage.className() != other.className()) {
NSException(name:"IllegalArgument", reason:"Cannot merge extensions from a different type", userInfo: nil).raise()
}
if other.extensionMap.count > 0 {
var registry = other.extensionRegistry
for fieldNumber in other.extensionMap.keys {
var thisField = registry[fieldNumber]!
var value = other.extensionMap[fieldNumber]!
if thisField.isRepeated {
switch value
{
case let values as [Int32]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Int64]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [UInt64]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [UInt32]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Bool]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Float]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Double]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [String]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as Array<NSData>:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [GeneratedMessage]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
default:
break
}
}
else
{
thisMessage.extensionMap[fieldNumber] = value
}
}
}
}
}
|
88703480ee6e2ed96804150ea2b35d21
| 36.855346 | 166 | 0.61173 | false | false | false | false |
khoren93/SwiftHub
|
refs/heads/master
|
SwiftHub/Modules/Search/SearchViewController.swift
|
mit
|
1
|
//
// SearchViewController.swift
// SwiftHub
//
// Created by Khoren Markosyan on 6/30/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
private let trendingRepositoryReuseIdentifier = R.reuseIdentifier.trendingRepositoryCell
private let trendingUserReuseIdentifier = R.reuseIdentifier.trendingUserCell
private let repositoryReuseIdentifier = R.reuseIdentifier.repositoryCell
private let userReuseIdentifier = R.reuseIdentifier.userCell
enum SearchTypeSegments: Int {
case repositories, users
var title: String {
switch self {
case .repositories: return R.string.localizable.searchRepositoriesSegmentTitle.key.localized()
case .users: return R.string.localizable.searchUsersSegmentTitle.key.localized()
}
}
}
enum TrendingPeriodSegments: Int {
case daily, weekly, montly
var title: String {
switch self {
case .daily: return R.string.localizable.searchDailySegmentTitle.key.localized()
case .weekly: return R.string.localizable.searchWeeklySegmentTitle.key.localized()
case .montly: return R.string.localizable.searchMonthlySegmentTitle.key.localized()
}
}
var paramValue: String {
switch self {
case .daily: return "daily"
case .weekly: return "weekly"
case .montly: return "monthly"
}
}
}
enum SearchModeSegments: Int {
case trending, search
var title: String {
switch self {
case .trending: return R.string.localizable.searchTrendingSegmentTitle.key.localized()
case .search: return R.string.localizable.searchSearchSegmentTitle.key.localized()
}
}
}
enum SortRepositoryItems: Int {
case bestMatch, mostStars, fewestStars, mostForks, fewestForks, recentlyUpdated, lastRecentlyUpdated
var title: String {
switch self {
case .bestMatch: return R.string.localizable.searchSortRepositoriesBestMatchTitle.key.localized()
case .mostStars: return R.string.localizable.searchSortRepositoriesMostStarsTitle.key.localized()
case .fewestStars: return R.string.localizable.searchSortRepositoriesFewestStarsTitle.key.localized()
case .mostForks: return R.string.localizable.searchSortRepositoriesMostForksTitle.key.localized()
case .fewestForks: return R.string.localizable.searchSortRepositoriesFewestForksTitle.key.localized()
case .recentlyUpdated: return R.string.localizable.searchSortRepositoriesRecentlyUpdatedTitle.key.localized()
case .lastRecentlyUpdated: return R.string.localizable.searchSortRepositoriesLastRecentlyUpdatedTitle.key.localized()
}
}
var sortValue: String {
switch self {
case .bestMatch: return ""
case .mostStars, .fewestStars: return "stars"
case .mostForks, .fewestForks: return "forks"
case .recentlyUpdated, .lastRecentlyUpdated: return "updated"
}
}
var orderValue: String {
switch self {
case .bestMatch: return ""
case .mostStars, .mostForks, .recentlyUpdated: return "desc"
case .fewestStars, .fewestForks, .lastRecentlyUpdated: return "asc"
}
}
static func allItems() -> [String] {
return (0...SortRepositoryItems.lastRecentlyUpdated.rawValue)
.map { SortRepositoryItems(rawValue: $0)!.title }
}
}
enum SortUserItems: Int {
case bestMatch, mostFollowers, fewestFollowers, mostRecentlyJoined, leastRecentlyJoined, mostRepositories, fewestRepositories
var title: String {
switch self {
case .bestMatch: return R.string.localizable.searchSortUsersBestMatchTitle.key.localized()
case .mostFollowers: return R.string.localizable.searchSortUsersMostFollowersTitle.key.localized()
case .fewestFollowers: return R.string.localizable.searchSortUsersFewestFollowersTitle.key.localized()
case .mostRecentlyJoined: return R.string.localizable.searchSortUsersMostRecentlyJoinedTitle.key.localized()
case .leastRecentlyJoined: return R.string.localizable.searchSortUsersLeastRecentlyJoinedTitle.key.localized()
case .mostRepositories: return R.string.localizable.searchSortUsersMostRepositoriesTitle.key.localized()
case .fewestRepositories: return R.string.localizable.searchSortUsersFewestRepositoriesTitle.key.localized()
}
}
var sortValue: String {
switch self {
case .bestMatch: return ""
case .mostFollowers, .fewestFollowers: return "followers"
case .mostRecentlyJoined, .leastRecentlyJoined: return "joined"
case .mostRepositories, .fewestRepositories: return "repositories"
}
}
var orderValue: String {
switch self {
case .bestMatch, .mostFollowers, .mostRecentlyJoined, .mostRepositories: return "desc"
case .fewestFollowers, .leastRecentlyJoined, .fewestRepositories: return "asc"
}
}
static func allItems() -> [String] {
return (0...SortUserItems.fewestRepositories.rawValue)
.map { SortUserItems(rawValue: $0)!.title }
}
}
class SearchViewController: TableViewController {
lazy var rightBarButton: BarButtonItem = {
let view = BarButtonItem(image: R.image.icon_navigation_language(), style: .done, target: nil, action: nil)
return view
}()
lazy var segmentedControl: SegmentedControl = {
let titles = [SearchTypeSegments.repositories.title, SearchTypeSegments.users.title]
let images = [R.image.icon_cell_badge_repository()!, R.image.icon_cell_badge_user()!]
let selectedImages = [R.image.icon_cell_badge_repository()!, R.image.icon_cell_badge_user()!]
let view = SegmentedControl(sectionImages: images, sectionSelectedImages: selectedImages, titlesForSections: titles)
view.selectedSegmentIndex = 0
view.snp.makeConstraints({ (make) in
make.width.equalTo(220)
})
return view
}()
let trendingPeriodView = View()
lazy var trendingPeriodSegmentedControl: SegmentedControl = {
let items = [TrendingPeriodSegments.daily.title, TrendingPeriodSegments.weekly.title, TrendingPeriodSegments.montly.title]
let view = SegmentedControl(sectionTitles: items)
view.selectedSegmentIndex = 0
return view
}()
let searchModeView = View()
lazy var searchModeSegmentedControl: SegmentedControl = {
let titles = [SearchModeSegments.trending.title, SearchModeSegments.search.title]
let images = [R.image.icon_cell_badge_trending()!, R.image.icon_cell_badge_search()!]
let selectedImages = [R.image.icon_cell_badge_trending()!, R.image.icon_cell_badge_search()!]
let view = SegmentedControl(sectionImages: images, sectionSelectedImages: selectedImages, titlesForSections: titles)
view.selectedSegmentIndex = 0
return view
}()
lazy var totalCountLabel: Label = {
let view = Label()
view.font = view.font.withSize(14)
view.leftTextInset = self.inset
return view
}()
lazy var sortLabel: Label = {
let view = Label()
view.font = view.font.withSize(14)
view.textAlignment = .right
view.rightTextInset = self.inset
return view
}()
lazy var labelsStackView: StackView = {
let view = StackView(arrangedSubviews: [self.totalCountLabel, self.sortLabel])
view.axis = .horizontal
return view
}()
lazy var sortDropDown: DropDownView = {
let view = DropDownView(anchorView: self.tableView)
return view
}()
let sortRepositoryItem = BehaviorRelay(value: SortRepositoryItems.bestMatch)
let sortUserItem = BehaviorRelay(value: SortUserItems.bestMatch)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func makeUI() {
super.makeUI()
navigationItem.titleView = segmentedControl
navigationItem.rightBarButtonItem = rightBarButton
languageChanged.subscribe(onNext: { [weak self] () in
self?.searchBar.placeholder = R.string.localizable.searchSearchBarPlaceholder.key.localized()
self?.segmentedControl.sectionTitles = [SearchTypeSegments.repositories.title,
SearchTypeSegments.users.title]
self?.trendingPeriodSegmentedControl.sectionTitles = [TrendingPeriodSegments.daily.title,
TrendingPeriodSegments.weekly.title,
TrendingPeriodSegments.montly.title]
self?.searchModeSegmentedControl.sectionTitles = [SearchModeSegments.trending.title,
SearchModeSegments.search.title]
}).disposed(by: rx.disposeBag)
trendingPeriodView.addSubview(trendingPeriodSegmentedControl)
trendingPeriodSegmentedControl.snp.makeConstraints { (make) in
make.left.right.equalToSuperview().inset(self.inset)
make.top.bottom.equalToSuperview()
}
searchModeView.addSubview(searchModeSegmentedControl)
searchModeSegmentedControl.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(self.inset)
}
stackView.insertArrangedSubview(labelsStackView, at: 0)
stackView.insertArrangedSubview(trendingPeriodView, at: 0)
stackView.insertArrangedSubview(searchBar, at: 0)
stackView.addArrangedSubview(searchModeView)
labelsStackView.snp.makeConstraints { (make) in
make.height.equalTo(30)
}
sortDropDown.selectionAction = { [weak self] (index: Int, item: String) in
if self?.segmentedControl.selectedSegmentIndex == 0 {
if let item = SortRepositoryItems(rawValue: index) {
self?.sortRepositoryItem.accept(item)
}
} else {
if let item = SortUserItems(rawValue: index) {
self?.sortUserItem.accept(item)
}
}
}
bannerView.isHidden = true
tableView.register(R.nib.trendingRepositoryCell)
tableView.register(R.nib.trendingUserCell)
tableView.register(R.nib.repositoryCell)
tableView.register(R.nib.userCell)
totalCountLabel.theme.textColor = themeService.attribute { $0.text }
sortLabel.theme.textColor = themeService.attribute { $0.text }
themeService.typeStream.subscribe(onNext: { [weak self] (themeType) in
let theme = themeType.associatedObject
self?.sortDropDown.dimmedBackgroundColor = theme.primaryDark.withAlphaComponent(0.5)
self?.segmentedControl.sectionImages = [
R.image.icon_cell_badge_repository()!.tint(theme.textGray, blendMode: .normal).withRoundedCorners()!,
R.image.icon_cell_badge_user()!.tint(theme.textGray, blendMode: .normal).withRoundedCorners()!
]
self?.segmentedControl.sectionSelectedImages = [
R.image.icon_cell_badge_repository()!.tint(theme.secondary, blendMode: .normal).withRoundedCorners()!,
R.image.icon_cell_badge_user()!.tint(theme.secondary, blendMode: .normal).withRoundedCorners()!
]
self?.searchModeSegmentedControl.sectionImages = [
R.image.icon_cell_badge_trending()!.tint(theme.textGray, blendMode: .normal).withRoundedCorners()!,
R.image.icon_cell_badge_search()!.tint(theme.textGray, blendMode: .normal).withRoundedCorners()!
]
self?.searchModeSegmentedControl.sectionSelectedImages = [
R.image.icon_cell_badge_trending()!.tint(theme.secondary, blendMode: .normal).withRoundedCorners()!,
R.image.icon_cell_badge_search()!.tint(theme.secondary, blendMode: .normal).withRoundedCorners()!
]
}).disposed(by: rx.disposeBag)
}
override func bindViewModel() {
super.bindViewModel()
guard let viewModel = viewModel as? SearchViewModel else { return }
let searchTypeSegmentSelected = segmentedControl.segmentSelection.map { SearchTypeSegments(rawValue: $0)! }
let trendingPerionSegmentSelected = trendingPeriodSegmentedControl.segmentSelection.map { TrendingPeriodSegments(rawValue: $0)! }
let searchModeSegmentSelected = searchModeSegmentedControl.segmentSelection.map { SearchModeSegments(rawValue: $0)! }
let refresh = Observable.of(Observable.just(()), headerRefreshTrigger, themeService.typeStream.mapToVoid()).merge()
let input = SearchViewModel.Input(headerRefresh: refresh,
footerRefresh: footerRefreshTrigger,
languageTrigger: languageChanged.asObservable(),
keywordTrigger: searchBar.rx.text.orEmpty.asDriver(),
textDidBeginEditing: searchBar.rx.textDidBeginEditing.asDriver(),
languagesSelection: rightBarButton.rx.tap.asObservable(),
searchTypeSegmentSelection: searchTypeSegmentSelected,
trendingPeriodSegmentSelection: trendingPerionSegmentSelected,
searchModeSelection: searchModeSegmentSelected,
sortRepositorySelection: sortRepositoryItem.asObservable(),
sortUserSelection: sortUserItem.asObservable(),
selection: tableView.rx.modelSelected(SearchSectionItem.self).asDriver())
let output = viewModel.transform(input: input)
let dataSource = RxTableViewSectionedReloadDataSource<SearchSection>(configureCell: { dataSource, tableView, indexPath, item in
switch item {
case .trendingRepositoriesItem(let cellViewModel):
let cell = tableView.dequeueReusableCell(withIdentifier: trendingRepositoryReuseIdentifier, for: indexPath)!
cell.bind(to: cellViewModel)
return cell
case .trendingUsersItem(let cellViewModel):
let cell = tableView.dequeueReusableCell(withIdentifier: trendingUserReuseIdentifier, for: indexPath)!
cell.bind(to: cellViewModel)
return cell
case .repositoriesItem(let cellViewModel):
let cell = tableView.dequeueReusableCell(withIdentifier: repositoryReuseIdentifier, for: indexPath)!
cell.bind(to: cellViewModel)
return cell
case .usersItem(let cellViewModel):
let cell = tableView.dequeueReusableCell(withIdentifier: userReuseIdentifier, for: indexPath)!
cell.bind(to: cellViewModel)
return cell
}
}, titleForHeaderInSection: { dataSource, index in
let section = dataSource[index]
return section.title
})
output.items.asObservable()
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: rx.disposeBag)
output.languagesSelection.drive(onNext: { [weak self] (viewModel) in
self?.navigator.show(segue: .languages(viewModel: viewModel), sender: self, transition: .modal)
}).disposed(by: rx.disposeBag)
output.repositorySelected.drive(onNext: { [weak self] (viewModel) in
self?.navigator.show(segue: .repositoryDetails(viewModel: viewModel), sender: self, transition: .detail)
}).disposed(by: rx.disposeBag)
output.userSelected.drive(onNext: { [weak self] (viewModel) in
self?.navigator.show(segue: .userDetails(viewModel: viewModel), sender: self, transition: .detail)
}).disposed(by: rx.disposeBag)
output.dismissKeyboard.drive(onNext: { [weak self] () in
self?.searchBar.resignFirstResponder()
}).disposed(by: rx.disposeBag)
output.hidesTrendingPeriodSegment.drive(trendingPeriodView.rx.isHidden).disposed(by: rx.disposeBag)
output.hidesSearchModeSegment.drive(searchModeView.rx.isHidden).disposed(by: rx.disposeBag)
output.hidesSortLabel.drive(labelsStackView.rx.isHidden).disposed(by: rx.disposeBag)
output.hidesSortLabel.drive(totalCountLabel.rx.isHidden).disposed(by: rx.disposeBag)
output.hidesSortLabel.drive(sortLabel.rx.isHidden).disposed(by: rx.disposeBag)
sortLabel.rx.tap().subscribe(onNext: { [weak self] () in
self?.sortDropDown.show()
}).disposed(by: rx.disposeBag)
output.sortItems.drive(onNext: { [weak self] (items) in
self?.sortDropDown.dataSource = items
self?.sortDropDown.reloadAllComponents()
}).disposed(by: rx.disposeBag)
output.totalCountText.drive(totalCountLabel.rx.text).disposed(by: rx.disposeBag)
output.sortText.drive(sortLabel.rx.text).disposed(by: rx.disposeBag)
viewModel.searchMode.asDriver().drive(onNext: { [weak self] (searchMode) in
guard let self = self else { return }
self.searchModeSegmentedControl.selectedSegmentIndex = UInt(searchMode.rawValue)
switch searchMode {
case .trending:
self.tableView.footRefreshControl = nil
case .search:
self.tableView.bindGlobalStyle(forFootRefreshHandler: { [weak self] in
self?.footerRefreshTrigger.onNext(())
})
self.tableView.footRefreshControl.autoRefreshOnFoot = true
self.isFooterLoading.bind(to: self.tableView.footRefreshControl.rx.isAnimating).disposed(by: self.rx.disposeBag)
}
}).disposed(by: rx.disposeBag)
}
}
|
6f9d02f9e9db95475086e76441dc6b7a
| 45.306905 | 137 | 0.662156 | false | false | false | false |
hgani/ganilib-ios
|
refs/heads/master
|
glib/Classes/View/GWebView.swift
|
mit
|
1
|
import UIKit
import WebKit
open class GWebView: WKWebView {
private var helper: ViewHelper!
private var requestUrl: URL?
fileprivate lazy var refresher: GRefreshControl = {
GRefreshControl().onValueChanged { [unowned self] in
self.refresh()
}
}()
public init() {
super.init(frame: .zero, configuration: WKWebViewConfiguration())
initialize()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initialize()
}
private func initialize() {
helper = ViewHelper(self)
navigationDelegate = self
scrollView.addSubview(refresher)
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
helper.didMoveToSuperview()
}
public func color(bg: UIColor?) -> Self {
if let bgColor = bg {
backgroundColor = bgColor
}
return self
}
public func width(_ width: Int) -> Self {
helper.width(width)
return self
}
public func width(_ width: LayoutSize) -> Self {
helper.width(width)
return self
}
public func width(weight: Float) -> Self {
helper.width(weight: weight)
return self
}
public func height(_ height: Int) -> Self {
helper.height(height)
return self
}
public func height(_ height: LayoutSize) -> Self {
helper.height(height)
return self
}
public func load(url: URL) -> Self {
requestUrl = url
GLog.i("Loading \(url) ...")
refresher.show()
load(URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 30))
return self
}
public func load(url: String) -> Self {
return load(url: URL(string: url)!)
}
public func refresh() {
// It seems that reload() doesn't do anything when the initial load() failed.
if let url = self.requestUrl {
_ = load(url: url)
}
}
public func end() {
// Ends chaining
}
}
extension GWebView: WKNavigationDelegate {
public func webView(_: WKWebView, didFinish _: WKNavigation!) {
refresher.hide()
}
public func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error) {
handle(error: error)
}
// E.g. SSL error
public func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
handle(error: error)
}
private func handle(error: Error) {
refresher.hide()
let alert = UIAlertController(title: nil,
message: error.localizedDescription,
preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.addAction(UIAlertAction(title: "Retry", style: .default) { [unowned self] (_) -> Void in
self.refresh()
})
GApp.instance.navigationController.present(alert, animated: true, completion: nil)
}
}
|
3591cbca6f7ca141ff57a1301aa0d1a5
| 24.603306 | 110 | 0.584571 | false | false | false | false |
bitjammer/swift
|
refs/heads/master
|
test/ClangImporter/objc_init.swift
|
apache-2.0
|
4
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify -verify-ignore-unknown
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
// FIXME: <rdar://problem/19452886> test/ClangModules/objc_init.swift should not require REQUIRES: OS=macosx
import AppKit
import objc_ext
import TestProtocols
import ObjCParseExtras
// rdar://problem/18500201
extension NSSet {
convenience init<T>(array: Array<T>) {
self.init()
}
}
// Subclassing and designated initializers
func testNSInterestingDesignated() {
NSInterestingDesignated() // expected-warning{{unused}}
NSInterestingDesignated(string:"hello") // expected-warning{{unused}}
NSInterestingDesignatedSub() // expected-warning{{unused}}
NSInterestingDesignatedSub(string:"hello") // expected-warning{{unused}}
}
extension URLDocument {
convenience init(string: String) {
self.init(url: string)
}
}
class MyDocument1 : URLDocument {
override init() {
super.init()
}
}
func createMyDocument1() {
var md = MyDocument1()
md = MyDocument1(url: "http://llvm.org")
// Inherited convenience init.
md = MyDocument1(string: "http://llvm.org")
_ = md
}
class MyDocument2 : URLDocument {
init(url: String) {
super.init(url: url) // expected-error{{must call a designated initializer of the superclass 'URLDocument'}}
}
}
class MyDocument3 : NSAwesomeDocument {
override init() {
super.init()
}
}
func createMyDocument3(_ url: NSURL) {
var md = MyDocument3()
md = try! MyDocument3(contentsOf: url as URL, ofType:"")
_ = md
}
class MyInterestingDesignated : NSInterestingDesignatedSub {
override init(string str: String) {
super.init(string: str)
}
init(int i: Int) {
super.init() // expected-error{{must call a designated initializer of the superclass 'NSInterestingDesignatedSub'}}
}
}
func createMyInterestingDesignated() {
_ = MyInterestingDesignated(url: "http://llvm.org")
}
func testNoReturn(_ a : NSAwesomeDocument) -> Int {
a.noReturnMethod(42)
return 17 // TODO: In principle, we should produce an unreachable code diagnostic here.
}
// Initializer inheritance from protocol-specified initializers.
class MyViewController : NSViewController {
}
class MyView : NSView {
override init() { super.init() }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSView'}}
class MyMenu : NSMenu {
override init(title: String) { super.init(title: title) }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSMenu'}}
class MyTableViewController : NSTableViewController {
}
class MyOtherTableViewController : NSTableViewController {
override init(int i: Int) {
super.init(int: i)
}
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSTableViewController'}}
class MyThirdTableViewController : NSTableViewController {
override init(int i: Int) {
super.init(int: i)
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
}
func checkInitWithCoder(_ coder: NSCoder) {
NSViewController(coder: coder) // expected-warning{{unused}}
NSTableViewController(coder: coder) // expected-warning{{unused}}
MyViewController(coder: coder) // expected-warning{{unused}}
MyTableViewController(coder: coder) // expected-warning{{unused}}
MyOtherTableViewController(coder: coder) // expected-error{{incorrect argument label in call (have 'coder:', expected 'int:')}}
MyThirdTableViewController(coder: coder) // expected-warning{{unused}}
}
// <rdar://problem/16838409>
class MyDictionary1 : NSDictionary {}
func getMyDictionary1() {
_ = MyDictionary1()
}
// <rdar://problem/16838515>
class MyDictionary2 : NSDictionary {
override init() {
super.init()
}
}
class MyString : NSString {
override init() { super.init() }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSString'}}
// <rdar://problem/17281900>
class View: NSView {
override func addSubview(_ aView: NSView) {
_ = MyViewController.init()
}
}
// rdar://problem/19726164
class NonNullDefaultInitSubSub : NonNullDefaultInitSub {
func foo() {
_ = NonNullDefaultInitSubSub() as NonNullDefaultInitSubSub?
}
}
class DesignatedInitSub : DesignatedInitBase {
var foo: Int?
override init(int: Int) {}
}
class DesignedInitSubSub : DesignatedInitSub {
init(double: Double) { super.init(int: 0) } // okay
init(string: String) { super.init() } // expected-error {{must call a designated initializer of the superclass 'DesignatedInitSub'}}
}
// Make sure that our magic doesn't think the class property with the type name is an init
func classPropertiesAreNotInit() -> ProcessInfo {
var procInfo = NSProcessInfo.processInfo // expected-error{{'NSProcessInfo' has been renamed to 'ProcessInfo'}}
procInfo = ProcessInfo.processInfo // okay
return procInfo
}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected note produced: 'NSProcessInfo' was obsoleted in Swift 3
|
a68afdc39d2b00048e53b3c763278887
| 27.823864 | 134 | 0.719298 | false | false | false | false |
adamahrens/braintweak
|
refs/heads/master
|
BrainTweak/BrainTweak/ViewControllers/GameViewController.swift
|
mit
|
1
|
//
// GameViewController.swift
// BrainTweak
//
// Created by Adam Ahrens on 2/20/15.
// Copyright (c) 2015 Appsbyahrens. All rights reserved.
//
import UIKit
class GameViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var correctButton: UIButton!
@IBOutlet weak var incorrectButton: UIButton!
@IBOutlet weak var tableViewBottomSpace: NSLayoutConstraint!
var gameBrain: GameBrain?
var scoreKeeper: ScoreKeeper?
var currentMathProblem = 0
var answeredQuestions = Dictionary<Int, String>()
override func viewDidLoad() {
super.viewDidLoad()
title = "Game"
// Setup the ScoreKeeper
scoreKeeper = ScoreKeeper(maxScore: Double(gameBrain!.size()))
}
//MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gameBrain!.size()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MathCell", forIndexPath: indexPath) as! MathCell
cell.mathProblem.text = gameBrain!.mathProblemDisplay(indexPath.row)
if (answeredQuestions[indexPath.row] != nil) {
if (answeredQuestions[indexPath.row] == "true") {
let greenColor = UIColor(red: 4.0/255.0, green: 175.0/255.0, blue: 77.0/255.0, alpha: 1.0)
cell.backgroundColor = greenColor
cell.contentView.backgroundColor = greenColor
cell.mathProblem.backgroundColor = greenColor
} else {
let redColor = UIColor(red: 255.0/255.0, green: 61.0/255.0, blue: 50.0/255.0, alpha: 1.0)
cell.backgroundColor = redColor
cell.contentView.backgroundColor = redColor
cell.mathProblem.backgroundColor = redColor
}
}
return cell
}
//MARK: IBActions
@IBAction func wrongPressed(sender: UIButton) {
userAnsweredQuestionWith(false)
}
@IBAction func submitPressed(sender: UIButton) {
userAnsweredQuestionWith(true)
}
private func userAnsweredQuestionWith(answer: Bool) {
var usersAnswerIsCorrect = "false"
if gameBrain!.isMathProblemCorrect(currentMathProblem) == answer {
scoreKeeper!.answeredCorrectly()
usersAnswerIsCorrect = "true"
}
// Update score
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: scoreKeeper!.scoreDisplay(), style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
answeredQuestions[currentMathProblem] = usersAnswerIsCorrect
currentMathProblem += 1
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: currentMathProblem - 1, inSection: 0)], withRowAnimation: .Automatic)
// Answered all the questions. Remove the buttons
if currentMathProblem == gameBrain!.size() {
disableButtons()
}
// Scroll the answered problem off screen so the User can
// focus on the next
if currentMathProblem != gameBrain!.size() {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: currentMathProblem, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}
}
private func disableButtons() {
correctButton.enabled = false
incorrectButton.enabled = false
UIView.animateWithDuration(0.35, animations: {
self.tableViewBottomSpace.constant = 0
self.correctButton.hidden = true
self.incorrectButton.hidden = true
self.view.layoutIfNeeded()
})
}
}
|
b036417287c3b278eeb0f1f70884fc10
| 36.192308 | 164 | 0.645036 | false | false | false | false |
BritishGecko31/HHCircleView
|
refs/heads/master
|
HHCircleView/HHCircleView.swift
|
mit
|
1
|
//
// HHCircleView.swift
// HHCircleView
//
// Created by Mathew Trussell on 8/30/15.
// Copyright © 2015 HailHydrant. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
class HHCircleView: UIView {
let progressLayer = CAShapeLayer()
// MARK: - IBInspectable
// Common Circle
@IBInspectable var angleStart: CGFloat = 0
@IBInspectable var angleEnd: CGFloat = 0
//@IBInspectable var rotation: Float = 0
//@IBInspectable var mask: UIImage?
// Progress Circle Appearance
@IBInspectable var progressLineWidth: CGFloat = 40
@IBInspectable var progressLineColor: UIColor = UIColor.redColor()
@IBInspectable var progressBorderWidth: CGFloat = 1
@IBInspectable var progressBorderColor: UIColor = UIColor.greenColor()
@IBInspectable var progressLineCapStyle: String = "kCGLineCapButt"
// Background Circle Appearance
//@IBInspectable var backgroundVisibility: Bool = true
//@IBInspectable var backgroundLineWidth: CGFloat = 1
//@IBInspectable var backgroundLineColor: UIColor = UIColor.lightGrayColor()
//@IBInspectable var backgroundBorderWidth: CGFloat = 10
//@IBInspectable var backgroundBorderColor: UIColor = UIColor.lightGrayColor()
//@IBInspectable var backgroundEndCapStyle: CGLineCap = kCGLineCapButt
// Value Label
//@IBInspectable var value: CGFloat = 33
//@IBInspectable var maxValue: CGFloat = 100
//@IBInspectable var valueDecimals: Int = 2
//@IBInspectable var valueFontName: String = "System"
//@IBInspectable var valueFontSize: CGFloat = 12
//@IBInspectable var valueFontColor: UIColor = UIColor.blackColor()
//@IBInspectable var showValue: Bool = true
// Units Label
//@IBInspectable var units: String = "%"
//@IBInspectable var unitsFontName: String = "System"
//@IBInspectable var unitsFontSize: CGFloat = 12
//@IBInspectable var unitsFontColor: UIColor = UIColor.blackColor()
//@IBInspectable var showUnits: Bool = true
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
configure(frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(frame: CGRect) {
let radius: CGFloat = min(self.frame.width / 2, self.frame.height / 2)
let progressLayerFillColor: UIColor = UIColor.clearColor()
progressLayer.bounds = self.bounds
progressLayer.frame = self.frame
progressLayer.cornerRadius = radius
/*
(self.progressAngle/100.f)*M_PI,
-(self.progressAngle/100.f)*M_PI-((-self.progressRotationAngle/100.f)*2.f+0.5)*M_PI,
*/
progressLayer.path = UIBezierPath(
arcCenter: CGPoint(x: radius, y: radius),
radius: (radius - progressBorderWidth) - (progressLineWidth / 2),
startAngle: radians(angleStart),
endAngle: radians(-1 * angleEnd),
clockwise: true
).CGPath
progressLayer.borderColor = progressBorderColor.CGColor
progressLayer.borderWidth = progressBorderWidth
progressLayer.lineWidth = progressLineWidth
progressLayer.strokeColor = progressLineColor.CGColor
progressLayer.lineCap = progressLineCapStyle
progressLayer.fillColor = progressLayerFillColor.CGColor
self.layer.addSublayer(progressLayer)
// self.layoutIfNeeded()
}
override func layoutSubviews() {
configure(self.frame)
}
// MARK: - Private
func radians(degrees: CGFloat) -> CGFloat {
return CGFloat(Double(degrees) / 180.0 * M_PI)
}
}
|
d15015fb8af0fcf4aecf78b7106183fe
| 32.72973 | 84 | 0.66631 | false | false | false | false |
AloneMonkey/RxSwiftStudy
|
refs/heads/master
|
RxSwiftTableViewSection/RxSwiftTableViewSection/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// RxSwiftTableViewSection
//
// Created by monkey on 2017/3/28.
// Copyright © 2017年 Coder. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ViewController: UIViewController {
@IBOutlet weak var tableview: UITableView!
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let dataSource = self.dataSource
let items = Observable.just([
SectionModel(model: "First", items:[
1.0,
2.0,
3.0
]),
SectionModel(model: "Second", items:[
1.0,
2.0,
3.0
]),
SectionModel(model: "Third", items:[
1.0,
2.0,
3.0
])
])
dataSource.configureCell = {
(_, tv, indexPath, element) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
return cell
}
dataSource.titleForHeaderInSection = { dataSource, sectionIndex in
return dataSource[sectionIndex].model
}
items
.bindTo(tableview.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableview.rx
.itemSelected
.map { indexPath in
return (indexPath, dataSource[indexPath])
}
.subscribe(onNext: { indexPath, model in
print("Tapped `\(model)` @ \(indexPath)")
})
.disposed(by: disposeBag)
tableview.rx
.setDelegate(self)
.disposed(by: disposeBag)
}
}
extension ViewController : UITableViewDelegate{
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .none
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
}
|
d59a2b6a0dca15bb1d171f7ee50a4dfd
| 26.2 | 120 | 0.532872 | false | false | false | false |
mindbody/Conduit
|
refs/heads/main
|
Tests/ConduitTests/Networking/Serialization/XML/XMLTests.swift
|
apache-2.0
|
1
|
//
// XMLTests.swift
// ConduitTests
//
// Created by John Hammerlund on 7/10/17.
// Copyright © 2017 MINDBODY. All rights reserved.
//
import XCTest
import Conduit
class XMLTests: XCTestCase {
/// Test structure:
/// <?xml version="1.0" encoding="utf-8"?>
/// <Root>
/// </N>
/// <N>test 🙂 value</N>
/// <N>
/// <N testKey=\"testValue\"/>
/// <LastNode/>
/// </N>
/// </Root>
let xmlString = """
<?xml version="1.0" encoding="utf-8"?><Root><N/><N>test 🙂 value</N><N><N testKey="testValue"/><LastNode/></N></Root>
"""
private func validate(xml: XML) {
XCTAssert(xml.root?.name == "Root")
XCTAssert(xml.root?.children.count == 3)
XCTAssert(xml.root?.children.first?.isLeaf == true)
XCTAssert(xml.root?.children[1].getValue() == "test 🙂 value")
XCTAssert(xml.root?.children.last?.isLeaf == false)
XCTAssert(xml.root?.children.last?.children.count == 2)
guard let attributes = xml.root?.children.last?.children.first?.attributes else {
XCTFail("No attributes")
return
}
XCTAssertEqual(attributes["testKey"], "testValue")
XCTAssertEqual(xml.root?.children.last?.children.last?.name, "LastNode")
}
func testXMLNodeConstruction() {
let node4 = XMLNode(name: "N")
node4.attributes["testKey"] = "testValue"
let node5 = XMLNode(name: "LastNode")
let node1 = XMLNode(name: "N")
let node2 = XMLNode(name: "N")
node2.text = "test 🙂 value"
let node3 = XMLNode(name: "N")
node3.children = [node4, node5]
let root = XMLNode(name: "Root")
root.children = [node1, node2, node3]
let xml = XML(root: root)
validate(xml: xml)
}
func testXMLStringConstruction() {
guard let xml = XML(xmlString) else {
XCTFail("Failed to parse string")
return
}
validate(xml: xml)
}
func testXMLStringOutputReconstruction() {
guard let originalXML = XML(xmlString), let xml = XML(originalXML.description) else {
XCTFail("Failed to parse xml")
return
}
validate(xml: xml)
}
func testXMLNodeStringConstruction() {
let string = "<foo><bar>baz</bar></foo>"
let node = XMLNode(string)
XCTAssertEqual(node?.name, "foo")
XCTAssertEqual(node?["bar"]?.getValue(), "baz")
XCTAssertEqual(node?.description, string)
}
func testXMLNodeStringConstructionWithGenerics() {
let string = "<xml><int>1</int><double>12.34</double><bool>true</bool></xml>"
let node = XMLNode(string)
XCTAssertEqual(node?.name, "xml")
XCTAssertEqual(node?.getValue("int"), 1)
XCTAssertEqual(node?.getValue("double"), 12.34)
XCTAssertEqual(node?.getValue("bool"), true)
}
func testLosslessStringConvertibleEmpty() {
let xml = ""
XCTAssertNil(XML(xml))
}
func testXMLInjection() {
let xml = "<Node><Parent><Child>Foo</Child></Parent></Node>"
let node = XML(xml)
let parent = node?.root?.nodes(named: "Parent", traversal: .breadthFirst).first
parent?.children.append(XMLNode(name: "Child", value: "Bar"))
XCTAssertEqual(node?.description, "<?xml version=\"1.0\" encoding=\"utf-8\"?><Node><Parent><Child>Foo</Child><Child>Bar</Child></Parent></Node>")
}
func testXMLReplacement() {
let xml = "<Node><Parent><Child>Foo</Child></Parent></Node>"
let node = XML(xml)
let parent = node?.root?.nodes(named: "Parent", traversal: .breadthFirst).first
parent?.children = [XMLNode(name: "Child", value: "Bar")]
XCTAssertEqual(node?.description, "<?xml version=\"1.0\" encoding=\"utf-8\"?><Node><Parent><Child>Bar</Child></Parent></Node>")
}
func testXMLDeletion() {
let xml = "<Node><Parent><Child>Foo</Child></Parent></Node>"
let node = XML(xml)
let parent = node?.root?.nodes(named: "Parent", traversal: .breadthFirst).first
parent?.children = []
XCTAssertEqual(node?.description, "<?xml version=\"1.0\" encoding=\"utf-8\"?><Node><Parent/></Node>")
}
}
|
aec409203e40f67761a24d05cdd93a23
| 33.104 | 153 | 0.582219 | false | true | false | false |
daviwiki/Gourmet_Swift
|
refs/heads/master
|
Gourmet/GourmetModelTests/LoginCheckParserTest.swift
|
mit
|
1
|
//
// LoginCheckParserTest.swift
// Gourmet
//
// Created by David Martinez on 11/12/2016.
// Copyright © 2016 Atenea. All rights reserved.
//
import XCTest
@testable import Gourmet
@testable import GourmetModel
class LoginCheckParserTest: XCTestCase, LoginCheckParseListener {
private var responseArrived : XCTestExpectation?
private var response : ResponseLogin?
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testShouldReadXmlInformationIfPresent() {
let result = "<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"><S:Body><ns2:consultaUsuariosResponse xmlns:ns2=\"http://ws.tarjetaWeb.gourmet.com/\"><return><codReq>-1</codReq><desReq>tarjeta no existe</desReq></return></ns2:consultaUsuariosResponse></S:Body></S:Envelope>"
let data = result.data(using: String.Encoding.utf8)
let inputStream = InputStream(data: data!)
responseArrived = expectation(description: "Waiting for XMLParser")
let parser = LoginCheckParser()
parser.setListener(listener: self)
parser.execute(inputStream: inputStream)
waitForExpectations(timeout: 3.0) { (error: Error?) in
XCTAssertEqual(self.response?.code, -1)
XCTAssertEqual(self.response?.message, "tarjeta no existe")
}
}
internal func onSuccess(parser: LoginCheckParser, response: ResponseLogin) {
self.response = response
responseArrived?.fulfill()
}
internal func onError(parser: LoginCheckParser) {
responseArrived?.fulfill()
}
}
|
dfa1a50cd5f6c2f9f67d25fa31d3b137
| 31.716981 | 336 | 0.655709 | false | true | false | false |
ashfurrow/RxSwift
|
refs/heads/master
|
RxTests/RxSwiftTests/TestImplementations/Subscription.swift
|
mit
|
2
|
//
// Subscription.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
struct Subscription
: Equatable
, Hashable
, CustomDebugStringConvertible {
let subscribe : Time
let unsubscribe : Time
init(_ subscribe: Time) {
self.subscribe = subscribe
self.unsubscribe = Int.max
}
init(_ subscribe: Time, _ unsubscribe: Time) {
self.subscribe = subscribe
self.unsubscribe = unsubscribe
}
var hashValue : Int {
get {
return subscribe.hashValue ^ unsubscribe.hashValue
}
}
}
extension Subscription {
var debugDescription : String {
get {
let infiniteText = "Infinity"
return "(\(subscribe) : \(unsubscribe != Time.max ? String(unsubscribe) : infiniteText))"
}
}
}
func == (lhs: Subscription, rhs: Subscription) -> Bool {
return lhs.subscribe == rhs.subscribe && lhs.unsubscribe == rhs.unsubscribe
}
|
32e1d691b33a9bbd2677c5906c4ca4be
| 21.446809 | 101 | 0.606262 | false | false | false | false |
takeo-asai/math-puzzle
|
refs/heads/master
|
problems/24.swift
|
mit
|
1
|
// 1 2 3
// 4 5 6
// 7 8 9
let targets = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let neighbors: [Int: [Int?]] = [1: [2, 4, nil], 2: [1, 3, nil], 3: [2, 6, nil],
4: [1, 7, nil], 5: [nil], 6: [3, 9, nil],
7: [4, 8, nil], 8: [7, 9, nil], 9: [6, 8, nil]]
func - (lhs: [Int], rhs: [Int]) -> [Int] {
var expr = lhs
for e in rhs {
if let idx = expr.indexOf(e) {
expr.removeAtIndex(idx)
}
}
return expr
}
func isStrikable(targets: [Int], neighbor: Int?) -> Bool {
if let n = neighbor {
return targets.contains(n)
}
return false
}
struct Status: Hashable {
var values: [Int]
init(_ v: [Int]) {
values = v
}
var hashValue: Int {
get {
return values.description.hashValue
}
}
}
func == (lhs: Status, rhs: Status) -> Bool {
return lhs.hashValue == rhs.hashValue
}
var memo: [Status: Int] = Dictionary()
func depthSearch(targets: [Int]) -> Int {
if let m = memo[Status(targets)] {
return m
}
if targets.count == 0 {
return 1
}
var count = 0
for t in targets {
for n in neighbors[t]! {
if isStrikable(targets, neighbor: n) {
count += depthSearch(targets - [n!] - [t])
}
}
count += depthSearch(targets - [t])
}
memo[Status(targets)] = count
return count
}
let t = depthSearch(targets)
print(t)
// 1507200 but answer is 798000
|
fc4232608f2c749eccd419a203856333
| 20.112903 | 80 | 0.559969 | false | false | false | false |
swagproject/swag
|
refs/heads/master
|
Sources/App.swift
|
mit
|
1
|
//
// App.swift
// Swag-Test
//
// Created by Jens Ravens on 24/12/15.
// Copyright © 2015 nerdgeschoss GmbH. All rights reserved.
//
import Foundation
public class App {
private var middlewareStack = [MiddlewareType]()
private var repositories = [String:Any]()
public var router = Router()
public var cache = MemoryCache() as CacheType
private struct RepositoryNotRegistered: ErrorType {
let name: String
}
public init() {}
public func app(request: RequestType) -> ResponseType {
print("parsing request")
let app = combineMiddleware(middlewareStack, app: router.app)
var request = request
request.swag = self
do {
return try app(request)
} catch let e {
if let errorPage = rescue(request, error: e) {
return errorPage
} else {
return Response(code: 500, headers: [:], content: "Internal Server Error: \(e)")
}
}
}
public func repository<T: RepositoryType>(type: T.Type) throws -> T {
guard let repo = repositories[String(T)] as? T else { throw RepositoryNotRegistered(name: String(T)) }
return repo
}
public func register(middleware: MiddlewareType) {
middlewareStack.append(middleware)
}
public func register<T: RepositoryType>(repository: T) {
let type = String(T)
repositories[type] = repository
}
public func rescue(request: RequestType, error: ErrorType) -> ResponseType? {
guard let error = error as? RepositoryError else { return nil }
if case .NotFound(let id) = error {
return Response(code: 404, headers: [:], content: "Object \(id) not found")
}
return nil
}
}
|
34fd2f2c16f9e7015dccb2700fe85e20
| 28.633333 | 110 | 0.608549 | false | false | false | false |
julienbodet/wikipedia-ios
|
refs/heads/develop
|
Wikipedia/Code/BaseExploreFeedSettingsViewController.swift
|
mit
|
1
|
protocol ExploreFeedSettingsItem {
var title: String { get }
var subtitle: String? { get }
var disclosureType: WMFSettingsMenuItemDisclosureType { get }
var disclosureText: String? { get }
var iconName: String? { get }
var iconColor: UIColor? { get }
var iconBackgroundColor: UIColor? { get }
var controlTag: Int { get }
var isOn: Bool { get }
func updateSubtitle(for displayType: ExploreFeedSettingsDisplayType)
func updateDisclosureText(for displayType: ExploreFeedSettingsDisplayType)
func updateIsOn(for displayType: ExploreFeedSettingsDisplayType)
}
extension ExploreFeedSettingsItem {
var subtitle: String? { return nil }
var disclosureType: WMFSettingsMenuItemDisclosureType { return .switch }
var disclosureText: String? { return nil }
var iconName: String? { return nil }
var iconColor: UIColor? { return nil }
var iconBackgroundColor: UIColor? { return nil }
func updateSubtitle(for displayType: ExploreFeedSettingsDisplayType) {
}
func updateDisclosureText(for displayType: ExploreFeedSettingsDisplayType) {
}
func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) {
}
}
enum ExploreFeedSettingsMasterType {
case entireFeed
case singleFeedCard(WMFContentGroupKind)
}
private extension WMFContentGroupKind {
var masterSwitchTitle: String {
switch self {
case .news:
return WMFLocalizedString("explore-feed-preferences-show-news-title", value: "Show In the news card", comment: "Text for the setting that allows users to toggle the visibility of the In the news card")
case .featuredArticle:
return WMFLocalizedString("explore-feed-preferences-show-featured-article-title", value: "Show Featured article card", comment: "Text for the setting that allows users to toggle the visibility of the Featured article card")
case .topRead:
return WMFLocalizedString("explore-feed-preferences-show-top-read-title", value: "Show Top read card", comment: "Text for the setting that allows users to toggle the visibility of the Top read card")
case .onThisDay:
return WMFLocalizedString("explore-feed-preferences-show-on-this-day-title", value: "Show On this day card", comment: "Text for the setting that allows users to toggle the visibility of the On this day card")
case .pictureOfTheDay:
return WMFLocalizedString("explore-feed-preferences-show-picture-of-the-day-title", value: "Show Picture of the day card", comment: "Text for the setting that allows users to toggle the visibility of the Picture of the day card")
case .locationPlaceholder:
fallthrough
case .location:
return WMFLocalizedString("explore-feed-preferences-show-places-title", value: "Show Places card", comment: "Text for the setting that allows users to toggle the visibility of the Places card")
case .random:
return WMFLocalizedString("explore-feed-preferences-show-randomizer-title", value: "Show Randomizer card", comment: "Text for the setting that allows users to toggle the visibility of the Randomizer card")
case .continueReading:
return WMFLocalizedString("explore-feed-preferences-show-continue-reading-title", value: "Show Continue reading card", comment: "Text for the setting that allows users to toggle the visibility of the Continue reading card")
case .relatedPages:
return WMFLocalizedString("explore-feed-preferences-show-related-pages-title", value: "Show Because you read card", comment: "Text for the setting that allows users to toggle the visibility of the Because you read card")
default:
assertionFailure("\(self) is not customizable")
return ""
}
}
}
class ExploreFeedSettingsMaster: ExploreFeedSettingsItem {
let title: String
let controlTag: Int = -1
var isOn: Bool = false
let type: ExploreFeedSettingsMasterType
init(for type: ExploreFeedSettingsMasterType) {
self.type = type
if case let .singleFeedCard(contentGroupKind) = type {
title = contentGroupKind.masterSwitchTitle
isOn = contentGroupKind.isInFeed
} else {
title = WMFLocalizedString("explore-feed-preferences-turn-off-feed", value: "Turn off Explore tab", comment: "Text for the setting that allows users to turn off Explore tab")
isOn = UserDefaults.wmf_userDefaults().defaultTabType != .explore
}
}
func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) {
if case let .singleFeedCard(contentGroupKind) = type {
isOn = contentGroupKind.isInFeed
} else {
isOn = UserDefaults.wmf_userDefaults().defaultTabType != .explore
}
}
}
struct ExploreFeedSettingsSection {
let headerTitle: String?
let footerTitle: String
let items: [ExploreFeedSettingsItem]
}
class ExploreFeedSettingsLanguage: ExploreFeedSettingsItem {
let title: String
let subtitle: String?
let controlTag: Int
var isOn: Bool = false
let siteURL: URL
let languageLink: MWKLanguageLink
init(_ languageLink: MWKLanguageLink, controlTag: Int, displayType: ExploreFeedSettingsDisplayType) {
self.languageLink = languageLink
title = languageLink.localizedName
subtitle = languageLink.languageCode.uppercased()
self.controlTag = controlTag
siteURL = languageLink.siteURL()
updateIsOn(for: displayType)
}
func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) {
switch (displayType) {
case .singleLanguage:
return
case .multipleLanguages:
isOn = languageLink.isInFeed
case .detail(let contentGroupKind):
isOn = languageLink.isInFeed(for: contentGroupKind)
}
}
}
class ExploreFeedSettingsGlobalCards: ExploreFeedSettingsItem {
let disclosureType: WMFSettingsMenuItemDisclosureType = .switch
let title: String = WMFLocalizedString("explore-feed-preferences-global-cards-title", value: "Global cards", comment: "Title for the setting that allows users to toggle non-language specific feed cards")
let subtitle: String? = WMFLocalizedString("explore-feed-preferences-global-cards-description", value: "Non-language specific cards", comment: "Description of global feed cards")
let controlTag: Int = -2
var isOn: Bool = SessionSingleton.sharedInstance().dataStore.feedContentController.areGlobalContentGroupKindsInFeed
func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) {
guard displayType == .singleLanguage || displayType == .multipleLanguages else {
return
}
isOn = SessionSingleton.sharedInstance().dataStore.feedContentController.areGlobalContentGroupKindsInFeed
}
}
enum ExploreFeedSettingsDisplayType: Equatable {
case singleLanguage
case multipleLanguages
case detail(WMFContentGroupKind)
}
class BaseExploreFeedSettingsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@objc var dataStore: MWKDataStore?
var theme = Theme.standard
private var cellsToItemsThatNeedReloading = [WMFSettingsTableViewCell: ExploreFeedSettingsItem]()
override var nibName: String? {
return "BaseExploreFeedSettingsViewController"
}
open var displayType: ExploreFeedSettingsDisplayType = .singleLanguage
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(WMFSettingsTableViewCell.wmf_classNib(), forCellReuseIdentifier: WMFSettingsTableViewCell.identifier)
tableView.register(WMFTableHeaderFooterLabelView.wmf_classNib(), forHeaderFooterViewReuseIdentifier: WMFTableHeaderFooterLabelView.identifier)
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
tableView.sectionFooterHeight = UITableViewAutomaticDimension
tableView.estimatedSectionFooterHeight = 44
apply(theme: theme)
NotificationCenter.default.addObserver(self, selector: #selector(exploreFeedPreferencesDidSave(_:)), name: NSNotification.Name.WMFExploreFeedPreferencesDidSave, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(newExploreFeedPreferencesWereRejected(_:)), name: NSNotification.Name.WMFNewExploreFeedPreferencesWereRejected, object: nil)
}
var preferredLanguages: [MWKLanguageLink] {
return MWKLanguageLinkController.sharedInstance().preferredLanguages
}
lazy var languages: [ExploreFeedSettingsLanguage] = {
let languages = preferredLanguages.enumerated().compactMap { (index, languageLink) in
ExploreFeedSettingsLanguage(languageLink, controlTag: index, displayType: self.displayType)
}
return languages
}()
var feedContentController: WMFExploreFeedContentController? {
return dataStore?.feedContentController
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open var sections: [ExploreFeedSettingsSection] {
assertionFailure("Subclassers should override")
return []
}
func getItem(at indexPath: IndexPath) -> ExploreFeedSettingsItem {
let items = getSection(at: indexPath.section).items
assert(items.indices.contains(indexPath.row), "Item at indexPath \(indexPath) doesn't exist")
return items[indexPath.row]
}
func getSection(at index: Int) -> ExploreFeedSettingsSection {
assert(sections.indices.contains(index), "Section at index \(index) doesn't exist")
return sections[index]
}
// MARK: - Notifications
open func reload() {
for (cell, item) in cellsToItemsThatNeedReloading {
item.updateDisclosureText(for: displayType)
item.updateSubtitle(for: displayType)
item.updateIsOn(for: displayType)
cell.disclosureText = item.disclosureText
cell.subtitle = item.subtitle
cell.disclosureSwitch.setOn(item.isOn, animated: true)
}
}
@objc open func exploreFeedPreferencesDidSave(_ notification: Notification) {
DispatchQueue.main.async {
self.reload()
}
}
@objc open func newExploreFeedPreferencesWereRejected(_ notification: Notification) {
DispatchQueue.main.async {
self.reload()
}
}
}
// MARK: - UITableViewDataSource
extension BaseExploreFeedSettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = getSection(at: section)
return section.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: WMFSettingsTableViewCell.identifier, for: indexPath) as? WMFSettingsTableViewCell else {
return UITableViewCell()
}
let item = getItem(at: indexPath)
configureCell(cell, item: item)
cellsToItemsThatNeedReloading[cell] = item
return cell
}
private func configureCell(_ cell: WMFSettingsTableViewCell, item: ExploreFeedSettingsItem) {
cell.configure(item.disclosureType, disclosureText: item.disclosureText, title: item.title, subtitle: item.subtitle, iconName: item.iconName, isSwitchOn: item.isOn, iconColor: item.iconColor, iconBackgroundColor: item.iconBackgroundColor, controlTag: item.controlTag, theme: theme)
cell.delegate = self
}
}
// MARK: - UITableViewDelegate
extension BaseExploreFeedSettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let section = getSection(at: section)
return section.headerTitle
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: WMFTableHeaderFooterLabelView.identifier) as? WMFTableHeaderFooterLabelView else {
return nil
}
let section = getSection(at: section)
footer.setShortTextAsProse(section.footerTitle)
footer.type = .footer
if let footer = footer as Themeable? {
footer.apply(theme: theme)
}
return footer
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard let _ = self.tableView(tableView, viewForFooterInSection: section) as? WMFTableHeaderFooterLabelView else {
return 0
}
return UITableViewAutomaticDimension
}
}
// MARK: - WMFSettingsTableViewCellDelegate
extension BaseExploreFeedSettingsViewController: WMFSettingsTableViewCellDelegate {
open func settingsTableViewCell(_ settingsTableViewCell: WMFSettingsTableViewCell!, didToggleDisclosureSwitch sender: UISwitch!) {
assertionFailure("Subclassers should override")
}
}
// MARK: - Themeable
extension BaseExploreFeedSettingsViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
tableView.backgroundColor = theme.colors.baseBackground
}
}
|
e8a3bf329108909228e440aafcd308f7
| 42.207668 | 289 | 0.715099 | false | false | false | false |
WeirdMath/SwiftyHaru
|
refs/heads/dev
|
Sources/SwiftyHaru/PDFDocument.swift
|
mit
|
1
|
//
// PDFDocument.swift
// SwiftyHaru
//
// Created by Sergej Jaskiewicz on 30.09.16.
//
//
import Foundation
#if SWIFT_PACKAGE
import CLibHaru
#endif
/// A handle to operate on a document object.
public final class PDFDocument {
internal var _documentHandle: HPDF_Doc
/// An array of pages in the document. Initially is empty. Use the `addPage()`, `addPage(width:height:)`,
/// `addPage(size:direction:)` or `insertPage(atIndex:)`, `insertPage(width:height:atIndex:)`,
/// `insertPage(size:direction:atIndex:)` methods to add pages to your document and populate this array.
public private(set) var pages: [PDFPage] = []
/// The fonts loaded in the document. Initially is empty. Use the `loadTrueTypeFont(from:embeddingGlyphData:)`
/// or `loadTrueTypeFontFromCollection(from:index:embeddingGlyphData:)` methods to load fonts.
///
/// This set does not include the base 14 fonts (see predefined values of `Font`)
/// that can be used in the document without loading any external fonts.
public private(set) var fonts: Set<Font> = []
internal var _error: PDFError
/// Creates an instance of a document object.
///
/// - returns: An instance of a document.
public init() {
_error = PDFError(code: HPDF_OK)
func errorHandler(errorCode: HPDF_STATUS,
detailCode: HPDF_STATUS,
userData: UnsafeMutableRawPointer?) {
let error = userData!.assumingMemoryBound(to: PDFError.self)
error.pointee = PDFError(code: Int32(errorCode))
// TODO: Must be removed in 1.0.0 release
#if DEBUG
print("An error in Haru. Code: \(error.pointee.code). \(error.pointee.description)")
#endif
}
_documentHandle = HPDF_New(errorHandler, &_error)
}
deinit {
HPDF_Free(_documentHandle)
}
// MARK: - Creating pages
private func _drawOnPage(_ page: PDFPage, _ draw: (DrawingContext) throws -> Void) rethrows -> PDFPage {
let context = DrawingContext(page: page, document: self)
defer { context._isInvalidated = true }
try draw(context)
return page
}
// In libHaru, each page object maintains a flag named "graphics mode".
// The graphics mode corresponds to the graphics-object of the PDF specification.
// The graphics mode is changed by invoking particular functions.
// The functions that can be invoked are decided by the value of the graphics mode.
// The following figure shows the relationships of the graphics mode.
//
// +=============================+
// / HPDF_GMODE_PAGE_DESCRIPTION /
// / /<-------------------------------+
// / Allowed operators: / |
// / * General graphics state / |
// / * Special graphics state /-----------------+ +---------------------+
// / * Color / | | HPDF_Page_EndText() |
// +=============================+ | +---------------------+
// | ^ | |
// | | +-----------------------+ |
// +-----------------------+ | | HPDF_Page_BeginText() | |
// | HPDF_Page_MoveTo() | | +-----------------------+ |
// | HPDF_Page_Rectangle() | | | |
// | HPDF_Page_Arc() | | V |
// | HPDF_Page_Circle() | | +========================+
// +-----------------------+ | / HPDF_GMODE_TEXT_OBJECT /
// | | / /
// | +-------------------------+ / Allowed operators /
// | | Path Painting Operators | / * Graphics state /
// | +-------------------------+ / * Color /
// | | / * Text state /
// V | / * Text-showing /
// +=============================+ / * Text-positioning /
// / HPDF_GMODE_PATH_OBJECT / +========================+
// / /
// / Allowed operators: /
// / * Path construction /
// +=============================+
//
// In SwiftyHaru we don't want the make the user maintain this state machine manually,
// so there are context objects of type DrawingContext which maintain it automatically.
// So each graphics mode except HPDF_GMODE_PAGE_DESCRIPTION is entered only during certain function calls.
//
// We invoke the `draw` closure that takes a context object and performs path construction
// or text creation on the context object which is connected with the page object.
/// Creates a new page and adds it after the last page of the document.
///
/// - Returns: A `PDFPage` object.
@discardableResult
public func addPage() -> PDFPage {
let haruPage = HPDF_AddPage(_documentHandle)!
let page = PDFPage(document: self, haruObject: haruPage)
pages.append(page)
return page
}
/// Creates a new page and adds it after the last page of the document.
///
/// - Parameter draw: The drawing operations to perform, or `nil` if no drawing should be performed.
/// - Returns: A `PDFPage` object.
/// - Warning: The `DrawingContext` object should not be stored and used outside of the lifetime
/// of the call to the closure.
@discardableResult
public func addPage(_ draw: (DrawingContext) throws -> Void) rethrows -> PDFPage {
return try _drawOnPage(addPage(), draw)
}
/// Creates a new page of the specified width and height and adds it after the last page of the document.
///
/// - Parameters:
/// - width: The width of the page.
/// - height: The height of the page.
/// - Returns: A `PDFPage` object.
@discardableResult
public func addPage(width: Float, height: Float) -> PDFPage {
let page = addPage()
page.width = width
page.height = height
return page
}
/// Creates a new page of the specified width and height and adds it after the last page of the document.
///
/// - Parameters:
/// - width: The width of the page.
/// - height: The height of the page.
/// - draw: The drawing operations to perform, or `nil` if no drawing should be performed.
/// - Returns: A `PDFPage` object.
/// - Warning: The `DrawingContext` object should not be stored and used outside of the lifetime
/// of the call to the closure.
@discardableResult
public func addPage(width: Float,
height: Float,
_ draw: (DrawingContext) throws -> Void) rethrows -> PDFPage {
return try _drawOnPage(addPage(width: width, height: height), draw)
}
/// Creates a new page of the specified size and direction and adds it after the last page of the document.
///
/// - Parameters:
/// - size: A predefined page-size value.
/// - direction: The direction of the page (portrait or landscape).
/// - Returns: A `PDFPage` object.
@discardableResult
public func addPage(size: PDFPage.Size,
direction: PDFPage.Direction) -> PDFPage {
let page = addPage()
page.set(size: size, direction: direction)
return page
}
/// Creates a new page of the specified size and direction and adds it after the last page of the document.
///
/// - Parameters:
/// - size: A predefined page-size value.
/// - direction: The direction of the page (portrait or landscape).
/// - draw: The drawing operations to perform, or `nil` if no drawing should be performed.
/// - Returns: A `PDFPage` object.
/// - Warning: The `DrawingContext` object should not be stored and used outside of the lifetime
/// of the call to the closure.
@discardableResult
public func addPage(size: PDFPage.Size,
direction: PDFPage.Direction,
_ draw: (DrawingContext) throws -> Void) rethrows -> PDFPage {
return try _drawOnPage(addPage(size: size, direction: direction), draw)
}
/// Creates a new page and inserts it just before the page with the specified index.
///
/// - Parameter index: The index at which the new page will appear. `index` must be a valid index
/// of the array `pages` or equal to its `endIndex` property.
/// - Returns: A `PDFPage` object.
@discardableResult
public func insertPage(atIndex index: Int) -> PDFPage {
if index == pages.endIndex {
return addPage()
}
let haruTargetPage = pages[index]._pageHandle
let haruInsertedPage = HPDF_InsertPage(_documentHandle, haruTargetPage)!
let page = PDFPage(document: self, haruObject: haruInsertedPage)
pages.insert(page, at: index)
return page
}
/// Creates a new page and inserts it just before the page with the specified index.
///
/// - Parameters:
/// - index: The index at which the new page will appear. `index` must be a valid index
/// of the array `pages` or equal to its `endIndex` property.
/// - draw: The drawing operations to perform, or `nil` if no drawing should be performed.
/// - Returns: A `PDFPage` object.
/// - Warning: The `DrawingContext` object should not be stored and used outside of the lifetime
/// of the call to the closure.
@discardableResult
public func insertPage(atIndex index: Int, _ draw: (DrawingContext) throws -> Void) rethrows -> PDFPage {
return try _drawOnPage(insertPage(atIndex: index), draw)
}
/// Creates a new page of the specified width and height and inserts it just before the page
/// with the specified index.
///
/// - Parameters:
/// - width: The width of the page.
/// - height: The height of the page.
/// - index: The index at which the new page will appear. `index` must be a valid index
/// of the array `pages` or equal to its `endIndex` property.
/// - Returns: A `PDFPage` object.
@discardableResult
public func insertPage(width: Float, height: Float, atIndex index: Int) -> PDFPage {
let page = insertPage(atIndex: index)
page.width = width
page.height = height
return page
}
/// Creates a new page of the specified width and height and inserts it just before the page
/// with the specified index.
///
/// - Parameters:
/// - width: The width of the page.
/// - height: The height of the page.
/// - index: The index at which the new page will appear. `index` must be a valid index
/// of the array `pages` or equal to its `endIndex` property.
/// - draw: The drawing operations to perform, or `nil` if no drawing should be performed.
/// - Returns: A `PDFPage` object.
/// - Warning: The `DrawingContext` object should not be stored and used outside of the lifetime
/// of the call to the closure.
@discardableResult
public func insertPage(width: Float,
height: Float,
atIndex index: Int,
_ draw: (DrawingContext) throws -> Void) rethrows -> PDFPage {
return try _drawOnPage(insertPage(width: width, height: height, atIndex: index), draw)
}
/// Creates a new page of the specified size and direction and inserts it just before the page
/// with the specified index.
///
/// - Parameters:
/// - size: A predefined page-size value.
/// - direction: The direction of the page (portrait or landscape).
/// - index: The index at which the new page will appear. `index` must be a valid index
/// of the array `pages` or equal to its `endIndex` property.
/// - Returns: A `PDFPage` object.
@discardableResult
public func insertPage(size: PDFPage.Size,
direction: PDFPage.Direction,
atIndex index: Int) -> PDFPage {
let page = insertPage(atIndex: index)
page.set(size: size, direction: direction)
return page
}
/// Creates a new page of the specified size and direction and inserts it just before the page
/// with the specified index.
///
/// - Parameters:
/// - size: A predefined page-size value.
/// - direction: The direction of the page (portrait or landscape).
/// - index: The index at which the new page will appear. `index` must be a valid index
/// of the array `pages` or equal to its `endIndex` property.
/// - draw: The drawing operations to perform, or `nil` if no drawing should be performed.
/// - Returns: A `PDFPage` object.
/// - Warning: The `DrawingContext` object should not be stored and used outside of the lifetime
/// of the call to the closure.
@discardableResult
public func insertPage(size: PDFPage.Size,
direction: PDFPage.Direction,
atIndex index: Int,
_ draw: (DrawingContext) throws -> Void) rethrows -> PDFPage {
return try _drawOnPage(insertPage(size: size, direction: direction, atIndex: index), draw)
}
// MARK: - Getting data
/// Renders the document and returns its contents.
///
/// - returns: The document's contents
public func getData() -> Data {
_renderMetadata()
HPDF_SaveToStream(_documentHandle)
let sizeOfStream = HPDF_GetStreamSize(_documentHandle)
HPDF_ResetStream(_documentHandle)
let buffer = UnsafeMutablePointer<HPDF_BYTE>.allocate(capacity: Int(sizeOfStream))
var sizeOfBuffer = sizeOfStream
HPDF_ReadFromStream(_documentHandle, buffer, &sizeOfBuffer)
let data = Data(bytes: buffer, count: Int(sizeOfBuffer))
buffer.deallocate()
return data
}
// MARK: - General pages parameters
/// Determines how pages should be displayed.
/// If this attribute is not set, the setting of the viewer application is used.
public var pageLayout: PageLayout {
get {
return PageLayout(haruEnum: HPDF_GetPageLayout(_documentHandle))
}
set {
HPDF_SetPageLayout(_documentHandle, HPDF_PageLayout(rawValue: newValue.rawValue))
}
}
/// Adds a page labeling range for the document. The page label is shown in the thumbnails view.
///
/// Example:
///
/// ```swift
/// document.addPageLabel(.lowerRoman, fromPage: 0, startingWith: 1)
/// document.addPageLabel(.decimal, fromPage: 4, startingWith: 1)
/// document.addPageLabel(.decimal, fromPage: 7, startingWith: 8, withPrefix: "A-")
/// ```
///
/// Result in a document with pages labeled:
///
/// i, ii, iii, iv, 1, 2, 3, A-8, A-9, ...
///
/// - parameter style: `PDFDocument.PageNumberStyle` enum case
/// - parameter startingPage: The first page that applies this labeling range.
/// - parameter firstPageNumber: The first page number to use.
/// - parameter prefix: The prefix for the page label. Default is `nil`.
public func addPageLabel(_ style: PageNumberStyle,
fromPage startingPage: Int,
startingWith firstPageNumber: Int,
withPrefix prefix: String = String()) {
prefix.withCString { cString in
_ = HPDF_AddPageLabel(_documentHandle,
HPDF_UINT(startingPage),
HPDF_PageNumStyle(rawValue: style.rawValue),
HPDF_UINT(firstPageNumber),
cString)
}
}
// MARK: - Including fonts
/// Loads a TrueType font from `data` and registers it to a document.
///
/// - parameter data: Contents of a `.ttf` file.
/// - parameter embeddingGlyphData: If this parameter is set to `true`, the glyph data of the font is embedded,
/// otherwise only the matrix data is included in PDF file.
///
/// - throws: `PDFError.invalidTTCIndex`, `PDFError.invalidTTCFile`,
/// `PDFError.ttfInvalidCMap`, `PDFError.ttfInvalidFormat`, `PDFError.ttfMissingTable`,
/// `PDFError.ttfCannotEmbedFont`.
///
/// - returns: The loaded font.
public func loadTrueTypeFont(from data: Data, embeddingGlyphData: Bool) throws -> Font {
let embedding = embeddingGlyphData ? HPDF_TRUE : HPDF_FALSE
let name = data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) -> String? in
let cString = HPDF_LoadTTFontFromMemory(self._documentHandle,
pointer,
HPDF_UINT(data.count),
embedding)
if let cString = cString {
return String(cString: cString)
} else {
return nil
}
}
if let name = name {
let font = Font(name: name)
fonts.insert(font)
return font
} else {
HPDF_ResetError(_documentHandle)
throw _error
}
}
/// Loads a TrueType font from a TrueType Collection and registers it to a document.
///
/// - parameter data: Contents of a `.ttc` file.
/// - parameter index: The index of the font to be loaded.
/// - parameter embeddingGlyphData: If this parameter is set to `true`, the glyph data of the font is embedded,
/// otherwise only the matrix data is included in PDF file.
///
/// - throws: `PDFError.invalidTTCIndex`, `PDFError.invalidTTCFile`,
/// `PDFError.ttfInvalidCMap`, `PDFError.ttfInvalidFormat`, `PDFError.ttfMissingTable`,
/// `PDFError.ttfCannotEmbedFont`.
///
/// - returns: The loaded font.
public func loadTrueTypeFontFromCollection(from data: Data,
index: Int,
embeddingGlyphData: Bool) throws -> Font {
let embedding = embeddingGlyphData ? HPDF_TRUE : HPDF_FALSE
let name = data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) -> String? in
HPDF_LoadTTFontFromMemory2(self._documentHandle,
pointer,
HPDF_UINT(data.count),
HPDF_UINT(index),
embedding).map(String.init)
}
if let name = name {
let font = Font(name: name)
fonts.insert(font)
return font
} else {
HPDF_ResetError(_documentHandle)
throw _error
}
}
private var _jpEncodingsEnabled = false
private var _krEncodingsEnabled = false
private var _cnsEncodingsEnabled = false
private var _cntEncodingsEnabled = false
private var _utfEncodingsEnabled = false
internal func _useJPEncodings() {
if !_jpEncodingsEnabled {
HPDF_UseJPEncodings(_documentHandle)
_jpEncodingsEnabled = true
}
}
internal func _useKREncodings() {
if !_krEncodingsEnabled {
HPDF_UseKREncodings(_documentHandle)
_krEncodingsEnabled = true
}
}
internal func _useCNSEncodings() {
if !_cnsEncodingsEnabled {
HPDF_UseCNSEncodings(_documentHandle)
_cnsEncodingsEnabled = true
}
}
internal func _useCNTEncodings() {
if !_cntEncodingsEnabled {
HPDF_UseCNTEncodings(_documentHandle)
_cntEncodingsEnabled = true
}
}
internal func _useUTFEncodings() {
if !_utfEncodingsEnabled {
HPDF_UseUTFEncodings(_documentHandle)
_utfEncodingsEnabled = true
}
}
// MARK: - Compression
/// Set the mode of compression.
///
/// - Parameter mode: The mode of compression (may be combined).
/// - Throws: `PDFError.invalidCompressionMode` if the provided compression mode was invalid.
public func setCompressionMode(to mode: CompressionMode) throws {
if HPDF_SetCompressionMode(_documentHandle, HPDF_UINT(mode.rawValue)) != UInt(HPDF_OK) {
HPDF_ResetError(_documentHandle)
throw _error
}
}
// MARK: - Security
/// Sets the encryption mode. As a side effect, ups the version of PDF to 1.4
/// when the mode is set to `.r3`.
///
/// - Important: Prior to calling this method you must set the password using
/// the `setPassword(owner:user:)` method.
///
/// - Parameter mode: The encryption mode to set.
/// - Throws: `PDFError.invalidEncryptionKeyLength` if an invalid key length was specified;
/// `PDFError.documentEncryptionDictionaryNotFound` if you haven't set a password.
private func _setEncryptionMode(to mode: EncryptionMode) throws {
let haruMode: HPDF_EncryptMode
let keyLength: HPDF_UINT
switch mode {
case .r2:
haruMode = HPDF_ENCRYPT_R2
keyLength = 5
case .r3(keyLength: let length):
haruMode = HPDF_ENCRYPT_R3
if length < 0 { throw PDFError.invalidEncryptionKeyLength }
keyLength = HPDF_UINT(length)
}
if HPDF_SetEncryptionMode(_documentHandle, haruMode, keyLength) != UInt(HPDF_OK) {
HPDF_ResetError(_documentHandle)
throw _error
}
}
private func _setPermissions(to permissions: Permissions) throws {
if HPDF_SetPermission(_documentHandle, HPDF_UINT(permissions.rawValue)) != UInt(HPDF_OK) {
HPDF_ResetError(_documentHandle)
throw _error
}
}
/// Sets a password for the document. If the password is set, the document contents are encrypted.
///
/// - Parameters:
/// - owner: The password for the owner of the document. The owner can change the permission of the document.
/// Zero length string and the same value as user password are not allowed.
/// - user: The password for the user of the document. May be set to `nil` or zero length string.
/// - permissions: The permission flags for the document. Default is `nil`.
/// - encryptionMode: The encryption mode. Ups the version of PDF to 1.4 when the mode is set to `.r3`.
/// Default is `nil`.
/// - Throws: `PDFError.encryptionInvalidPassword` if the owner password is zero length string or
/// same value as the user password; `PDFError.invalidEncryptionKeyLength` if an invalid key length
/// was specified.
public func setPassword(owner: String,
user: String? = nil,
permissions: Permissions? = nil,
encryptionMode: EncryptionMode? = nil) throws {
guard !owner.isEmpty, owner != user else {
throw PDFError.encryptionInvalidPassword
}
let status: HPDF_STATUS
// Workaround for https://bugs.swift.org/browse/SR-2814
if let user = user {
status = HPDF_SetPassword(_documentHandle, owner, user)
} else {
status = HPDF_SetPassword(_documentHandle, owner, nil)
}
if status != UInt(HPDF_OK) {
HPDF_ResetError(_documentHandle)
throw _error
}
try permissions.map(_setPermissions)
try encryptionMode.map(_setEncryptionMode)
}
// MARK: - Document Info
private lazy var _dateFormatter = PDFDateFormatter()
private func _setAttribute(_ attr: HPDF_InfoType, to value: String?) {
// Workaround for https://bugs.swift.org/browse/SR-2814
if let value = value {
HPDF_SetInfoAttr(_documentHandle, attr, value)
} else {
HPDF_SetInfoAttr(_documentHandle, attr, nil)
}
}
private func _renderMetadata() {
_setAttribute(HPDF_INFO_AUTHOR, to: metadata.author)
_setAttribute(HPDF_INFO_CREATOR, to: metadata.creator)
_setAttribute(HPDF_INFO_TITLE, to: metadata.title)
_setAttribute(HPDF_INFO_SUBJECT, to: metadata.subject)
_setAttribute(HPDF_INFO_KEYWORDS, to: metadata.keywords?.joined(separator: ", "))
let creationDateString = metadata.creationDate.flatMap {
_dateFormatter.string(from: $0, timeZone: metadata.timeZone)
}
_setAttribute(HPDF_INFO_CREATION_DATE, to: creationDateString)
let modificationDateString = metadata.modificationDate.flatMap {
_dateFormatter.string(from: $0, timeZone: metadata.timeZone)
}
_setAttribute(HPDF_INFO_MOD_DATE, to: modificationDateString)
}
/// The metadata of the document: an author, keywords, creation date etc.
public var metadata: Metadata = Metadata()
}
|
0444af55597c46e446002152c9dc6468
| 40.9424 | 115 | 0.561303 | false | false | false | false |
fanyinan/ImagePickerProject
|
refs/heads/master
|
ImagePickerDemo/ImagePickerProject/ViewController.swift
|
bsd-2-clause
|
1
|
//
// ViewController.swift
// PhotoBrowserProject
//
// Created by 范祎楠 on 15/11/25.
// Copyright © 2015年 范祎楠. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var isCropSwitch: UISwitch!
@IBOutlet var maxCountTextField: UITextField!
@IBOutlet var imageViews: [UIImageView]!
private lazy var imagePickerHelper = WZImagePickerHelper(delegate: self)
var isCrop: Bool = false
var type: WZImagePickerType = .albumAndCamera
var maxCount = 3
var reourceOption: WZResourceOption = [.image]
@IBAction func onStart() {
imagePickerHelper.isCrop = isCrop
imagePickerHelper.maxSelectedCount = maxCount
imagePickerHelper.type = type
imagePickerHelper.resourceOption = reourceOption
imagePickerHelper.start()
}
@IBAction func onIsCrop(_ sender: UISwitch) {
isCrop = sender.isOn
if isCrop {
maxCountTextField.text = "1"
maxCount = 1
}
}
@IBAction func onStyle(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
type = .albumAndCamera
case 1:
type = .album
case 2:
type = .camera
default:
break
}
}
@IBAction func onResourceType(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
reourceOption = [.image, .data]
case 1:
reourceOption = .video
default:
break
}
}
@IBAction func onCountChange(_ sender: UITextField) {
guard let maxCount = Int(sender.text!) else { return }
self.maxCount = maxCount
if maxCount != 1 {
isCropSwitch.setOn(false, animated: true)
}
}
}
extension ViewController: WZImagePickerDelegate {
func pickedPhoto(_ imagePickerHelper: WZImagePickerHelper, didPickResource resource: WZResourceType) {
print(#function)
if case .video(videos: let tmpAVAssets) = resource {
tmpAVAssets.forEach{print($0)}
}
if case .rawImageData(imageData: let imageData) = resource, let _imageData = imageData {
print(_imageData.count)
}
if case .image(images: let images) = resource {
print(images.count)
for (index, image) in images.enumerated() {
if index >= imageViews.count {
return
}
imageViews[index].image = image
}
}
}
}
|
119aefc0ca8c96eb9e4fe2df358bd376
| 21.036697 | 104 | 0.638634 | false | false | false | false |
tlax/GaussSquad
|
refs/heads/master
|
GaussSquad/View/LinearEquations/Plot/VLinearEquationsPlotBarZoom.swift
|
mit
|
1
|
import UIKit
class VLinearEquationsPlotBarZoom:UIView
{
private weak var controller:CLinearEquationsPlot!
private weak var stepper:UIStepper!
private weak var label:UILabel!
private let numberFormatter:NumberFormatter
private let kMinInteger:Int = 1
private let kMinFraction:Int = 0
private let kMaxFraction:Int = 3
private let kLabelRight:CGFloat = -10
private let kLabelWidth:CGFloat = 70
private let kLabelBottom:CGFloat = -8
private let kLabelHeight:CGFloat = 30
private let kStepperWidth:CGFloat = 110
private let kStepperHeight:CGFloat = 38
private let kMinZoom:Double = -28
private let kMaxZoom:Double = 30
init(controller:CLinearEquationsPlot)
{
numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.minimumFractionDigits = kMinFraction
numberFormatter.maximumFractionDigits = kMaxFraction
numberFormatter.minimumIntegerDigits = kMinInteger
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.right
label.font = UIFont.bold(size:14)
label.textColor = UIColor.black
self.label = label
let stepper:UIStepper = UIStepper()
stepper.translatesAutoresizingMaskIntoConstraints = false
stepper.tintColor = UIColor.black
stepper.minimumValue = kMinZoom
stepper.maximumValue = kMaxZoom
stepper.value = controller.model.zoom
stepper.addTarget(
self,
action:#selector(actionStepper(sender:)),
for:UIControlEvents.valueChanged)
self.stepper = stepper
addSubview(label)
addSubview(stepper)
NSLayoutConstraint.bottomToBottom(
view:stepper,
toView:self)
NSLayoutConstraint.height(
view:stepper,
constant:kStepperHeight)
NSLayoutConstraint.rightToRight(
view:stepper,
toView:self)
NSLayoutConstraint.width(
view:stepper,
constant:kStepperWidth)
NSLayoutConstraint.bottomToBottom(
view:label,
toView:self,
constant:kLabelBottom)
NSLayoutConstraint.height(
view:label,
constant:kLabelHeight)
NSLayoutConstraint.rightToLeft(
view:label,
toView:stepper,
constant:kLabelRight)
NSLayoutConstraint.width(
view:label,
constant:kLabelWidth)
showZoom()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionStepper(sender stepper:UIStepper)
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
var value:Double = stepper.value
if value < 1
{
let negativeValue:Double = abs(value - 2)
value = 1 / negativeValue
}
self?.controller.updateZoom(zoom:value)
DispatchQueue.main.async
{ [weak self] in
self?.showZoom()
}
}
}
//MARK: private
private func showZoom()
{
let zoom:Double = controller.model.zoom
let zoomNumber:NSNumber = zoom as NSNumber
guard
let zoomString:String = numberFormatter.string(from:zoomNumber)
else
{
return
}
let zoomDescr:String = String(
format:NSLocalizedString("VLinearEquationsPlotBarZoom_descr", comment:""),
zoomString)
label.text = zoomDescr
}
}
|
35ceb501f6f9770a0e750056c47a682f
| 28.957447 | 86 | 0.598958 | false | false | false | false |
apple/swift-corelibs-foundation
|
refs/heads/main
|
Darwin/Foundation-swiftoverlay/NSUndoManager.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
@_implementationOnly import _FoundationOverlayShims
extension UndoManager {
@available(*, unavailable, renamed: "registerUndo(withTarget:handler:)")
public func registerUndoWithTarget<TargetType : AnyObject>(_ target: TargetType, handler: (TargetType) -> Void) {
fatalError("This API has been renamed")
}
@available(macOS 10.11, iOS 9.0, *)
public func registerUndo<TargetType : AnyObject>(withTarget target: TargetType, handler: @escaping (TargetType) -> Void) {
__NSUndoManagerRegisterWithTargetHandler( self, target) { internalTarget in
handler(internalTarget as! TargetType)
}
}
}
|
de055657d5b8fdacdbf74eb659a49d39
| 41.214286 | 124 | 0.641286 | false | false | false | false |
mibaldi/ChildBeaconApp
|
refs/heads/publish
|
ChildBeaconProject/BD/BeaconGroupDataHelper.swift
|
apache-2.0
|
1
|
//
// IngredientDataHelper.swift
// iosAPP
//
// Created by mikel balduciel diaz on 17/2/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import Foundation
import SQLite
class BeaconGroupDataHelper: DataHelperProtocol {
static let TABLE_NAME = "BeaconsGroups"
static let table = Table(TABLE_NAME)
// let storage = Table("users")
static let beaconGroupId = Expression<Int64>("beaconGroupId")
static let name = Expression<String>("name")
static let uuid = Expression<String>("UUID")
typealias T = BeaconGroup
static func createTable() throws {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
do {
let _ = try DB.run(table.create(temporary: false, ifNotExists: true) { t in
t.column(beaconGroupId, primaryKey: true)
t.column(name, unique: true)
t.column(uuid, unique: true)
})
}catch _ {
print("error create table")
}
}
static func insert (item: T) throws -> Int64 {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let insert = table.insert(name <- item.name,uuid <- item.UUID)
do {
let rowId = try DB.run(insert)
guard rowId > 0 else {
throw DataAccessError.Insert_Error
}
return rowId
}catch _ {
throw DataAccessError.Insert_Error
}
}
static func delete (item: T) throws -> Void {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(beaconGroupId == item.beaconGroupId)
do {
let tmp = try DB.run(query.delete())
guard tmp == 1 else {
throw DataAccessError.Delete_Error
}
} catch _ {
throw DataAccessError.Delete_Error
}
}
/* static func updateStorage (item: T) throws -> Void {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(ingredientId == item.ingredientId)
do {
let tmp = try DB.run(query.update(storageId <- item.storageId))
guard tmp == 1 else {
throw DataAccessError.Delete_Error
}
} catch _ {
throw DataAccessError.Delete_Error
}
}
static func updateCart (item: T) throws -> Void {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(ingredientId == item.ingredientId)
do {
let tmp = try DB.run(query.update(cartId <- item.cartId))
guard tmp == 1 else {
throw DataAccessError.Delete_Error
}
} catch _ {
throw DataAccessError.Delete_Error
}
}
static func findIngredientsInStorage () throws -> [T]? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(storageId == 1)
var retArray = [T]()
let items = try DB.prepare(query)
for item in items {
let ingredient = Ingredient()
ingredient.ingredientId = item[ingredientId]
ingredient.ingredientIdServer = item[ingredientIdServer]
ingredient.name = item[name]
ingredient.baseType = item[baseType]
ingredient.category = item[category]
ingredient.frozen = FrozenTypes(rawValue: item[frozen])!
ingredient.storageId = item[storageId]
ingredient.cartId = item[cartId]
retArray.append(ingredient)
}
return retArray
}
static func findIngredientsNotInStorage () throws -> [T]? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(storageId != 1)
var retArray = [T]()
let items = try DB.prepare(query)
for item in items {
let ingredient = Ingredient()
ingredient.ingredientId = item[ingredientId]
ingredient.ingredientIdServer = item[ingredientIdServer]
ingredient.name = item[name]
ingredient.baseType = item[baseType]
ingredient.category = item[category]
ingredient.frozen = FrozenTypes(rawValue: item[frozen])!
ingredient.storageId = item[storageId]
ingredient.cartId = item[cartId]
retArray.append(ingredient)
}
return retArray
}
static func findIngredientsNotInStorageCart () throws -> [T]? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(storageId != 1)
let query2 = query.filter(cartId != 1)
var retArray = [T]()
let items = try DB.prepare(query2)
for item in items {
let ingredient = Ingredient()
ingredient.ingredientId = item[ingredientId]
ingredient.ingredientIdServer = item[ingredientIdServer]
ingredient.name = item[name]
ingredient.baseType = item[baseType]
ingredient.category = item[category]
ingredient.frozen = FrozenTypes(rawValue: item[frozen])!
ingredient.storageId = item[storageId]
ingredient.cartId = item[cartId]
retArray.append(ingredient)
}
return retArray
}
static func findIngredientsInCart () throws -> [T]? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(cartId == 1)
var retArray = [T]()
let items = try DB.prepare(query)
for item in items {
let ingredient = Ingredient()
ingredient.ingredientId = item[ingredientId]
ingredient.ingredientIdServer = item[ingredientIdServer]
ingredient.name = item[name]
ingredient.baseType = item[baseType]
ingredient.category = item[category]
ingredient.frozen = FrozenTypes(rawValue: item[frozen])!
ingredient.storageId = item[storageId]
ingredient.cartId = item[cartId]
retArray.append(ingredient)
}
return retArray
}*/
static func find(id: Int64) throws -> T? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(beaconGroupId == id)
let items = try DB.prepare(query)
for item in items {
let beaconGroup = BeaconGroup()
beaconGroup.beaconGroupId = item[beaconGroupId]
beaconGroup.name = item[name]
beaconGroup.UUID = item[uuid]
return beaconGroup
}
return nil
}
/*static func findIdServer(id: Int64) throws -> T? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(ingredientIdServer == id)
let items = try DB.prepare(query)
for item in items {
let ingredient = Ingredient()
ingredient.ingredientId = item[ingredientId]
ingredient.ingredientIdServer = item[ingredientIdServer]
ingredient.name = item[name]
ingredient.baseType = item[baseType]
ingredient.category = item[category]
ingredient.frozen = FrozenTypes(rawValue: item[frozen])!
ingredient.storageId = item[storageId]
ingredient.cartId = item[cartId]
return ingredient
}
return nil
}*/
static func findAll() throws -> [T]? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
var retArray = [T]()
let items = try DB.prepare(table)
for item in items {
let beaconGroup = BeaconGroup()
beaconGroup.beaconGroupId = item[beaconGroupId]
beaconGroup.name = item[name]
beaconGroup.UUID = item[uuid]
retArray.append(beaconGroup)
}
return retArray
}
}
|
489ab0d54ac0d00d217620b309c4bd2e
| 34.960159 | 87 | 0.576731 | false | false | false | false |
Scorocode/scorocode-SDK-swift
|
refs/heads/master
|
todolist/SCLib/Model/SCValue.swift
|
mit
|
1
|
//
// SCFieldType.swift
// SC
//
// Created by Alexey Kuznetsov on 27/12/2016.
// Copyright © 2016 Prof-IT Group OOO. All rights reserved.
//
import Foundation
public protocol SCPullable {
}
public protocol SCValue: SCPullable {
var apiValue: Any { get }
}
public struct SCBool: SCValue {
let value: Bool
public init(_ value: Bool) {
self.value = value
}
public var apiValue: Any {
return value as Any
}
}
public struct SCString: SCValue {
let value: String
public init(_ value: String) {
self.value = value
}
public var apiValue: Any {
return value as Any
}
}
public struct SCInt: SCValue {
let value: Int
public init(_ value: Int) {
self.value = value
}
public var apiValue: Any {
return value as Any
}
}
public struct SCDouble: SCValue {
let value: Double
public init(_ value: Double) {
self.value = value
}
public var apiValue: Any {
return value as Any
}
}
public struct SCDate: SCValue {
let value: Date
public init(_ value: Date) {
self.value = value
}
public var apiValue: Any {
let en_US_POSIX = Locale(identifier: "en_US_POSIX")
let rfc3339DateFormatter = DateFormatter()
rfc3339DateFormatter.locale = en_US_POSIX
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssXXX"
rfc3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return rfc3339DateFormatter.string(from: value) as Any
}
}
public struct SCArray: SCValue {
let value: [SCValue]
public init(_ value: [SCValue]) {
self.value = value
}
public var apiValue: Any {
return value.map({ $0.apiValue })
}
public init(stringArray: [String]) {
self.value = stringArray.map({SCString($0)})
}
public init(integerArray: [Int]) {
self.value = integerArray.map({SCInt($0)})
}
public init(doubleArray: [Double]) {
self.value = doubleArray.map({SCDouble($0)})
}
public init(boolArray: [Bool]) {
self.value = boolArray.map({SCBool($0)})
}
public init(dateArray: [Date]) {
self.value = dateArray.map({SCDate($0)})
}
}
public struct SCDictionary: SCValue {
let value: [String: SCValue]
public init(_ value: [String: SCValue]) {
self.value = value
}
public var apiValue: Any {
var result = [String: Any]()
for (key, val) in value {
result[key] = val.apiValue
}
return result as Any
}
}
public func == (lhs: [SCValue], rhs: [SCValue]) -> Bool {
if lhs.count != rhs.count {
return false
}
for (index, leftValue) in lhs.enumerated() {
if leftValue != rhs[index] {
return false
}
}
return true
}
public func == (lhs: [String: SCValue], rhs: [String: SCValue]) -> Bool {
if lhs.count != rhs.count {
return false
}
for (key, leftValue) in lhs {
if rhs[key] == nil || rhs[key]! != leftValue {
return false
}
}
return true
}
public func !=(lhs: SCValue, rhs: SCValue) -> Bool {
return !(lhs == rhs)
}
public func ==(lhs: SCValue, rhs: SCValue) -> Bool {
if lhs is SCBool && rhs is SCBool {
return (lhs as! SCBool).value == (rhs as! SCBool).value
}
if lhs is SCString && rhs is SCString {
return (lhs as! SCString).value == (rhs as! SCString).value
}
if lhs is SCInt && rhs is SCInt {
return (lhs as! SCInt).value == (rhs as! SCInt).value
}
if lhs is SCDouble && rhs is SCDouble {
return (lhs as! SCDouble).value == (rhs as! SCDouble).value
}
if lhs is SCDate && rhs is SCDate {
return (lhs as! SCDate).value == (rhs as! SCDate).value
}
if lhs is SCArray && rhs is SCArray {
return (lhs as! SCArray).value == (rhs as! SCArray).value
}
if lhs is SCDictionary && rhs is SCDictionary {
return (lhs as! SCDictionary).value == (rhs as! SCDictionary).value
}
return false
}
|
39a770e6484540198168640a5befa05d
| 21.390374 | 76 | 0.568904 | false | false | false | false |
zarochintsev/MotivationBox
|
refs/heads/master
|
Pods/Swinject/Sources/Container.Arguments.swift
|
mit
|
1
|
//
// Container.Arguments.swift
// Swinject
//
// Created by Yoichi Tagaya on 8/18/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
//
// NOTICE:
//
// Container.Arguments.swift is generated from Container.Arguments.erb by ERB.
// Do NOT modify Container.Arguments.swift directly.
// Instead, modify Container.Arguments.erb and run `script/gencode` at the project root directory to generate the code.
//
import Foundation
// MARK: - Registeration with Arguments
extension Container {
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 1 argument to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 2 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 3 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2, Arg3>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2, Arg3) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 4 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2, Arg3, Arg4>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 5 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 6 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 7 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 8 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `Resolver` instance and 9 arguments to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
}
// MARK: - Resolver with Arguments
extension Container {
/// Retrieves the instance with the specified service type and 1 argument to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - argument: 1 argument to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and 1 argument is found in the `Container`.
public func resolve<Service, Arg1>(
_ serviceType: Service.Type,
argument: Arg1) -> Service?
{
return resolve(serviceType, name: nil, argument: argument)
}
/// Retrieves the instance with the specified service type, 1 argument to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - argument: 1 argument to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// 1 argument and name is found in the `Container`.
public func resolve<Service, Arg1>(
_ serviceType: Service.Type,
name: String?,
argument: Arg1) -> Service?
{
typealias FactoryType = (Resolver, Arg1) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, argument) }
}
/// Retrieves the instance with the specified service type and list of 2 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 2 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 2 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2)
}
/// Retrieves the instance with the specified service type, list of 2 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 2 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 2 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2) }
}
/// Retrieves the instance with the specified service type and list of 3 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 3 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 3 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3)
}
/// Retrieves the instance with the specified service type, list of 3 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 3 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 3 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2, Arg3) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2, arg3) }
}
/// Retrieves the instance with the specified service type and list of 4 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 4 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 4 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4)
}
/// Retrieves the instance with the specified service type, list of 4 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 4 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 4 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2, Arg3, Arg4) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2, arg3, arg4) }
}
/// Retrieves the instance with the specified service type and list of 5 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 5 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 5 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5)
}
/// Retrieves the instance with the specified service type, list of 5 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 5 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 5 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2, arg3, arg4, arg5) }
}
/// Retrieves the instance with the specified service type and list of 6 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 6 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 6 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6)
}
/// Retrieves the instance with the specified service type, list of 6 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 6 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 6 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2, arg3, arg4, arg5, arg6) }
}
/// Retrieves the instance with the specified service type and list of 7 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 7 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 7 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7)
}
/// Retrieves the instance with the specified service type, list of 7 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 7 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 7 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2, arg3, arg4, arg5, arg6, arg7) }
}
/// Retrieves the instance with the specified service type and list of 8 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 8 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 8 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
}
/// Retrieves the instance with the specified service type, list of 8 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 8 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 8 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) }
}
/// Retrieves the instance with the specified service type and list of 9 arguments to the factory closure.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - arguments: List of 9 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// and list of 9 arguments is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>(
_ serviceType: Service.Type,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8, _ arg9: Arg9) -> Service?
{
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
}
/// Retrieves the instance with the specified service type, list of 9 arguments to the factory closure and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
/// - arguments: List of 9 arguments to pass to the factory closure.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type,
/// list of 9 arguments and name is found in the `Container`.
public func resolve<Service, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9>(
_ serviceType: Service.Type,
name: String?,
arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4, _ arg5: Arg5, _ arg6: Arg6, _ arg7: Arg7, _ arg8: Arg8, _ arg9: Arg9) -> Service?
{
typealias FactoryType = (Resolver, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) }
}
}
|
40258a1de5abbbe6dd92a49c3cfe6b9e
| 52.052734 | 153 | 0.634724 | false | false | false | false |
edstewbob/cs193p-winter-2015
|
refs/heads/master
|
GraphingCalculator/GraphingCalculator/CalculatorViewController.swift
|
mit
|
2
|
//
// CalculatorViewController.swift
// GraphingCalculator
//
// Created by jrm on 4/5/15.
// Copyright (c) 2015 Riesam LLC. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController {
@IBOutlet weak var history: UILabel!
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
var numberHasADecimalPoint = false
var brain = CalculatorBrain()
@IBAction func back(sender: UIButton) {
if userIsInTheMiddleOfTypingANumber {
if count(display.text!) > 0 {
var text = display.text!
text = dropLast(text)
if count(text) > 0 {
display.text = text
}else{
display.text = " "
}
}
}else{
//remove last item from program/brain opStack
if let result = brain.removeLast() {
displayValue = result
} else {
displayValue = 0
}
updateUI()
}
//addToHistory("🔙")
}
@IBAction func plusMinus(sender: UIButton) {
if userIsInTheMiddleOfTypingANumber {
//change the sign of the number and allow typing to continue
var text = display.text!
if(text[text.startIndex] == "-"){
display.text = dropFirst(text)
}else{
display.text = "-" + text
}
//addToHistory("±")
}else{
operate(sender)
}
}
@IBAction func appendDigit(sender: UIButton) {
if let digit = sender.currentTitle{
if( numberHasADecimalPoint && digit == "."){
// do nothing additional decimal point is not allowed
}else {
if (digit == "."){
numberHasADecimalPoint = true
}
if userIsInTheMiddleOfTypingANumber {
var text = display.text!
if(text[text.startIndex] == "0"){
text = dropFirst(text)
}
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
//println("digit = \(digit)")
}
updateUI()
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
if let operation = sender.currentTitle {
if let result = brain.performOperation(operation) {
displayValue = result
} else {
displayValue = nil
}
}
updateUI()
}
@IBAction func clear(sender: UIButton) {
display.text = " "
brain.clear()
brain.variableValues.removeValueForKey("M")
updateUI()
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
if let value = displayValue{
if let result = brain.pushOperand(value) {
displayValue = result
} else {
displayValue = nil
}
}else {
displayValue = nil
}
updateUI()
}
@IBAction func saveMemory() {
if let value = displayValue {
brain.variableValues["M"] = value
}
userIsInTheMiddleOfTypingANumber = false
if let result = brain.evaluate() {
displayValue = result
} else {
displayValue = nil
}
updateUI()
}
@IBAction func loadMemory() {
if let result = brain.pushOperand("M") {
displayValue = result
} else {
displayValue = nil
}
updateUI()
}
var displayValue: Double? {
get {
return NSNumberFormatter().numberFromString(display.text!)?.doubleValue
}
set {
if let value = newValue{
display.text = "\(value)"
} else {
//if let result = brain.evaluateAndReportErrors() as? String {
// display.text = result
//} else {
display.text = " "
//}
}
userIsInTheMiddleOfTypingANumber = false
}
}
func updateUI(){
history.text = brain.description
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
var destination = segue.destinationViewController as? UIViewController
if let navCon = destination as? UINavigationController {
destination = navCon.visibleViewController
}
if let identifier = segue.identifier {
switch identifier {
case "Show Graph View":
if let gvc = destination as? GraphViewController {
//println("CVC.prepareForSegue: brain.program \(brain.program) ")
gvc.program = brain.program
}
default:
break
}
}
}
}
|
ea5ded90dc22211b5e07936fde0e6461
| 26.85567 | 89 | 0.486306 | false | false | false | false |
CCRogerWang/ReactiveWeatherExample
|
refs/heads/master
|
WhatsTheWeatherIn/WeatherOverviewViewController.swift
|
mit
|
1
|
//
// WeatherTableViewController.swift
// WhatsTheWeatherIn
//
// Created by Marin Bencevic on 17/10/15.
// Copyright © 2015 marinbenc. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
//MARK: - ForecastModel
///Represents a presentation layer model for a Forecast, to be displayed in a UITableViewCell
struct ForecastModel {
let time: String
let description: String
let temp: String
}
//MARK: -
//MARK: - WeatherOverviewViewController
final class WeatherOverviewViewController: UIViewController {
//MARK: - Dependencies
fileprivate var viewModel: WeatherViewModel!
fileprivate let disposeBag = DisposeBag()
//MARK: - Outlets
@IBOutlet weak var forecastsTableView: UITableView!
@IBOutlet weak var cityTextField: UITextField!
@IBOutlet weak var cityNameLabel: UILabel!
@IBOutlet weak var cityDegreesLabel: UILabel!
@IBOutlet weak var weatherMessageLabel: UILabel!
@IBOutlet weak var weatherIconImageView: UIImageView!
@IBOutlet weak var weatherBackgroundImageView: UIImageView!
///table view header (current weather display)
@IBOutlet weak var weatherView: UIView!
//MARK: - Lifecycle
fileprivate func addBindsToViewModel(_ viewModel: WeatherViewModel) {
cityTextField.rx.text
.orEmpty
.bindTo(viewModel.searchText)
.addDisposableTo(disposeBag)
viewModel.cityName
.bindTo(cityNameLabel.rx.text)
.addDisposableTo(disposeBag)
viewModel.temp
.bindTo(cityDegreesLabel.rx.text)
.addDisposableTo(disposeBag)
viewModel.weatherDescription
.bindTo(weatherMessageLabel.rx.text)
.addDisposableTo(disposeBag)
viewModel.weatherImageData
.map(UIImage.init)
.bindTo(weatherIconImageView.rx.image)
.addDisposableTo(disposeBag)
viewModel.weatherBackgroundImage
.map { $0.image }
.bindTo(weatherBackgroundImageView.rx.image)
.addDisposableTo(disposeBag)
viewModel.cellData
.bindTo(forecastsTableView.rx.items(dataSource: self))
.addDisposableTo(disposeBag)
}
override func viewDidLoad() {
super.viewDidLoad()
forecastsTableView.delegate = self
viewModel = WeatherViewModel(weatherService: WeatherAPIService())
addBindsToViewModel(viewModel)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Set Forecast views hight to cover the whole screen
forecastsTableView.tableHeaderView?.bounds.size.height = view.bounds.height
//A dirty UIKit bug workaround to force a UI update on the TableView's header
forecastsTableView.tableHeaderView = forecastsTableView.tableHeaderView
}
//MARK: - TableViewData
//The data to update the tableView with. These is a better way to update the
//tableView with RxSwift, please see
//https://github.com/ReactiveX/RxSwift/tree/master/RxExample
//However this implementation is much simpler
fileprivate var tableViewData: [(day: String, forecasts: [ForecastModel])]? {
didSet {
forecastsTableView.reloadData()
}
}
}
//MARK: - Table View Data Source & Delegate
extension WeatherOverviewViewController: UITableViewDataSource, RxTableViewDataSourceType {
//Gets called on tableView.rx_elements.bindTo methods
func tableView(_ tableView: UITableView, observedEvent: Event<[(day: String, forecasts: [ForecastModel])]>) {
switch observedEvent {
case .next(let items):
tableViewData = items
case .error(let error):
print(error)
presentError()
case .completed:
tableViewData = nil
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return tableViewData?.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return tableViewData?[section].day
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewData?[section].forecasts.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "forecastCell", for: indexPath) as! ForecastTableViewCell
guard let forecast = tableViewData?[indexPath.section].forecasts[indexPath.row] else {
return cell
}
cell.cityDegreesLabel.text = forecast.temp
cell.dateLabel.text = forecast.time
cell.weatherMessageLabel.text = forecast.description
return cell
}
}
extension WeatherOverviewViewController: UITableViewDelegate {}
|
61839f6c1d46f0333e01ccee7327ba92
| 29.313253 | 122 | 0.660175 | false | false | false | false |
macfeteria/swift-line-echobot-demo
|
refs/heads/master
|
Sources/Line.swift
|
mit
|
1
|
//
// Line.swift
// demo
//
// Created by Ter on 3/14/17.
//
//
import Foundation
import Cryptor
import SwiftyJSON
public func validateSignature( message: String, signature: String , secretKey: String) -> Bool {
let key = CryptoUtils.byteArray(from: secretKey)
let data : [UInt8] = CryptoUtils.byteArray(from: message)
if let hmac = HMAC(using: HMAC.Algorithm.sha256, key: key).update(byteArray: data)?.final() {
let hmacData = Data(hmac)
let hmacHex = hmacData.base64EncodedString(options: .endLineWithLineFeed)
if signature == hmacHex {
return true
} else {
return false
}
}
return false
}
public func textFromLineWebhook(json: JSON) -> (text:String,replyToken:String) {
let emptyResult = ("","")
guard let eventsJSON = json["events"].arrayValue.first else {
return emptyResult
}
if eventsJSON["type"].stringValue == "message" {
let token = eventsJSON["replyToken"].stringValue
let messageJson = eventsJSON["message"]
if messageJson["type"].stringValue == "text" {
let textMessage = messageJson["text"].stringValue
return (text:textMessage , replyToken: token)
}
return emptyResult
}
return emptyResult
}
public func reply(text:String,token:String) -> [String:Any] {
let message = ["type":"text", "text":text]
let json:[String:Any] = ["replyToken":token , "messages": [message] ]
return json
}
|
bbba5f090b35610977036f2cfb4fa820
| 26.872727 | 97 | 0.6197 | false | false | false | false |
daxiangfei/RTSwiftUtils
|
refs/heads/master
|
RTSwiftUtils/Core/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// RTSwiftUtils
//
// Created by rongteng on 2017/7/17.
// Copyright © 2017年 rongteng. All rights reserved.
//
import Foundation
/// 打印
///
/// - Parameters:
/// - message: 需要打印的目标
/// - file: 省略
/// - method: 省略
/// - line: 省略
public func printLog<T>(message: T,file: String = #file,
method: String = #function,
line: Int = #line ) {
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
}
public let ScreenWidth = UIScreen.main.bounds.width //屏幕的宽度
public let ScreenHeight = UIScreen.main.bounds.height //屏幕的高度
|
456f4a1ff818fe9ffbb251567cdf6bf1
| 21.555556 | 82 | 0.617406 | false | false | false | false |
trentrand/WWDC-2015-Scholarship
|
refs/heads/master
|
Trent Rand/KnowledgeChildViewController.swift
|
mit
|
1
|
//
// KnowledgeChildViewController.swift
// Trent Rand
//
// Created by Trent Rand on 4/26/15.
// Copyright (c) 2015 Trent Rand. All rights reserved.
//
import Foundation
class KnowledgeChildViewController: UIViewController {
var index: NSInteger!
@IBOutlet var knowledgeDescription: UITextView!
@IBOutlet var knowledgeTitle: UILabel!
@IBOutlet var knowledgeIcon: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Force text view to start at top
knowledgeDescription.scrollRangeToVisible(NSRange(location:0, length:0))
switch index {
case 0:
knowledgeTitle.text = "Software Development"
knowledgeIcon.text = ""
knowledgeDescription.text = "Currently studying Software Engineering at Arizona State University, I have a strong background in the practice and methodologies required to deliver a well made software to any of the leading platforms."
case 1:
knowledgeTitle.text = "Website Development"
knowledgeIcon.text = ""
knowledgeDescription.text = "While I am not the most artistic person, I am particularly great with the HTML and CSS languages. I have the ability to work alongside an artist in order to create, configure, and launch your website on any of the leading web services or local server."
case 2:
knowledgeTitle.text = "Mobile Applications"
knowledgeIcon.text = ""
knowledgeDescription.text = "Having first learned to program with the Android SDK, I have long since been a big fan of mobile application development. My focus has now shifted towards iOS, although I have a strong background in the mobile application design principles required to bring your application idea to the marketplace."
case 3:
knowledgeTitle.text = "Networking"
knowledgeIcon.text = ""
knowledgeDescription.text = "Since being employed at PerfOpt in June 2014, I have had the opportunity to work at IO Datacenter in Phoenix, AZ managing two server cabinets. I have a great understanding of basic networking, as well as hands-on experience with wiring and configuring PDUs, switches, firewalls, KVM, servers, and NAS drives among others."
case 4:
knowledgeTitle.text = "Hardware"
knowledgeIcon.text = ""
knowledgeDescription.text = "After taking electronics and circuit courses at Arizona State University, I developed a love for working with circuitry. As a hobby, I have since begun to learn and work with the Arduino platform in an attempt to make my own Internet of Things electronics."
case 5:
knowledgeTitle.text = "IT Management"
knowledgeIcon.text = ""
knowledgeDescription.text = "With an extensive background in both Mac OS X and Windows operating systems, I can configure and manage computer systems. Likewise, I have the knowledge required in order to troubleshoot and solve advanced software and hardware computer technical issues."
default:
knowledgeTitle.text = "Error"
knowledgeIcon.text = ""
knowledgeDescription.text = "This shouldn't have shown up. Oops!"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
15e55b25950e27fd4f97005de5a23117
| 54.836066 | 363 | 0.693098 | false | false | false | false |
CodePath2017Group4/travel-app
|
refs/heads/master
|
RoadTripPlanner/LandingPageViewController.swift
|
mit
|
1
|
//
// LandingPageViewController.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/10/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import CoreLocation
import AFNetworking
import YelpAPI
import CDYelpFusionKit
import Parse
class LandingPageViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
// @IBOutlet weak var tableView: UITableView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pagingView: UIView!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var createTripButton: UIButton!
@IBOutlet weak var nearMeButton: UIButton!
@IBOutlet weak var alongTheRouteButton: UIButton!
@IBOutlet weak var currentCity: UILabel!
@IBOutlet weak var currentTemperature: UILabel!
@IBOutlet weak var temperatureImage: UIImageView!
let locationManager = CLLocationManager()
var weather: WeatherGetter!
@IBOutlet weak var gasImageView: UIImageView!
@IBOutlet weak var foodImageView: UIImageView!
@IBOutlet weak var poiImageView: UIImageView!
@IBOutlet weak var shoppingImageView: UIImageView!
@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var labelTwo: UILabel!
@IBOutlet weak var labelThree: UILabel!
@IBOutlet weak var labelFour: UILabel!
//drugstores, deptstores, flowers
//food - bakeries, bagels, coffee, donuts, foodtrucks
//hotels - bedbreakfast, campgrounds, guesthouses. hostels
//thingstodo
//arts - arcades, museums
// active - aquariums, zoos, parks, amusementparks
// nightlife
//poi // publicservicesgovt - civiccenter, landmarks,
//entertainmneet// arts - movietheaters, galleries, theater
// servicestations
let categoriesList = ["auto", "food, restaurant", "publicservicesgovt"/*poi*/,"shopping"/*shopping"*/, "hotels", "arts, active", "nightlife", "arts"]
var selectedType = [String] ()
var businesses: [CDYelpBusiness]!
var trips: [Trip]!
let testData = TestData()
override func viewDidLoad() {
super.viewDidLoad()
createTripButton.layer.cornerRadius = createTripButton.frame.height / 2
nearMeButton.layer.cornerRadius = createTripButton.frame.height / 2
alongTheRouteButton.layer.cornerRadius = createTripButton.frame.height / 2
nearMeButton.isHidden = true
alongTheRouteButton.isHidden = true
// tableView.rowHeight = UITableViewAutomaticDimension
//tableView.estimatedRowHeight = 192
//tableView.separatorStyle = .none
// let tripTableViewCellNib = UINib(nibName: Constants.NibNames.TripTableViewCell, bundle: nil)
// tableView.register(tripTableViewCellNib, forCellReuseIdentifier: Constants.ReuseableCellIdentifiers.TripTableViewCell)
let tripCollectionViewCellNib = UINib(nibName: Constants.NibNames.TripCollectionViewCell, bundle: nil)
collectionView.register(tripCollectionViewCellNib, forCellWithReuseIdentifier: Constants.ReuseableCellIdentifiers.TripCollectionViewCell)
collectionView.delegate = self
collectionView.dataSource = self
nearMeButton.isHidden = true
alongTheRouteButton.isHidden = true
getLocation()
weather = WeatherGetter(delegate: self)
trips = []
loadUpcomingTrips()
//1
//self.scrollView.frame = CGRect(x:0, y:0, width:self.view.frame.width, height:self.view.frame.height)
let scrollViewWidth: CGFloat = self.scrollView.frame.width
let scrollViewHeight: CGFloat = self.scrollView.frame.height
let lodgingImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
lodgingImageTap.numberOfTapsRequired = 1
gasImageView.isUserInteractionEnabled = true
//gasImageView.tag = 4
gasImageView.addGestureRecognizer(lodgingImageTap)
labelOne.text = "Lodging"
let thingsToDoImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
thingsToDoImageTap.numberOfTapsRequired = 1
foodImageView.isUserInteractionEnabled = true
//foodImageView.tag = 5
foodImageView.addGestureRecognizer(thingsToDoImageTap)
labelTwo.text = "Point of Interest"
let nightlifeImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
nightlifeImageTap.numberOfTapsRequired = 1
poiImageView.isUserInteractionEnabled = true
//poiImageView.tag = 6
poiImageView.addGestureRecognizer(nightlifeImageTap)
labelThree.text = "Nightlife"
let entertainmentImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
entertainmentImageTap.numberOfTapsRequired = 1
shoppingImageView.isUserInteractionEnabled = true
//shoppingImageView.tag = 7
shoppingImageView.addGestureRecognizer(entertainmentImageTap)
labelFour.text = "Enterntainment"
self.scrollView.addSubview(pagingView)
let gasImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
gasImageTap.numberOfTapsRequired = 1
gasImageView.isUserInteractionEnabled = true
gasImageView.tag = 0
gasImageView.addGestureRecognizer(gasImageTap)
labelOne.text = "Automotive"
let foodImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
foodImageTap.numberOfTapsRequired = 1
foodImageView.isUserInteractionEnabled = true
let foodImageFromFile = UIImage(named: "food")!
foodImageView.image = foodImageFromFile.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
foodImageView.tintColor = UIColor(red: 22/255, green: 134/255, blue: 36/255, alpha: 1)//.green*/
foodImageView.tag = 1
foodImageView.addGestureRecognizer(foodImageTap)
labelTwo.text = "Food"
let poiImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
poiImageTap.numberOfTapsRequired = 1
poiImageView.isUserInteractionEnabled = true
poiImageView.tag = 2
poiImageView.addGestureRecognizer(poiImageTap)
labelThree.text = "POI"
let shoppingImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
shoppingImageTap.numberOfTapsRequired = 1
shoppingImageView.isUserInteractionEnabled = true
shoppingImageView.tag = 3
shoppingImageView.addGestureRecognizer(shoppingImageTap)
labelFour.text = "Shopping"
self.scrollView.addSubview(pagingView)
self.scrollView.contentSize = CGSize(width:self.scrollView.frame.width * 2, height:self.scrollView.frame.height)
self.scrollView.delegate = self
self.pageControl.currentPage = 1
navigationController?.navigationBar.tintColor = Constants.Colors.NavigationBarLightTintColor
let textAttributes = [NSForegroundColorAttributeName:Constants.Colors.NavigationBarLightTintColor]
navigationController?.navigationBar.titleTextAttributes = textAttributes
registerForNotifications()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
// Make the navigation bar completely transparent.
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
}
fileprivate func loadUpcomingTrips() {
ParseBackend.getTripsForUser(user: PFUser.current()!, areUpcoming: true, onlyConfirmed: true) { (trips, error) in
if error == nil {
if let t = trips {
log.info("Upcoming trip count \(t.count)")
self.trips = t
DispatchQueue.main.async {
//self.tableView.reloadData()
self.collectionView.reloadData()
}
}
} else {
log.error("Error loading upcoming trips: \(error!)")
}
}
}
fileprivate func registerForNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(tripWasModified(notification:)),
name: Constants.NotificationNames.TripModifiedNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(tripDeleted(notification:)),
name: Constants.NotificationNames.TripDeletedNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(tripCreated(notification:)),
name: Constants.NotificationNames.TripCreatedNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func tripCreated(notification: NSNotification) {
// Reload trips
loadUpcomingTrips()
}
func tripWasModified(notification: NSNotification) {
let info = notification.userInfo
let trip = info!["trip"] as! Trip
let tripId = trip.objectId
// Find the trip in the trips array.
log.info("Trip with id: \(String(describing: tripId)) has been modified.")
let matchingTrips = trips.filter { (trip) -> Bool in
return trip.objectId == tripId
}
if matchingTrips.count > 0 {
let match = matchingTrips.first!
let index = trips.index(of: match)
guard let idx = index else { return }
// replace the trip with the new trip
trips[idx] = trip
// reload the trips
collectionView.reloadData()
}
}
func tripDeleted(notification: NSNotification) {
// Reload trips
loadUpcomingTrips()
}
func categoryTapped(_ sender: UITapGestureRecognizer) {
let selectedIndex = sender.view?.tag
print("selectedIndex ===== > \(selectedIndex)")
let selectedImg = sender.view
if !selectedType.isEmpty {
//if selectedTypes.contains(categoriesList[selectedIndex!]) {
if categoriesList.contains(selectedType[0]) {
print("in first if")
selectedImg?.transform = CGAffineTransform(scaleX: 1.1,y: 1.1);
selectedImg?.alpha = 0.0
UIView.beginAnimations("button", context:nil)
UIView.setAnimationDuration(0.5)
selectedImg?.transform = CGAffineTransform(scaleX: 1,y: 1);
selectedImg?.alpha = 1.0
UIView.commitAnimations()
gasImageView.alpha = 1
foodImageView.alpha = 1
poiImageView.alpha = 1
shoppingImageView.alpha = 1
createTripButton.isHidden = selectedType.isEmpty//false
nearMeButton.isHidden = !selectedType.isEmpty//true
alongTheRouteButton.isHidden = !selectedType.isEmpty//true
selectedType.removeAll()
}
else {
gasImageView.alpha = 0.5
foodImageView.alpha = 0.5
poiImageView.alpha = 0.5
shoppingImageView.alpha = 0.5
selectedImg?.transform = CGAffineTransform(scaleX: 1.1,y: 1.1);
selectedImg?.alpha = 0.0
UIView.beginAnimations("button", context:nil)
UIView.setAnimationDuration(0.5)
selectedImg?.transform = CGAffineTransform(scaleX: 1,y: 1);
selectedImg?.alpha = 1.0
UIView.commitAnimations()
selectedType.removeAll()
selectedType.append(categoriesList[selectedIndex!])
}
}
else {
if gasImageView.tag != selectedIndex {
gasImageView.alpha = 0.5
}
if foodImageView.tag != selectedIndex {
foodImageView.alpha = 0.5
}
if poiImageView.tag != selectedIndex {
poiImageView.alpha = 0.5
}
if shoppingImageView.tag != selectedIndex {
shoppingImageView.alpha = 0.5
}
createTripButton.isHidden = selectedType.isEmpty//false
nearMeButton.isHidden = !selectedType.isEmpty//true
alongTheRouteButton.isHidden = !selectedType.isEmpty//true
selectedImg?.transform = CGAffineTransform(scaleX: 1,y: 1);
selectedImg?.alpha = 0.0
UIView.beginAnimations("button", context:nil)
UIView.setAnimationDuration(0.5)
selectedImg?.transform = CGAffineTransform(scaleX: 1.1,y: 1.1);
selectedImg?.alpha = 1.0
UIView.commitAnimations()
selectedType.append(categoriesList[selectedIndex!])
}
print("selectedType \(selectedType)")
}
func getLocation() {
guard CLLocationManager.locationServicesEnabled() else {
print("Location services are disabled on your device. In order to use this app, go to " +
"Settings → Privacy → Location Services and turn location services on.")
return
}
let authStatus = CLLocationManager.authorizationStatus()
guard authStatus == .authorizedWhenInUse else {
switch authStatus {
case .denied, .restricted:
print("This app is not authorized to use your location. In order to use this app, " +
"go to Settings → GeoExample → Location and select the \"While Using " +
"the App\" setting.")
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
default:
print("Oops! Shouldn't have come this far.")
}
return
}
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
// MARK: - Utility methods
// -----------------------
func showSimpleAlert(title: String, message: String) {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .alert
)
let okAction = UIAlertAction(
title: "OK",
style: .default,
handler: nil
)
alert.addAction(okAction)
present(
alert,
animated: true,
completion: nil
)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("segue.identifier \(segue.identifier!)")
if segue.identifier! == "NearMe" {
let mapViewController = segue.destination as! MapViewController
mapViewController.businesses = businesses
mapViewController.searchTerm = selectedType
}
else if segue.identifier! == "CreateTrip" {
let createTripViewController = segue.destination as! CreateTripViewController
//createTripViewController.businesses = businesses
//createTripViewController.searchBar = searchBar
//mapViewController.filters = filters
// mapViewController.filters1 = filters1*/
}
else {
let createTripViewController = segue.destination as! CreateTripViewController
/* if let cell = sender as? BusinessCell {
let indexPath = tableView.indexPath(for: cell)
let selectedBusiness = businesses[(indexPath?.row)!]
if let detailViewController = segue.destination as? DetailViewController {
detailViewController.business = selectedBusiness
detailViewController.filters = filters
// detailViewController.filters1 = filters1
}
}*/
}
}
@IBAction func onCreateTrip(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
//let createTripViewController = storyBoard.instantiateViewController(withIdentifier: "CreateTrip") as! UINavigationController
// self.navigationController?.pushViewController(createTripViewController.topViewController!, animated: true)
}
@IBAction func onNearMe(_ sender: Any) {
performSearch(selectedType)
}
@IBAction func onAlongTheRoute(_ sender: Any) {
}
final func performSearch(_ term: [String]) {
if !term.isEmpty {
YelpFusionClient.shared.searchQueryWith(location: locationManager.location!, term: term[0], completionHandler: {(businesses: [CDYelpBusiness]?, error: Error?) -> Void in
self.businesses = businesses
})
// working
/*YelpFusionClient.sharedInstance.searchQueryWith(location: locationManager.location!, term: term[0], completionHandler: {(businesses: [YLPBusiness]?, error: Error?) -> Void in
self.businesses = businesses
})*/
}
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension LandingPageViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trips.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// if indexPath.row == 0 || indexPath.row == 2 {
// return 30.0
// }
return 192
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// switch indexPath.row {
// case 0, 2 : let headerCell = tableView.dequeueReusableCell(withIdentifier: "TripHeaderCell", for: indexPath) as! UITableViewCell
// return headerCell
//
// case 1, 3 : let tripCell = tableView.dequeueReusableCell(withIdentifier: "TripCell", for: indexPath) as! TripCell
// tripCell.selectionStyle = .none
//
// return tripCell
// default: return UITableViewCell()
//
//
// }
let tripCell = tableView.dequeueReusableCell(withIdentifier: Constants.ReuseableCellIdentifiers.TripTableViewCell, for: indexPath) as! TripTableViewCell
tripCell.trip = trips[indexPath.row]
return tripCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Show the trip details view controller.
let trip = trips[indexPath.row]
log.info("Selected trip \(trip.name ?? "none")")
let tripDetailsVC = TripDetailsViewController.storyboardInstance()
tripDetailsVC?.trip = trip
navigationController?.pushViewController(tripDetailsVC!, animated: true)
}
}
// MARK: - CLLocationManagerDelegate
extension LandingPageViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last!
weather.getWeatherByCoordinates(latitude: newLocation.coordinate.latitude,
longitude: newLocation.coordinate.longitude)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
DispatchQueue.main.async() {
self.showSimpleAlert(title: "Can't determine your location",
message: "The GPS and other location services aren't responding.")
}
print("locationManager didFailWithError: \(error)")
}
}
// MARK: - WeatherGetterDelegate
extension LandingPageViewController: WeatherGetterDelegate {
func didGetWeather(weather: Weather) {
DispatchQueue.main.async {
self.currentCity.text = weather.city
self.currentTemperature.text = "\(Int(round(weather.tempFahrenheit)))° F"
let weatherIconID = weather.weatherIconID
if UIImage(named: weatherIconID) == nil {
let iconURL = URL(string: "http://openweathermap.org/img/w/\(weatherIconID)")
self.temperatureImage.setImageWith(iconURL!)
} else {
self.temperatureImage.image = UIImage(named: weatherIconID)
}
}
}
func didNotGetWeather(error: NSError) {
DispatchQueue.main.async() {
self.showSimpleAlert(title: "Can't get the weather", message: "The weather service isn't responding.")
}
}
}
// MARK: - UIScrollViewDelegate
extension LandingPageViewController : UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
// Test the offset and calculate the current page after scrolling ends
let pageWidth:CGFloat = scrollView.frame.width
let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1
// Change the indicator
self.pageControl.currentPage = Int(currentPage)
print("self.pageControl.currentPage ---=== \(self.pageControl.currentPage)")
// Change the text accordingly
if Int(currentPage) == 0{
//textView.text = "Sweettutos.com is your blog of choice for Mobile tutorials"
gasImageView?.image = UIImage(named: "gasstation")
labelOne.text = "Automotive"
gasImageView.tag = 0
foodImageView?.image = UIImage(named: "food")
let foodImageFromFile = UIImage(named: "food")!
foodImageView.image = foodImageFromFile.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
foodImageView.tintColor = UIColor(red: 22/255, green: 134/255, blue: 36/255, alpha: 1)//.green*/
labelTwo.text = "Food"
foodImageView.tag = 1
poiImageView.tag = 2
poiImageView?.image = UIImage(named: "poi")
labelThree.text = "POI"
poiImageView.tag = 2
shoppingImageView?.image = UIImage(named: "shopping")
labelFour.text = "Shopping"
shoppingImageView.tag = 3
}else if Int(currentPage) == 1{
gasImageView?.image = UIImage(named: "lodging")
labelOne.text = "Lodging"
gasImageView.tag = 4
foodImageView?.image = UIImage(named: "thingstodo")
labelTwo.text = "Things to Do"
foodImageView.tag = 5
poiImageView?.image = UIImage(named: "nightlife")
labelThree.text = "Nightlife"
poiImageView.tag = 6
shoppingImageView?.image = UIImage(named: "entertainment")
labelFour.text = "Enterntainment"
shoppingImageView.tag = 7
}
}
}
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension LandingPageViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.ReuseableCellIdentifiers.TripCollectionViewCell, for: indexPath) as! TripCollectionViewCell
cell.backgroundColor = UIColor.darkGray
cell.trip = trips[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if trips.isEmpty {
print("trips == \(trips.count)")
let messageLabel = UILabel(frame: CGRect(x: 0,y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
messageLabel.text = "You dont have any upcoming trips."
messageLabel.textColor = UIColor.gray
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
messageLabel.sizeToFit()
self.collectionView.backgroundView = messageLabel
self.collectionView.backgroundView?.isHidden = false
} else {
self.collectionView.backgroundView?.isHidden = true
}
return trips.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
log.info("Selected cell at \(indexPath)")
let trip = trips[indexPath.row]
log.info("Selected trip \(trip.name ?? "none")")
let tripDetailsVC = TripDetailsViewController.storyboardInstance()
tripDetailsVC?.trip = trip
navigationController?.pushViewController(tripDetailsVC!, animated: true)
}
}
|
e60197ce99c0ebf4f9b547a1716a209d
| 37.919118 | 188 | 0.609144 | false | false | false | false |
auth0/Lock.iOS-OSX
|
refs/heads/master
|
Lock/DatabaseConstants.swift
|
mit
|
2
|
// DatabaseConstants.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct DatabaseMode: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
public static let Login = DatabaseMode(rawValue: 1 << 0)
public static let Signup = DatabaseMode(rawValue: 1 << 1)
public static let ResetPassword = DatabaseMode(rawValue: 1 << 2)
}
public enum DatabaseScreen: Int, Equatable {
case login = 0
case signup
case resetPassword
}
public struct DatabaseIdentifierStyle: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
public static let Username = DatabaseIdentifierStyle(rawValue: 1 << 0)
public static let Email = DatabaseIdentifierStyle(rawValue: 1 << 1)
}
public func == (lhs: DatabaseScreen, rhs: DatabaseScreen) -> Bool {
return lhs.rawValue == rhs.rawValue
}
|
301c913ea27541018adab8c3912dd070
| 37.576923 | 80 | 0.741276 | false | false | false | false |
WeMadeCode/ZXPageView
|
refs/heads/master
|
Example/Pods/SwifterSwift/Sources/SwifterSwift/AppKit/NSViewExtensions.swift
|
mit
|
1
|
//
// NSViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 3/3/17.
// Copyright © 2017 SwifterSwift
//
#if canImport(Cocoa)
import Cocoa
// MARK: - Properties
public extension NSView {
/// SwifterSwift: Border color of view; also inspectable from Storyboard.
@IBInspectable
var borderColor: NSColor? {
get {
guard let color = layer?.borderColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.borderColor = newValue?.cgColor
}
}
/// SwifterSwift: Border width of view; also inspectable from Storyboard.
@IBInspectable
var borderWidth: CGFloat {
get {
return layer?.borderWidth ?? 0
}
set {
wantsLayer = true
layer?.borderWidth = newValue
}
}
/// SwifterSwift: Corner radius of view; also inspectable from Storyboard.
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer?.cornerRadius ?? 0
}
set {
wantsLayer = true
layer?.masksToBounds = true
layer?.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
}
}
// SwifterSwift: Height of view.
var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
/// SwifterSwift: Shadow color of view; also inspectable from Storyboard.
@IBInspectable
var shadowColor: NSColor? {
get {
guard let color = layer?.shadowColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.shadowColor = newValue?.cgColor
}
}
/// SwifterSwift: Shadow offset of view; also inspectable from Storyboard.
@IBInspectable
var shadowOffset: CGSize {
get {
return layer?.shadowOffset ?? CGSize.zero
}
set {
wantsLayer = true
layer?.shadowOffset = newValue
}
}
/// SwifterSwift: Shadow opacity of view; also inspectable from Storyboard.
@IBInspectable
var shadowOpacity: Float {
get {
return layer?.shadowOpacity ?? 0
}
set {
wantsLayer = true
layer?.shadowOpacity = newValue
}
}
/// SwifterSwift: Shadow radius of view; also inspectable from Storyboard.
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer?.shadowRadius ?? 0
}
set {
wantsLayer = true
layer?.shadowRadius = newValue
}
}
/// SwifterSwift: Size of view.
var size: CGSize {
get {
return frame.size
}
set {
width = newValue.width
height = newValue.height
}
}
/// SwifterSwift: Width of view.
var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
}
// MARK: - Methods
extension NSView {
/// SwifterSwift: Add array of subviews to view.
///
/// - Parameter subviews: array of subviews to add to self.
func addSubviews(_ subviews: [NSView]) {
subviews.forEach { addSubview($0) }
}
/// SwifterSwift: Remove all subviews in view.
func removeSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
}
#endif
|
6bc72d5563d2fc5329fae0fa60c7e32e
| 22.486842 | 79 | 0.546218 | false | false | false | false |
spark/photon-tinker-ios
|
refs/heads/master
|
Photon-Tinker/Mesh/StepEnsureCorrectSelectedWifiNetworkPassword.swift
|
apache-2.0
|
1
|
//
// Created by Raimundas Sakalauskas on 2019-03-07.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class StepEnsureCorrectSelectedWifiNetworkPassword : Gen3SetupStep {
override func start() {
guard let context = self.context else {
return
}
if context.selectedWifiNetworkInfo!.security == .noSecurity {
self.setSelectedWifiNetworkPassword("") { error in
self.log("WIFI with no password error: \(error)")
}
return
}
context.delegate.gen3SetupDidRequestToEnterSelectedWifiNetworkPassword(self)
}
func setSelectedWifiNetworkPassword(_ password: String, onComplete:@escaping (Gen3SetupFlowError?) -> ()) {
guard let context = self.context else {
onComplete(nil)
return
}
//TODO: validate length based on security
guard self.validateWifiNetworkPassword(password) || (context.selectedWifiNetworkInfo!.security == .noSecurity) else {
onComplete(.WifiPasswordTooShort)
return
}
self.log("trying password with character count: \(password.count)")
context.targetDevice!.transceiver?.sendJoinNewWifiNetwork(network: context.selectedWifiNetworkInfo!, password: password) {
[weak self, weak context] result in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("targetDevice.sendJoinNewWifiNetwork: \(result.description())")
if (context.selectedWifiNetworkInfo!.security == .noSecurity) {
if (result == .NONE) {
onComplete(nil)
self.stepCompleted()
} else {
onComplete(nil)
self.handleBluetoothErrorResult(result)
}
} else {
if (result == .NONE) {
onComplete(nil)
self.stepCompleted()
} else if (result == .NOT_FOUND) {
onComplete(.WrongNetworkPassword)
} else {
onComplete(.BluetoothTimeout)
}
}
}
}
private func validateWifiNetworkPassword(_ password: String) -> Bool {
return password.count >= 5
}
}
|
a6433da43665acc783298fd43268ba4a
| 34.088235 | 130 | 0.569153 | false | false | false | false |
lemberg/connfa-ios
|
refs/heads/master
|
Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/languages/lang_dsb.swift
|
apache-2.0
|
1
|
//
// lang_dsb.swift
// SwiftDate
//
// Created by Daniele Margutti on 13/06/2018.
// Copyright © 2018 SwiftDate. All rights reserved.
//
import Foundation
// swiftlint:disable type_name
public class lang_dsb: RelativeFormatterLang {
/// Locales.lowerSorbian
public static let identifier: String = "dsb"
public required init() {}
public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? {
switch value {
case 1: return .one
case 2, 3, 4: return .few
default: return .other
}
}
// module.exports=function(e){var i=String(e).split("."),n=Number(i{0})==e,r=n&&i{0}.slice(-1),s=n&&i{0}.slice(-2);return 1==r&&11!=s?"one":r>=2&&r<=4&&(s<12||s>14)?"few":n&&0==r||r>=5&&r<=9||s>=11&&s<=14?"many":"other"}
public var flavours: [String: Any] {
return [
RelativeFormatter.Flavour.long.rawValue: self._long,
RelativeFormatter.Flavour.narrow.rawValue: self._narrow,
RelativeFormatter.Flavour.short.rawValue: self._short
]
}
private var _short: [String: Any] {
return [
"year": [
"previous": "łoni",
"current": "lětosa",
"next": "znowa",
"past": "pśed {0} l.",
"future": "za {0} l."
],
"quarter": [
"previous": "last quarter",
"current": "this quarter",
"next": "next quarter",
"past": "pśed {0} kwart.",
"future": "za {0} kwart."
],
"month": [
"previous": "slědny mjasec",
"current": "ten mjasec",
"next": "pśiducy mjasec",
"past": "pśed {0} mjas.",
"future": "za {0} mjas."
],
"week": [
"previous": "slědny tyźeń",
"current": "ten tyźeń",
"next": "pśiducy tyźeń",
"past": "pśed {0} tyź.",
"future": "za {0} tyź."
],
"day": [
"previous": "cora",
"current": "źinsa",
"next": "witśe",
"past": "pśed {0} dnj.",
"future": [
"one": "za {0} źeń",
"few": "za {0} dny",
"other": "za {0} dnj."
]
],
"hour": [
"current": "this hour",
"past": "pśed {0} góź.",
"future": "za {0} góź."
],
"minute": [
"current": "this minute",
"past": "pśed {0} min.",
"future": "za {0} min."
],
"second": [
"current": "now",
"past": "pśed {0} sek.",
"future": "za {0} sek."
],
"now": "now"
]
}
private var _narrow: [String: Any] {
return [
"year": [
"previous": "łoni",
"current": "lětosa",
"next": "znowa",
"past": "pśed {0} l.",
"future": "za {0} l."
],
"quarter": [
"previous": "last quarter",
"current": "this quarter",
"next": "next quarter",
"past": "pśed {0} kw.",
"future": "za {0} kw."
],
"month": [
"previous": "slědny mjasec",
"current": "ten mjasec",
"next": "pśiducy mjasec",
"past": "pśed {0} mjas.",
"future": "za {0} mjas."
],
"week": [
"previous": "slědny tyźeń",
"current": "ten tyźeń",
"next": "pśiducy tyźeń",
"past": "pśed {0} tyź.",
"future": "za {0} tyź."
],
"day": [
"previous": "cora",
"current": "źinsa",
"next": "witśe",
"past": "pśed {0} d",
"future": "za {0} ź"
],
"hour": [
"current": "this hour",
"past": "pśed {0} g",
"future": "za {0} g"
],
"minute": [
"current": "this minute",
"past": "pśed {0} m",
"future": "za {0} m"
],
"second": [
"current": "now",
"past": "pśed {0} s",
"future": "za {0} s"
],
"now": "now"
]
}
private var _long: [String: Any] {
return [
"year": [
"previous": "łoni",
"current": "lětosa",
"next": "znowa",
"past": [
"one": "pśed {0} lětom",
"two": "pśed {0} lětoma",
"other": "pśed {0} lětami"
],
"future": [
"one": "za {0} lěto",
"two": "za {0} lěśe",
"few": "za {0} lěta",
"other": "za {0} lět"
]
],
"quarter": [
"previous": "last quarter",
"current": "this quarter",
"next": "next quarter",
"past": [
"one": "pśed {0} kwartalom",
"two": "pśed {0} kwartaloma",
"other": "pśed {0} kwartalami"
],
"future": [
"one": "za {0} kwartal",
"two": "za {0} kwartala",
"few": "za {0} kwartale",
"other": "za {0} kwartalow"
]
],
"month": [
"previous": "slědny mjasec",
"current": "ten mjasec",
"next": "pśiducy mjasec",
"past": [
"one": "pśed {0} mjasecom",
"two": "pśed {0} mjasecoma",
"other": "pśed {0} mjasecami"
],
"future": [
"one": "za {0} mjasec",
"two": "za {0} mjaseca",
"few": "za {0} mjasecy",
"other": "za {0} mjasecow"
]
],
"week": [
"previous": "slědny tyźeń",
"current": "ten tyźeń",
"next": "pśiducy tyźeń",
"past": [
"one": "pśed {0} tyźenjom",
"two": "pśed {0} tyźenjoma",
"other": "pśed {0} tyźenjami"
],
"future": [
"one": "za {0} tyźeń",
"two": "za {0} tyźenja",
"few": "za {0} tyźenje",
"other": "za {0} tyźenjow"
]
],
"day": [
"previous": "cora",
"current": "źinsa",
"next": "witśe",
"past": [
"one": "pśed {0} dnjom",
"two": "pśed {0} dnjoma",
"other": "pśed {0} dnjami"
],
"future": [
"one": "za {0} źeń",
"two": "za {0} dnja",
"few": "za {0} dny",
"other": "za {0} dnjow"
]
],
"hour": [
"current": "this hour",
"past": [
"one": "pśed {0} góźinu",
"two": "pśed {0} góźinoma",
"other": "pśed {0} góźinami"
],
"future": [
"one": "za {0} góźinu",
"two": "za {0} góźinje",
"few": "za {0} góźiny",
"other": "za {0} góźin"
]
],
"minute": [
"current": "this minute",
"past": [
"one": "pśed {0} minutu",
"two": "pśed {0} minutoma",
"other": "pśed {0} minutami"
],
"future": [
"one": "za {0} minutu",
"two": "za {0} minuśe",
"few": "za {0} minuty",
"other": "za {0} minutow"
]
],
"second": [
"current": "now",
"past": [
"one": "pśed {0} sekundu",
"two": "pśed {0} sekundoma",
"other": "pśed {0} sekundami"
],
"future": [
"one": "za {0} sekundu",
"two": "za {0} sekunźe",
"few": "za {0} sekundy",
"other": "za {0} sekundow"
]
],
"now": "now"
]
}
}
|
ad932ce8102a5029a1498ee873b4776f
| 21.16129 | 221 | 0.475174 | false | false | false | false |
jopamer/swift
|
refs/heads/master
|
test/Frontend/dependencies.swift
|
apache-2.0
|
2
|
// XFAIL: linux
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-dependencies-path - -resolve-imports %S/../Inputs/empty\ file.swift | %FileCheck -check-prefix=CHECK-BASIC %s
// RUN: %target-swift-frontend -emit-reference-dependencies-path - -typecheck -primary-file %S/../Inputs/empty\ file.swift | %FileCheck -check-prefix=CHECK-BASIC-YAML %s
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file %S/../Inputs/empty\ file.swift
// RUN: %FileCheck -check-prefix=CHECK-BASIC %s < %t.d
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s < %t.swiftdeps
// CHECK-BASIC-LABEL: - :
// CHECK-BASIC: Inputs/empty\ file.swift
// CHECK-BASIC: Swift.swiftmodule
// CHECK-BASIC-NOT: :
// CHECK-BASIC-YAML-LABEL: depends-external:
// CHECK-BASIC-YAML-NOT: empty\ file.swift
// CHECK-BASIC-YAML: "{{.*}}/Swift.swiftmodule"
// CHECK-BASIC-YAML-NOT: {{:$}}
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck %S/../Inputs/empty\ file.swift 2>&1 | %FileCheck -check-prefix=NO-PRIMARY-FILE %s
// NO-PRIMARY-FILE: warning: ignoring -emit-reference-dependencies (requires -primary-file)
// RUN: %target-swift-frontend -emit-dependencies-path - -emit-module %S/../Inputs/empty\ file.swift -o %t/empty\ file.swiftmodule -emit-module-doc-path %t/empty\ file.swiftdoc -emit-objc-header-path %t/empty\ file.h -emit-interface-path %t/empty\ file.swiftinterface | %FileCheck -check-prefix=CHECK-MULTIPLE-OUTPUTS %s
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftmodule :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftdoc :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftinterface :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.h :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-NOT: :
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -track-system-dependencies -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT-TRACK-SYSTEM %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path - -typecheck -primary-file %s | %FileCheck -check-prefix=CHECK-IMPORT-YAML %s
// CHECK-IMPORT-LABEL: - :
// CHECK-IMPORT: dependencies.swift
// CHECK-IMPORT-DAG: Swift.swiftmodule
// CHECK-IMPORT-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-DAG: Inputs/dependencies/UserClangModule.h
// CHECK-IMPORT-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-DAG: Inputs/dependencies/module.modulemap
// CHECK-IMPORT-DAG: ObjectiveC.swift
// CHECK-IMPORT-DAG: Foundation.swift
// CHECK-IMPORT-DAG: CoreGraphics.swift
// CHECK-IMPORT-NOT: :
// CHECK-IMPORT-TRACK-SYSTEM-LABEL: - :
// CHECK-IMPORT-TRACK-SYSTEM: dependencies.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Swift.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: SwiftOnoneSupport.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreFoundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreGraphics.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Foundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: ObjectiveC.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/UserClangModule.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: swift/shims/module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/CoreFoundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/CoreGraphics.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/CoreGraphics.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/Foundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/NSObject.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/ObjectiveC.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/module.map
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/objc.h
// CHECK-IMPORT-TRACK-SYSTEM-NOT: :
// CHECK-IMPORT-YAML-LABEL: depends-external:
// CHECK-IMPORT-YAML-NOT: dependencies.swift
// CHECK-IMPORT-YAML-DAG: "{{.*}}/Swift.swiftmodule"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/$$$$$.h"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/UserClangModule.h"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/extra-header.h"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/module.modulemap"
// CHECK-IMPORT-YAML-DAG: "{{.*}}/ObjectiveC.swift"
// CHECK-IMPORT-YAML-DAG: "{{.*}}/Foundation.swift"
// CHECK-IMPORT-YAML-DAG: "{{.*}}/CoreGraphics.swift"
// CHECK-IMPORT-YAML-NOT: {{^-}}
// CHECK-IMPORT-YAML-NOT: {{:$}}
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -typecheck %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path - -typecheck -primary-file %s | %FileCheck -check-prefix=CHECK-IMPORT-YAML %s
import Foundation
import UserClangModule
class Test: NSObject {}
_ = A()
_ = USER_VERSION
_ = EXTRA_VERSION
_ = MONEY
#if ERROR
_ = someRandomUndefinedName
#endif
|
cb925a4fbe6925f0cedaeb404557709c
| 52.026786 | 320 | 0.743391 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
test/RemoteAST/parameterized_existentials.swift
|
apache-2.0
|
5
|
// RUN: %target-swift-remoteast-test -disable-availability-checking %s | %FileCheck %s
// REQUIRES: swift-remoteast-test
@_silgen_name("printDynamicTypeAndAddressForExistential")
func printDynamicTypeAndAddressForExistential<T>(_: T)
@_silgen_name("stopRemoteAST")
func stopRemoteAST()
protocol Paddock<Animal> {
associatedtype Animal
}
struct Chicken {}
struct Coop: Paddock {
typealias Animal = Chicken
}
struct Pig {}
struct Pen: Paddock {
typealias Animal = Pig
}
struct Field<Animal>: Paddock {}
protocol SharedYard<Animal1, Animal2, Animal3, Animal4> {
associatedtype Animal1
associatedtype Animal2
associatedtype Animal3
associatedtype Animal4
}
class Lea: SharedYard {
typealias Animal1 = Chicken
typealias Animal2 = Pig
typealias Animal3 = Chicken
typealias Animal4 = Pig
init() {}
}
let coop = Coop()
// CHECK: Coop
printDynamicTypeAndAddressForExistential(coop as any Paddock)
// CHECK-NEXT: Coop
printDynamicTypeAndAddressForExistential(coop as any Paddock<Chicken>)
// CHECK-NEXT: Coop.Type
printDynamicTypeAndAddressForExistential(Coop.self as (any Paddock<Chicken>.Type))
// CHECK-NEXT: Coop.Type.Type.Type.Type
printDynamicTypeAndAddressForExistential(Coop.Type.Type.Type.self as (any Paddock<Chicken>.Type.Type.Type.Type))
let pen = Pen()
// CHECK-NEXT: Pen
printDynamicTypeAndAddressForExistential(pen as any Paddock)
// CHECK-NEXT: Pen
printDynamicTypeAndAddressForExistential(pen as any Paddock<Pig>)
let lea = Lea()
// CHECK-NEXT: Lea
printDynamicTypeAndAddressForExistential(lea as any SharedYard)
// CHECK-NEXT: Lea
printDynamicTypeAndAddressForExistential(lea as any SharedYard<Chicken, Pig, Chicken, Pig>)
func freeRange<Animal>(_ x: Animal.Type) {
printDynamicTypeAndAddressForExistential(Field<Animal>() as any Paddock<Animal>)
}
// CHECK-NEXT: Field<Chicken>
freeRange(Chicken.self)
// CHECK-NEXT: Field<Pig>
freeRange(Pig.self)
stopRemoteAST()
|
0ea456769e137e458bd516fd567d24b5
| 22.728395 | 112 | 0.774194 | false | false | false | false |
leonereveel/Moya
|
refs/heads/master
|
Source/RxSwift/Moya+RxSwift.swift
|
mit
|
1
|
import Foundation
import RxSwift
/// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures.
public class RxMoyaProvider<Target where Target: TargetType>: MoyaProvider<Target> {
/// Initializes a reactive provider.
override public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = RxMoyaProvider<Target>.DefaultAlamofireManager(),
plugins: [PluginType] = [],
trackInflights: Bool = false) {
super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights)
}
/// Designated request-making method.
public func request(token: Target) -> Observable<Response> {
// Creates an observable that starts a request each time it's subscribed to.
return Observable.create { [weak self] observer in
let cancellableToken = self?.request(token) { result in
switch result {
case let .Success(response):
observer.onNext(response)
observer.onCompleted()
case let .Failure(error):
observer.onError(error)
}
}
return AnonymousDisposable {
cancellableToken?.cancel()
}
}
}
}
public extension RxMoyaProvider {
public func requestWithProgress(token: Target) -> Observable<ProgressResponse> {
let progressBlock = { (observer: AnyObserver) -> (ProgressResponse) -> Void in
return { (progress: ProgressResponse) in
observer.onNext(progress)
}
}
let response: Observable<ProgressResponse> = Observable.create { [weak self] observer in
let cancellableToken = self?.request(token, queue: nil, progress: progressBlock(observer)) { result in
switch result {
case let .Success(response):
observer.onNext(ProgressResponse(response: response))
observer.onCompleted()
case let .Failure(error):
observer.onError(error)
}
}
return AnonymousDisposable {
cancellableToken?.cancel()
}
}
// Accumulate all progress and combine them when the result comes
return response.scan(ProgressResponse()) { (last, progress) in
let totalBytes = progress.totalBytes > 0 ? progress.totalBytes : last.totalBytes
let bytesExpected = progress.bytesExpected > 0 ? progress.bytesExpected : last.bytesExpected
let response = progress.response ?? last.response
return ProgressResponse(totalBytes: totalBytes, bytesExpected: bytesExpected, response: response)
}
}
}
|
3c0c555eea9b28e3397a726958475e10
| 43.028571 | 182 | 0.632057 | false | false | false | false |
WickedColdfront/Slide-iOS
|
refs/heads/master
|
Pods/SideMenu/Pod/Classes/SideMenuManager.swift
|
apache-2.0
|
1
|
//
// SideMenuManager.swift
//
// Created by Jon Kent on 12/6/15.
// Copyright © 2015 Jon Kent. All rights reserved.
//
/* Example usage:
// Define the menus
SideMenuManager.menuLeftNavigationController = storyboard!.instantiateViewController(withIdentifier: "LeftMenuNavigationController") as? UISideMenuNavigationController
SideMenuManager.menuRightNavigationController = storyboard!.instantiateViewController(withIdentifier: "RightMenuNavigationController") as? UISideMenuNavigationController
// Enable gestures. The left and/or right menus must be set up above for these to work.
// Note that these continue to work on the Navigation Controller independent of the View Controller it displays!
SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar)
SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view)
*/
open class SideMenuManager : NSObject {
@objc public enum MenuPushStyle : Int {
case defaultBehavior,
popWhenPossible,
replace,
preserve,
preserveAndHideBackButton,
subMenu
}
@objc public enum MenuPresentMode : Int {
case menuSlideIn,
viewSlideOut,
viewSlideInOut,
menuDissolveIn
}
// Bounds which has been allocated for the app on the whole device screen
internal static var appScreenRect: CGRect {
let appWindowRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds
return appWindowRect
}
/**
The push style of the menu.
There are six modes in MenuPushStyle:
- defaultBehavior: The view controller is pushed onto the stack.
- popWhenPossible: If a view controller already in the stack is of the same class as the pushed view controller, the stack is instead popped back to the existing view controller. This behavior can help users from getting lost in a deep navigation stack.
- preserve: If a view controller already in the stack is of the same class as the pushed view controller, the existing view controller is pushed to the end of the stack. This behavior is similar to a UITabBarController.
- preserveAndHideBackButton: Same as .preserve and back buttons are automatically hidden.
- replace: Any existing view controllers are released from the stack and replaced with the pushed view controller. Back buttons are automatically hidden. This behavior is ideal if view controllers require a lot of memory or their state doesn't need to be preserved..
- subMenu: Unlike all other behaviors that push using the menu's presentingViewController, this behavior pushes view controllers within the menu. Use this behavior if you want to display a sub menu.
*/
open static var menuPushStyle: MenuPushStyle = .defaultBehavior
/**
The presentation mode of the menu.
There are four modes in MenuPresentMode:
- menuSlideIn: Menu slides in over of the existing view.
- viewSlideOut: The existing view slides out to reveal the menu.
- viewSlideInOut: The existing view slides out while the menu slides in.
- menuDissolveIn: The menu dissolves in over the existing view controller.
*/
open static var menuPresentMode: MenuPresentMode = .viewSlideOut
/// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true.
open static var menuAllowPushOfSameClassTwice = true
/// Width of the menu when presented on screen, showing the existing view controller in the remaining space. Default is 75% of the screen width.
open static var menuWidth: CGFloat = max(round(min((appScreenRect.width), (appScreenRect.height)) * 0.75), 240)
/// Duration of the animation when the menu is presented without gestures. Default is 0.35 seconds.
open static var menuAnimationPresentDuration: Double = 0.35
/// Duration of the animation when the menu is dismissed without gestures. Default is 0.35 seconds.
open static var menuAnimationDismissDuration: Double = 0.35
/// Duration of the remaining animation when the menu is partially dismissed with gestures. Default is 0.2 seconds.
open static var menuAnimationCompleteGestureDuration: Double = 0.20
/// Amount to fade the existing view controller when the menu is presented. Default is 0 for no fade. Set to 1 to fade completely.
open static var menuAnimationFadeStrength: CGFloat = 0
/// The amount to scale the existing view controller or the menu view controller depending on the `menuPresentMode`. Default is 1 for no scaling. Less than 1 will shrink, greater than 1 will grow.
open static var menuAnimationTransformScaleFactor: CGFloat = 1
/// The background color behind menu animations. Depending on the animation settings this may not be visible. If `menuFadeStatusBar` is true, this color is used to fade it. Default is black.
open static var menuAnimationBackgroundColor: UIColor?
/// The shadow opacity around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 0.5 for 50% opacity.
open static var menuShadowOpacity: Float = 0.5
/// The shadow color around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is black.
open static var menuShadowColor = UIColor.black
/// The radius of the shadow around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 5.
open static var menuShadowRadius: CGFloat = 5
/// Enable or disable interaction with the presenting view controller while the menu is displayed. Enabling may make it difficult to dismiss the menu or cause exceptions if the user tries to present and already presented menu. Default is false.
open static var menuPresentingViewControllerUserInteractionEnabled: Bool = false
/// The strength of the parallax effect on the existing view controller. Does not apply to `menuPresentMode` when set to `ViewSlideOut`. Default is 0.
open static var menuParallaxStrength: Int = 0
/// Draws the `menuAnimationBackgroundColor` behind the status bar. Default is true.
open static var menuFadeStatusBar = true
/// The animation options when a menu is displayed. Ignored when displayed with a gesture.
open static var menuAnimationOptions: UIViewAnimationOptions = .curveEaseInOut
/// The animation spring damping when a menu is displayed. Ignored when displayed with a gesture.
open static var menuAnimationUsingSpringWithDamping: CGFloat = 1
/// The animation initial spring velocity when a menu is displayed. Ignored when displayed with a gesture.
open static var menuAnimationInitialSpringVelocity: CGFloat = 1
/**
Automatically dismisses the menu when another view is pushed from it.
Note: to prevent the menu from dismissing when presenting, set modalPresentationStyle = .overFullScreen
of the view controller being presented in storyboard or during its initalization.
*/
open static var menuDismissOnPush = true
/// -Warning: Deprecated. Use `menuPushStyle = .subMenu` instead.
@available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .subMenu` instead.")
open static var menuAllowSubmenus: Bool {
get {
return menuPushStyle == .subMenu
}
set {
if newValue {
menuPushStyle = .subMenu
}
}
}
/// -Warning: Deprecated. Use `menuPushStyle = .popWhenPossible` instead.
@available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .popWhenPossible` instead.")
open static var menuAllowPopIfPossible: Bool {
get {
return menuPushStyle == .popWhenPossible
}
set {
if newValue {
menuPushStyle = .popWhenPossible
}
}
}
/// -Warning: Deprecated. Use `menuPushStyle = .replace` instead.
@available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .replace` instead.")
open static var menuReplaceOnPush: Bool {
get {
return menuPushStyle == .replace
}
set {
if newValue {
menuPushStyle = .replace
}
}
}
/// -Warning: Deprecated. Use `menuAnimationTransformScaleFactor` instead.
@available(*, deprecated, renamed: "menuAnimationTransformScaleFactor")
open static var menuAnimationShrinkStrength: CGFloat {
get {
return menuAnimationTransformScaleFactor
}
set {
menuAnimationTransformScaleFactor = newValue
}
}
// prevent instantiation
fileprivate override init() {}
/**
The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController.
- Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell.
*/
open static var menuBlurEffectStyle: UIBlurEffectStyle? {
didSet {
if oldValue != menuBlurEffectStyle {
updateMenuBlurIfNecessary()
}
}
}
/// The left menu.
open static var menuLeftNavigationController: UISideMenuNavigationController? {
willSet {
if menuLeftNavigationController?.presentingViewController == nil {
removeMenuBlurForMenu(menuLeftNavigationController)
}
}
didSet {
guard oldValue?.presentingViewController == nil else {
print("SideMenu Warning: menuLeftNavigationController cannot be modified while it's presented.")
menuLeftNavigationController = oldValue
return
}
setupNavigationController(menuLeftNavigationController, leftSide: true)
}
}
/// The right menu.
open static var menuRightNavigationController: UISideMenuNavigationController? {
willSet {
if menuRightNavigationController?.presentingViewController == nil {
removeMenuBlurForMenu(menuRightNavigationController)
}
}
didSet {
guard oldValue?.presentingViewController == nil else {
print("SideMenu Warning: menuRightNavigationController cannot be modified while it's presented.")
menuRightNavigationController = oldValue
return
}
setupNavigationController(menuRightNavigationController, leftSide: false)
}
}
/// The left menu swipe to dismiss gesture.
open static weak var menuLeftSwipeToDismissGesture: UIPanGestureRecognizer? {
didSet {
oldValue?.view?.removeGestureRecognizer(oldValue!)
setupGesture(gesture: menuLeftSwipeToDismissGesture)
}
}
/// The right menu swipe to dismiss gesture.
open static weak var menuRightSwipeToDismissGesture: UIPanGestureRecognizer? {
didSet {
oldValue?.view?.removeGestureRecognizer(oldValue!)
setupGesture(gesture: menuRightSwipeToDismissGesture)
}
}
fileprivate class func setupGesture(gesture: UIPanGestureRecognizer?) {
guard let gesture = gesture else {
return
}
gesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:)))
}
fileprivate class func setupNavigationController(_ forMenu: UISideMenuNavigationController?, leftSide: Bool) {
guard let forMenu = forMenu else {
return
}
if menuEnableSwipeGestures {
let exitPanGesture = UIPanGestureRecognizer()
forMenu.view.addGestureRecognizer(exitPanGesture)
if leftSide {
menuLeftSwipeToDismissGesture = exitPanGesture
} else {
menuRightSwipeToDismissGesture = exitPanGesture
}
}
forMenu.transitioningDelegate = SideMenuTransition.singleton
forMenu.modalPresentationStyle = .overFullScreen
forMenu.leftSide = leftSide
updateMenuBlurIfNecessary()
}
/// Enable or disable gestures that would swipe to dismiss the menu. Default is true.
open static var menuEnableSwipeGestures: Bool = true {
didSet {
menuLeftSwipeToDismissGesture?.view?.removeGestureRecognizer(menuLeftSwipeToDismissGesture!)
menuRightSwipeToDismissGesture?.view?.removeGestureRecognizer(menuRightSwipeToDismissGesture!)
setupNavigationController(menuLeftNavigationController, leftSide: true)
setupNavigationController(menuRightNavigationController, leftSide: false)
}
}
fileprivate class func updateMenuBlurIfNecessary() {
let menuBlurBlock = { (forMenu: UISideMenuNavigationController?) in
if let forMenu = forMenu {
setupMenuBlurForMenu(forMenu)
}
}
menuBlurBlock(menuLeftNavigationController)
menuBlurBlock(menuRightNavigationController)
}
fileprivate class func setupMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) {
removeMenuBlurForMenu(forMenu)
guard let forMenu = forMenu,
let menuBlurEffectStyle = menuBlurEffectStyle,
let view = forMenu.visibleViewController?.view
, !UIAccessibilityIsReduceTransparencyEnabled() else {
return
}
if forMenu.originalMenuBackgroundColor == nil {
forMenu.originalMenuBackgroundColor = view.backgroundColor
}
let blurEffect = UIBlurEffect(style: menuBlurEffectStyle)
let blurView = UIVisualEffectView(effect: blurEffect)
view.backgroundColor = UIColor.clear
if let tableViewController = forMenu.visibleViewController as? UITableViewController {
tableViewController.tableView.backgroundView = blurView
tableViewController.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect)
tableViewController.tableView.reloadData()
} else {
blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
blurView.frame = view.bounds
view.insertSubview(blurView, at: 0)
}
}
fileprivate class func removeMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) {
guard let forMenu = forMenu,
let originalMenuBackgroundColor = forMenu.originalMenuBackgroundColor,
let view = forMenu.visibleViewController?.view else {
return
}
view.backgroundColor = originalMenuBackgroundColor
forMenu.originalMenuBackgroundColor = nil
if let tableViewController = forMenu.visibleViewController as? UITableViewController {
tableViewController.tableView.backgroundView = nil
tableViewController.tableView.separatorEffect = nil
tableViewController.tableView.reloadData()
} else if let blurView = view.subviews[0] as? UIVisualEffectView {
blurView.removeFromSuperview()
}
}
/**
Adds screen edge gestures to a view to present a menu.
- Parameter toView: The view to add gestures to.
- Parameter forMenu: The menu (left or right) you want to add a gesture for. If unspecified, gestures will be added for both sides.
- Returns: The array of screen edge gestures added to `toView`.
*/
@discardableResult open class func menuAddScreenEdgePanGesturesToPresent(toView: UIView, forMenu:UIRectEdge? = nil) -> [UIScreenEdgePanGestureRecognizer] {
var array = [UIScreenEdgePanGestureRecognizer]()
if forMenu != .right {
let leftScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer()
leftScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuLeftScreenEdge(_:)))
leftScreenEdgeGestureRecognizer.edges = .left
leftScreenEdgeGestureRecognizer.cancelsTouchesInView = true
toView.addGestureRecognizer(leftScreenEdgeGestureRecognizer)
array.append(leftScreenEdgeGestureRecognizer)
if SideMenuManager.menuLeftNavigationController == nil {
print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the left side was called before menuLeftNavigationController has been defined. The gesture will not work without a menu.")
}
}
if forMenu != .left {
let rightScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer()
rightScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuRightScreenEdge(_:)))
rightScreenEdgeGestureRecognizer.edges = .right
rightScreenEdgeGestureRecognizer.cancelsTouchesInView = true
toView.addGestureRecognizer(rightScreenEdgeGestureRecognizer)
array.append(rightScreenEdgeGestureRecognizer)
if SideMenuManager.menuRightNavigationController == nil {
print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the right side was called before menuRightNavigationController has been defined. The gesture will not work without a menu.")
}
}
return array
}
/**
Adds a pan edge gesture to a view to present menus.
- Parameter toView: The view to add a pan gesture to.
- Returns: The pan gesture added to `toView`.
*/
@discardableResult open class func menuAddPanGestureToPresent(toView: UIView) -> UIPanGestureRecognizer {
let panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuPan(_:)))
toView.addGestureRecognizer(panGestureRecognizer)
if SideMenuManager.menuLeftNavigationController ?? SideMenuManager.menuRightNavigationController == nil {
print("SideMenu Warning: menuAddPanGestureToPresent called before menuLeftNavigationController or menuRightNavigationController have been defined. Gestures will not work without a menu.")
}
return panGestureRecognizer
}
}
|
f4804e0419d0b6aec2c22a170ea442ec
| 46.424242 | 271 | 0.692971 | false | false | false | false |
jkolb/Swiftish
|
refs/heads/master
|
Sources/Swiftish/Vector4.swift
|
mit
|
1
|
/*
The MIT License (MIT)
Copyright (c) 2015-2017 Justin Kolb
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public struct Vector4<T: Vectorable> : Hashable, CustomStringConvertible {
public var x: T
public var y: T
public var z: T
public var w: T
@_transparent public var r: T {
return x
}
@_transparent public var g: T {
return y
}
@_transparent public var b: T {
return z
}
@_transparent public var a: T {
return w
}
public init() {
self.init(0, 0, 0, 0)
}
public init(_ v: T) {
self.init(v, v, v, v)
}
public init(_ v: Vector3<T>, _ c: T = 0) {
self.init(v.x, v.y, v.z, c)
}
public init(_ x: T, _ y: T, _ z: T, _ w: T) {
self.x = x
self.y = y
self.z = z
self.w = w
}
public var components: [T] {
get {
return [x, y, z, w]
}
set {
precondition(newValue.count == 4)
x = newValue[0]
y = newValue[1]
z = newValue[2]
w = newValue[3]
}
}
public subscript(index: Int) -> T {
get {
switch index {
case 0:
return x
case 1:
return y
case 2:
return z
case 3:
return w
default:
fatalError("Index out of range")
}
}
set {
switch index {
case 0:
x = newValue
case 1:
y = newValue
case 2:
z = newValue
case 3:
w = newValue
default:
fatalError("Index out of range")
}
}
}
public var minimum: T {
return min(min(min(x, y), z), w)
}
public var maximum: T {
return min(max(max(x, y), z), w)
}
public var description: String {
return "{\(x), \(y), \(z), \(w)}"
}
// MARK: - Addition
public static func +(a: Vector4<T>, b: T) -> Vector4<T> {
let x: T = a.x + b
let y: T = a.y + b
let z: T = a.z + b
let w: T = a.w + b
return Vector4<T>(x, y, z, w)
}
public static func +(a: T, b: Vector4<T>) -> Vector4<T> {
let x: T = a + b.x
let y: T = a + b.y
let z: T = a + b.z
let w: T = a + b.w
return Vector4<T>(x, y, z, w)
}
public static func +(a: Vector4<T>, b: Vector4<T>) -> Vector4<T> {
let x: T = a.x + b.x
let y: T = a.y + b.y
let z: T = a.z + b.z
let w: T = a.w + b.w
return Vector4<T>(x, y, z, w)
}
// MARK: - Subtraction
public static func -(a: Vector4<T>, b: T) -> Vector4<T> {
let x: T = a.x - b
let y: T = a.y - b
let z: T = a.z - b
let w: T = a.w - b
return Vector4<T>(x, y, z, w)
}
public static func -(a: T, b: Vector4<T>) -> Vector4<T> {
let x: T = a - b.x
let y: T = a - b.y
let z: T = a - b.z
let w: T = a - b.w
return Vector4<T>(x, y, z, w)
}
public static func -(a: Vector4<T>, b: Vector4<T>) -> Vector4<T> {
let x: T = a.x - b.x
let y: T = a.y - b.y
let z: T = a.z - b.z
let w: T = a.w - b.w
return Vector4<T>(x, y, z, w)
}
// MARK: - Multiplication
public static func *(a: Vector4<T>, b: T) -> Vector4<T> {
return Vector4<T>(
a.x * b,
a.y * b,
a.z * b,
a.w * b
)
}
public static func *(a: T, b: Vector4<T>) -> Vector4<T> {
let x: T = a * b.x
let y: T = a * b.y
let z: T = a * b.z
let w: T = a * b.w
return Vector4<T>(x, y, z, w)
}
public static func *(a: Vector4<T>, b: Vector4<T>) -> Vector4<T> {
let x: T = a.x * b.x
let y: T = a.y * b.y
let z: T = a.z * b.z
let w: T = a.w * b.w
return Vector4<T>(x, y, z, w)
}
// MARK: - Division
public static func /(a: Vector4<T>, b: T) -> Vector4<T> {
let x: T = a.x / b
let y: T = a.y / b
let z: T = a.z / b
let w: T = a.w / b
return Vector4<T>(x, y, z, w)
}
public static func /(a: T, b: Vector4<T>) -> Vector4<T> {
let x: T = a / b.x
let y: T = a / b.y
let z: T = a / b.z
let w: T = a / b.w
return Vector4<T>(x, y, z, w)
}
public static func /(a: Vector4<T>, b: Vector4<T>) -> Vector4<T> {
let x: T = a.x / b.x
let y: T = a.y / b.y
let z: T = a.z / b.z
let w: T = a.w / b.w
return Vector4<T>(x, y, z, w)
}
// MARK: - Negation
public static prefix func -(v: Vector4<T>) -> Vector4<T> {
let x: T = -v.x
let y: T = -v.y
let z: T = -v.z
let w: T = -v.w
return Vector4<T>(x, y, z, w)
}
public static prefix func +(v: Vector4<T>) -> Vector4<T> {
let x: T = +v.x
let y: T = +v.y
let z: T = +v.z
let w: T = +v.w
return Vector4<T>(x, y, z, w)
}
// MARK: Approximately Equal
public static func approx(_ a: Vector4<T>, _ b: Vector4<T>, epsilon: T) -> Bool {
let delta: Vector4<T> = b - a
let magnitude: Vector4<T> = abs(delta)
return magnitude.x <= epsilon && magnitude.y <= epsilon && magnitude.z <= epsilon && magnitude.w <= epsilon
}
// MARK: Absolute Value
public static func abs(_ a: Vector4<T>) -> Vector4<T> {
let x: T = Swift.abs(a.x)
let y: T = Swift.abs(a.y)
let z: T = Swift.abs(a.z)
let w: T = Swift.abs(a.w)
return Vector4<T>(x, y, z, w)
}
// MARK: - Sum
public static func sum(_ a: Vector4<T>) -> T {
return a.x + a.y + a.z + a.w
}
// MARK: - Geometric
public static func length(_ a: Vector4<T>) -> T {
return Vector4<T>.length2(a).squareRoot()
}
public static func length2(_ a: Vector4<T>) -> T {
let a2: Vector4<T> = a * a
return Vector4<T>.sum(a2)
}
public static func normalize(_ a: Vector4<T>) -> Vector4<T> {
return a / Vector4<T>.length(a)
}
public static func distance(_ a: Vector4<T>, _ b: Vector4<T>) -> T {
return Vector4<T>.distance2(a, b).squareRoot()
}
public static func distance2(_ a: Vector4<T>, _ b: Vector4<T>) -> T {
let difference: Vector4<T> = b - a
let difference2: Vector4<T> = difference * difference
return Vector4<T>.sum(difference2)
}
public static func dot(_ a: Vector4<T>, _ b: Vector4<T>) -> T {
let ab: Vector4<T> = a * b
return Vector4<T>.sum(ab)
}
// Trigonometry
public static func cos(_ a: Vector4<T>) -> Vector4<T> {
let x: T = T.cos(a.x)
let y: T = T.cos(a.y)
let z: T = T.cos(a.z)
let w: T = T.cos(a.w)
return Vector4<T>(x, y, z, w)
}
public static func sin(_ a: Vector4<T>) -> Vector4<T> {
let x: T = T.sin(a.x)
let y: T = T.sin(a.y)
let z: T = T.sin(a.z)
let w: T = T.sin(a.w)
return Vector4<T>(x, y, z, w)
}
}
extension Vector4 where T == Float {
public init(_ vf: IntVector4<UInt8>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<Int8>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<UInt16>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<Int16>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<UInt32>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<Int32>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<UInt64>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<Int64>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<UInt>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
public init(_ vf: IntVector4<Int>) {
self.init(Float(vf.x), Float(vf.y), Float(vf.z), Float(vf.w))
}
}
extension Vector4 where T == Double {
public init(_ vf: IntVector4<UInt8>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<Int8>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<UInt16>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<Int16>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<UInt32>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<Int32>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<UInt64>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<Int64>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<UInt>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
public init(_ vf: IntVector4<Int>) {
self.init(Double(vf.x), Double(vf.y), Double(vf.z), Double(vf.w))
}
}
|
7ef0de2d9ac6f30c9ca2193dd8361ec9
| 25.533175 | 115 | 0.485487 | false | false | false | false |
volendavidov/NagBar
|
refs/heads/master
|
NagBar/PasswordPromptController.swift
|
apache-2.0
|
1
|
//
// PasswordPromptController.swift
// NagBar
//
// Created by Volen Davidov on 02.05.16.
// Copyright © 2016 Volen Davidov. All rights reserved.
//
import Foundation
import Cocoa
import Alamofire
class PasswordPromptController : NSWindowController {
@IBOutlet weak fileprivate var okButton: NSButton!
@IBOutlet weak fileprivate var passwordField: NSSecureTextField!
@IBOutlet weak fileprivate var progressIndicator: NSProgressIndicator!
@IBOutlet weak fileprivate var textField: NSTextField!
private var currentMonitoringInstance: MonitoringInstance?
override func awakeFromNib() {
_ = self.nextMonitoringInstance()
self.textField.stringValue = String(format:NSLocalizedString("pleaseEnterPassword", comment: ""), self.currentMonitoringInstance!.name)
}
/**
* Set the next monitoring instance. Return false if there is no next monitoring instance.
*/
private func nextMonitoringInstance() -> Bool {
let enabledMonitoringInstances = MonitoringInstances().getAllEnabled()
let monitoringInstances = Array(enabledMonitoringInstances.keys.sorted())
if self.currentMonitoringInstance == nil {
if monitoringInstances.count > 0 {
self.currentMonitoringInstance = enabledMonitoringInstances[monitoringInstances[0]]
return true
}
}
for (index, monitoringInstance) in monitoringInstances.enumerated() {
if self.currentMonitoringInstance!.name == monitoringInstance && index + 1 < monitoringInstances.count {
self.currentMonitoringInstance = enabledMonitoringInstances[monitoringInstances[index + 1]]
return true
}
}
return false
}
private func startChecking() {
self.okButton.isEnabled = false
self.progressIndicator.startAnimation(nil)
}
private func stopChecking() {
self.okButton.isEnabled = true
self.progressIndicator.stopAnimation(nil)
}
@IBAction func checkConnection(_ sender: NSButton) {
// disable the button and start the progress indicator
self.startChecking()
// make the request
ConnectionManager.sharedInstance.manager!.request(self.currentMonitoringInstance!.url, method: .head).authenticate(user: self.currentMonitoringInstance!.username, password: self.passwordField.stringValue).validate().response { response in
if let error = response.error {
self.stopChecking()
self.retryModal(error as NSError)
} else {
// on success - set the password for the course of the app's life
PasswordStore.sharedInstance.set(self.currentMonitoringInstance!.name, password: self.passwordField.stringValue)
// if the passwords for all monitoring instances are set, and there is no next one
// then close the window and refresh
if !self.nextMonitoringInstance() {
self.window!.close()
LoadMonitoringData().refreshStatusData()
} else {
self.stopChecking()
self.textField.stringValue = String(format:NSLocalizedString("pleaseEnterPassword", comment: ""), self.currentMonitoringInstance!.name)
}
}
}
}
private func retryModal(_ error: NSError) {
let informativeText = String(format:NSLocalizedString("skipMonitoringInstance", comment: ""), self.errorCodeToText(error.code))
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("no", comment: ""))
alert.addButton(withTitle: NSLocalizedString("yes", comment: ""))
alert.messageText = NSLocalizedString("connectionFailed", comment: "")
alert.informativeText = informativeText
alert.alertStyle = .warning
if alert.runModal() == NSApplication.ModalResponse.alertSecondButtonReturn {
if self.nextMonitoringInstance() {
self.textField.stringValue = String(format:NSLocalizedString("pleaseEnterPassword", comment: ""), self.currentMonitoringInstance!.name)
} else {
self.window!.close()
}
}
}
private func errorCodeToText(_ code: Int) -> String {
switch code {
case -999:
return NSLocalizedString("incorrectPassword", comment: "")
case -1001:
return NSLocalizedString("connectionTimedOut", comment: "")
case -1004:
return NSLocalizedString("couldNotConnect", comment: "")
default:
return NSLocalizedString("unknownError", comment: "")
}
}
}
|
fa13afcc810e9484b59639771fdf4361
| 39.714286 | 246 | 0.638803 | false | false | false | false |
shaps80/Peek
|
refs/heads/master
|
Pod/Classes/Transformers/NSValue+Transformer.swift
|
mit
|
1
|
/*
Copyright © 23/04/2016 Shaps
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
/// Creates string representations of common values, e.g. CGPoint, CGRect, etc...
final class ValueTransformer: Foundation.ValueTransformer {
fileprivate static var floatFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.minimumFractionDigits = 0
formatter.minimumIntegerDigits = 1
formatter.roundingIncrement = 0.5
return formatter
}
override func transformedValue(_ value: Any?) -> Any? {
if let value = value as? NSValue {
let type = String(cString: value.objCType)
if type.hasPrefix("{CGRect") {
let rect = value.cgRectValue
return
"(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.minX)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.minY)))!)), " +
"(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.width)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.height)))!))"
}
if type.hasPrefix("{CGPoint") {
let point = value.cgPointValue
return "(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(point.x)))!), \(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(point.y)))!))"
}
if type.hasPrefix("{UIEdgeInset") {
let insets = value.uiEdgeInsetsValue
return
"(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.left)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.top)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.right)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.bottom)))!))"
}
if type.hasPrefix("{UIOffset") {
let offset = value.uiOffsetValue
return "(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(offset.horizontal)))!), \(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(offset.vertical)))!))"
}
if type.hasPrefix("{CGSize") {
let size = value.cgSizeValue
return "(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(size.width)))!), \(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(size.height)))!))"
}
}
return nil
}
override class func allowsReverseTransformation() -> Bool {
return false
}
}
|
7e94836bb8950d545e2c7c2b2fe20bad
| 47.792683 | 209 | 0.64184 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Me/Me Main/Presenter/MeScenePresenter.swift
|
gpl-2.0
|
1
|
import UIKit
/// Concrete implementation of ScenePresenter that presents the Me scene
/// in a UISplitViewController/UINavigationController view hierarchy
@objc
class MeScenePresenter: NSObject, ScenePresenter {
/// weak reference to the presented scene (no reference retained after it's dismissed)
private(set) weak var presentedViewController: UIViewController?
/// Done button action
@objc
private func dismissHandler() {
self.presentedViewController?.dismiss(animated: true)
}
func present(on viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
// prevent presenting if the scene is already presented
guard presentedViewController == nil else {
completion?()
return
}
let presentedViewController = makeNavigationController()
self.presentedViewController = presentedViewController
viewController.present(presentedViewController, animated: animated, completion: completion)
WPAnalytics.track(.meTabAccessed)
}
}
/// Presented UIViewController factory methods
private extension MeScenePresenter {
func makeDoneButton() -> UIBarButtonItem {
return UIBarButtonItem(target: self, action: #selector(dismissHandler))
}
func makeMeViewController() -> MeViewController {
return MeViewController()
}
func makeNavigationController() -> UINavigationController {
let meController = makeMeViewController()
let navigationController = UINavigationController(rootViewController: meController)
navigationController.restorationIdentifier = Restorer.Identifier.navigationController.rawValue
meController.navigationItem.rightBarButtonItem = makeDoneButton()
// present in formSheet on iPad, default on iPhone
if WPDeviceIdentification.isiPad() {
navigationController.modalPresentationStyle = .formSheet
navigationController.modalTransitionStyle = .coverVertical
}
return navigationController
}
}
/// Accessibility
extension UIBarButtonItem {
/// Initialize a 'Done' UIBarButtonItem with the specified target/action
/// - Parameters:
/// - target: target of the action to execute when the button is pressed
/// - action: selector of the action to execute when the button is pressed
convenience init(target: Any?, action: Selector) {
self.init(title: NSLocalizedString("Done", comment: "Title of the Done button on the me page"),
style: .done,
target: target,
action: action)
makeDoneButtonAccessible()
}
/// Adds accessibility traits for the `Me` bar button item
private func makeDoneButtonAccessible() {
accessibilityLabel = NSLocalizedString("Done", comment: "Accessibility label for the Done button in the Me screen.")
accessibilityHint = NSLocalizedString("Close the Me screen", comment: "Accessibility hint the Done button in the Me screen.")
accessibilityIdentifier = "doneBarButton"
accessibilityTraits = UIAccessibilityTraits.button
isAccessibilityElement = true
}
}
|
d136861b5cf0a3ce740e832577e4fd0e
| 38.9375 | 134 | 0.706416 | false | false | false | false |
aschwaighofer/swift
|
refs/heads/master
|
test/DebugInfo/enum.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend -primary-file %s -emit-ir -gdwarf-types -o - | %FileCheck %s --check-prefix=DWARF
// UNSUPPORTED: OS=watchos
protocol P {}
enum Either {
case First(Int64), Second(P), Neither
// CHECK: !DICompositeType({{.*}}name: "Either",
// CHECK-SAME: line: [[@LINE-3]],
// CHECK-SAME: size: {{328|168}},
}
// CHECK: ![[EMPTY:.*]] = !{}
// DWARF: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$sSiD"
let E : Either = .Neither;
// CHECK: !DICompositeType({{.*}}name: "Color",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: size: 8,
// CHECK-SAME: identifier: "$s4enum5ColorOD"
enum Color : UInt64 {
// This is effectively a 2-bit bitfield:
// DWARF: !DIDerivedType(tag: DW_TAG_member, name: "Red"
// DWARF-SAME: baseType: ![[UINT64:[0-9]+]]
// DWARF-SAME: size: 8{{[,)]}}
// DWARF: ![[UINT64]] = !DICompositeType({{.*}}identifier: "$ss6UInt64VD"
case Red, Green, Blue
}
// CHECK: !DICompositeType({{.*}}name: "MaybeIntPair",
// CHECK-SAME: line: [[@LINE+3]],
// CHECK-SAME: size: 136{{[,)]}}
// CHECK-SAME: identifier: "$s4enum12MaybeIntPairOD"
enum MaybeIntPair {
// DWARF: !DIDerivedType(tag: DW_TAG_member, name: "none"
// DWARF-SAME: baseType: ![[INT]]{{[,)]}}
case none
// DWARF: !DIDerivedType(tag: DW_TAG_member, name: "just"
// DWARF-SAME: baseType: ![[INTTUP:[0-9]+]]
// DWARF-SAME: size: 128{{[,)]}}
// DWARF: ![[INTTUP]] = !DICompositeType({{.*}}identifier: "$ss5Int64V_ABtD"
case just(Int64, Int64)
}
enum Maybe<T> {
case none
case just(T)
}
let r = Color.Red
let c = MaybeIntPair.just(74, 75)
// CHECK: !DICompositeType({{.*}}name: "Maybe",
// CHECK-SAME: line: [[@LINE-8]],
// CHECK-SAME: identifier: "$s4enum5MaybeOyAA5ColorOGD"
let movie : Maybe<Color> = .none
public enum Nothing { }
public func foo(_ empty : Nothing) { }
// CHECK: !DICompositeType({{.*}}name: "Nothing", {{.*}}elements: ![[EMPTY]]
// CHECK: !DICompositeType({{.*}}name: "Rose",
// CHECK-SAME: {{.*}}identifier: "$s4enum4RoseOyxG{{z?}}D")
enum Rose<A> {
case MkRose(() -> A, () -> [Rose<A>])
// DWARF: !DICompositeType({{.*}}name: "Rose",{{.*}}identifier: "$s4enum4RoseOyxGD")
case IORose(() -> Rose<A>)
}
func foo<T>(_ x : Rose<T>) -> Rose<T> { return x }
// CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}identifier: "$s4enum5TupleOyxGD")
// DWARF: !DICompositeType({{.*}}name: "Tuple",
// DWARF-SAME: {{.*}}identifier: "$s4enum5TupleOyxG{{z?}}D")
public enum Tuple<P> {
case C(P, () -> Tuple)
}
func bar<T>(_ x : Tuple<T>) -> Tuple<T> { return x }
// CHECK-DAG: ![[LIST:.*]] = !DICompositeType({{.*}}identifier: "$s4enum4ListOyxGD"
// CHECK-DAG: ![[LIST_MEMBER:.*]] = !DIDerivedType(tag: DW_TAG_member, {{.*}} baseType: ![[LIST]]
// CHECK-DAG: ![[LIST_ELTS:.*]] = !{![[LIST_MEMBER]]}
// CHECK-DAG: ![[LIST_CONTAINER:.*]] = !DICompositeType({{.*}}elements: ![[LIST_ELTS]]
// CHECK-DAG: ![[LET_LIST:.*]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[LIST_CONTAINER]])
// CHECK-DAG: !DILocalVariable(name: "self", arg: 1, {{.*}} line: [[@LINE+4]], type: ![[LET_LIST]], flags: DIFlagArtificial)
public enum List<T> {
indirect case Tail(List, T)
case End
func fooMyList() {}
}
|
1890a811125f1a99f8efb9914717a06d
| 36.184783 | 124 | 0.572932 | false | false | false | false |
kirmani/lockman
|
refs/heads/master
|
iOS/Lockman/Lockman/FirstViewController.swift
|
mit
|
1
|
//
// FirstViewController.swift
// fingerprintTest
//
// Created by Yuriy Minin on 11/7/15.
// Copyright © 2015 Yuriy Minin. All rights reserved.
//
import UIKit
import LocalAuthentication
import Alamofire
let baseURL = "http://api.codered.kirmani.io/lock"
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(netHex: 0xe1e0dd)
lockStatement.backgroundColor = UIColor(netHex: 0xe1e0dd)
lockButton.hidden = true
lockImage.image = UIImage(named: "lock")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet var dankButton: UIView!
@IBOutlet weak var lockStatement: UILabel!
@IBOutlet weak var authButton: UIButton!
@IBOutlet weak var lockButton: UIButton!
@IBOutlet weak var lockImage: UIImageView!
@IBAction func hitMeWitDatJSON(sender: AnyObject) {
Alamofire.request(.GET, baseURL + "/list").validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let id_list = JSON(value)
print("JSON: \(id_list)")
for result in id_list["result"].arrayValue {
print(result.stringValue)
let url = baseURL + "/id/" + result.stringValue
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let input = JSON(value)
print(input["result"]["image"])
}
case .Failure(let error):
print(error)
}
}
}
}
case .Failure(let error):
print(error)
}
}
}
@IBAction func lockButtonTouchUp(sender: UIButton) {
Alamofire.request(.PUT, "http://api.codered.kirmani.io/lock/close")
self.lockStatement.text = "Your Door is Locked"
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.lockImage.alpha = 100.0
self.authButton.alpha = 100.0
self.lockButton.hidden = true
self.lockButton.alpha = 0.0
}, completion: nil)
}
@IBAction func authenticateButtonTouchUp(sender: UIButton) {
// Get the local authentication context.
let context = LAContext()
// Declare a NSError variable.
var error: NSError?
// Set the reason string that will appear on the authentication alert.
let reasonString = "Authentication is needed to unlock your door."
// Check if the device can evaluate the policy.
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
[context .evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success: Bool, evalPolicyError: NSError?) -> Void in
if success {
Alamofire.request(.PUT, "http://api.codered.kirmani.io/lock/open")
dispatch_async(dispatch_get_main_queue()) {
UIView.animateWithDuration(0.4, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.lockImage.alpha = 0.0
self.authButton.alpha = 0.0
self.lockButton.hidden = false
self.lockButton.alpha = 100.0
}, completion: nil)
self.lockStatement.text = "Your Door is Unlocked"
}
Alamofire.request(.GET, "http://api.codered.kirmani.io/lock/list").validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
print("JSON: \(json)")
}
case .Failure(let error):
print(error)
}
}
}
else{
// If authentication failed then show a message to the console with a short description.
// In case that the error is a user fallback, then show the password alert view.
print(evalPolicyError?.localizedDescription)
switch evalPolicyError!.code {
case LAError.SystemCancel.rawValue:
print("Authentication was cancelled by the system")
case LAError.UserCancel.rawValue:
print("Authentication was cancelled by the user")
case LAError.UserFallback.rawValue:
print("User selected to enter custom password")
default:
print("Authentication failed")
}
}
})]
}
else{
// If the security policy cannot be evaluated then show a short message depending on the error.
switch error!.code{
case LAError.TouchIDNotEnrolled.rawValue:
print("TouchID is not enrolled")
case LAError.PasscodeNotSet.rawValue:
print("A passcode has not been set")
default:
// The LAError.TouchIDNotAvailable case.
print("TouchID not available")
}
// Optionally the error description can be displayed on the console.
print(error?.localizedDescription)
}
}
}
|
1edff10bcf269444d6cee3702b2c9431
| 38.944134 | 180 | 0.515664 | false | false | false | false |
reproto/reproto
|
refs/heads/main
|
it/versions/structures/codable/swift/ReprotoCodable.swift
|
apache-2.0
|
1
|
class AnyCodable: Codable {
public let value: Any
public required init(from decoder: Decoder) throws {
if var array = try? decoder.unkeyedContainer() {
self.value = try AnyCodable.decodeArray(from: &array)
return
}
if var c = try? decoder.container(keyedBy: AnyCodingKey.self) {
self.value = try AnyCodable.decodeDictionary(from: &c)
return
}
let c = try decoder.singleValueContainer()
self.value = try AnyCodable.decode(from: c)
}
public func encode(to encoder: Encoder) throws {
if let arr = self.value as? [Any] {
var c = encoder.unkeyedContainer()
try AnyCodable.encode(to: &c, array: arr)
return
}
if let dict = self.value as? [String: Any] {
var c = encoder.container(keyedBy: AnyCodingKey.self)
try AnyCodable.encode(to: &c, dictionary: dict)
return
}
var c = encoder.singleValueContainer()
try AnyCodable.encode(to: &c, value: self.value)
}
static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError {
let context = DecodingError.Context(
codingPath: codingPath,
debugDescription: "Cannot decode AnyCodable")
return DecodingError.typeMismatch(AnyCodable.self, context)
}
static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError {
let context = EncodingError.Context(
codingPath: codingPath,
debugDescription: "Cannot encode AnyCodable")
return EncodingError.invalidValue(value, context)
}
static func decode(from c: SingleValueDecodingContainer) throws -> Any {
if let value = try? c.decode(Bool.self) {
return value
}
if let value = try? c.decode(Int.self) {
return value
}
if let value = try? c.decode(UInt.self) {
return value
}
if let value = try? c.decode(Int32.self) {
return value
}
if let value = try? c.decode(Int64.self) {
return value
}
if let value = try? c.decode(UInt32.self) {
return value
}
if let value = try? c.decode(UInt64.self) {
return value
}
if let value = try? c.decode(Float.self) {
return value
}
if let value = try? c.decode(Double.self) {
return value
}
if let value = try? c.decode(String.self) {
return value
}
if c.decodeNil() {
return AnyNull()
}
throw decodingError(forCodingPath: c.codingPath)
}
static func decode(from c: inout UnkeyedDecodingContainer) throws -> Any {
if let value = try? c.decode(Bool.self) {
return value
}
if let value = try? c.decode(Int.self) {
return value
}
if let value = try? c.decode(UInt.self) {
return value
}
if let value = try? c.decode(Int32.self) {
return value
}
if let value = try? c.decode(Int64.self) {
return value
}
if let value = try? c.decode(UInt32.self) {
return value
}
if let value = try? c.decode(UInt64.self) {
return value
}
if let value = try? c.decode(Float.self) {
return value
}
if let value = try? c.decode(Double.self) {
return value
}
if let value = try? c.decode(String.self) {
return value
}
if let value = try? c.decodeNil() {
if value {
return AnyNull()
}
}
if var c = try? c.nestedUnkeyedContainer() {
return try decodeArray(from: &c)
}
if var c = try? c.nestedContainer(keyedBy: AnyCodingKey.self) {
return try decodeDictionary(from: &c)
}
throw decodingError(forCodingPath: c.codingPath)
}
static func decode(from c: inout KeyedDecodingContainer<AnyCodingKey>, forKey key: AnyCodingKey) throws -> Any {
if let value = try? c.decode(Bool.self, forKey: key) {
return value
}
if let value = try? c.decode(Int.self, forKey: key) {
return value
}
if let value = try? c.decode(UInt.self, forKey: key) {
return value
}
if let value = try? c.decode(Int32.self, forKey: key) {
return value
}
if let value = try? c.decode(Int64.self, forKey: key) {
return value
}
if let value = try? c.decode(UInt32.self, forKey: key) {
return value
}
if let value = try? c.decode(UInt64.self, forKey: key) {
return value
}
if let value = try? c.decode(Float.self, forKey: key) {
return value
}
if let value = try? c.decode(Double.self, forKey: key) {
return value
}
if let value = try? c.decode(String.self, forKey: key) {
return value
}
if let value = try? c.decodeNil(forKey: key) {
if value {
return AnyNull()
}
}
if var c = try? c.nestedUnkeyedContainer(forKey: key) {
return try decodeArray(from: &c)
}
if var c = try? c.nestedContainer(keyedBy: AnyCodingKey.self, forKey: key) {
return try decodeDictionary(from: &c)
}
throw decodingError(forCodingPath: c.codingPath)
}
static func decodeArray(from c: inout UnkeyedDecodingContainer) throws -> [Any] {
var array: [Any] = []
while !c.isAtEnd {
array.append(try decode(from: &c))
}
return array
}
static func decodeDictionary(from c: inout KeyedDecodingContainer<AnyCodingKey>) throws -> [String: Any] {
var dict = [String: Any]()
for key in c.allKeys {
dict[key.stringValue] = try decode(from: &c, forKey: key)
}
return dict
}
static func encode(to c: inout SingleValueEncodingContainer, value: Any) throws {
switch value {
case let value as Bool:
try c.encode(value)
case let value as Int:
try c.encode(value)
case let value as UInt:
try c.encode(value)
case let value as Int32:
try c.encode(value)
case let value as Int64:
try c.encode(value)
case let value as UInt32:
try c.encode(value)
case let value as UInt64:
try c.encode(value)
case let value as Float:
try c.encode(value)
case let value as Double:
try c.encode(value)
case let value as String:
try c.encode(value)
case _ as AnyNull:
try c.encodeNil()
default:
throw encodingError(forValue: value, codingPath: c.codingPath)
}
}
static func encode(to c: inout UnkeyedEncodingContainer, array: [Any]) throws {
for value in array {
switch value {
case let value as Bool:
try c.encode(value)
case let value as Int:
try c.encode(value)
case let value as UInt:
try c.encode(value)
case let value as Int32:
try c.encode(value)
case let value as Int64:
try c.encode(value)
case let value as UInt32:
try c.encode(value)
case let value as UInt64:
try c.encode(value)
case let value as Float:
try c.encode(value)
case let value as Double:
try c.encode(value)
case let value as String:
try c.encode(value)
case let value as [Any]:
var c = c.nestedUnkeyedContainer()
try encode(to: &c, array: value)
case let value as [String: Any]:
var c = c.nestedContainer(keyedBy: AnyCodingKey.self)
try encode(to: &c, dictionary: value)
case _ as AnyNull:
try c.encodeNil()
default:
throw encodingError(forValue: value, codingPath: c.codingPath)
}
}
}
static func encode(to c: inout KeyedEncodingContainer<AnyCodingKey>, dictionary: [String: Any]) throws {
for (key, value) in dictionary {
let key = AnyCodingKey(stringValue: key)!
switch value {
case let value as Bool:
try c.encode(value, forKey: key)
case let value as Int:
try c.encode(value, forKey: key)
case let value as UInt:
try c.encode(value, forKey: key)
case let value as Int32:
try c.encode(value, forKey: key)
case let value as Int64:
try c.encode(value, forKey: key)
case let value as UInt32:
try c.encode(value, forKey: key)
case let value as UInt64:
try c.encode(value, forKey: key)
case let value as Float:
try c.encode(value, forKey: key)
case let value as Double:
try c.encode(value, forKey: key)
case let value as String:
try c.encode(value, forKey: key)
case let value as [Any]:
var c = c.nestedUnkeyedContainer(forKey: key)
try encode(to: &c, array: value)
case let value as [String: Any]:
var c = c.nestedContainer(keyedBy: AnyCodingKey.self, forKey: key)
try encode(to: &c, dictionary: value)
case _ as AnyNull:
try c.encodeNil(forKey: key)
default:
throw encodingError(forValue: value, codingPath: c.codingPath)
}
}
}
}
class AnyCodingKey: CodingKey {
let key: String
required init?(intValue: Int) {
return nil
}
required init?(stringValue: String) {
key = stringValue
}
var intValue: Int? {
return nil
}
var stringValue: String {
return key
}
}
class AnyNull: Codable {
public init() {
}
public required init(from decoder: Decoder) throws {
let c = try decoder.singleValueContainer()
if !c.decodeNil() {
throw DecodingError.typeMismatch(AnyNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for AnyNull"))
}
}
public func encode(to encoder: Encoder) throws {
var c = encoder.singleValueContainer()
try c.encodeNil()
}
}
|
e702e5620ea5384f38138231c01008ef
| 24.790761 | 151 | 0.619218 | false | false | false | false |
RevenueCat/purchases-ios
|
refs/heads/main
|
Sources/Support/ManageSubscriptionsHelper.swift
|
mit
|
1
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// ManageSubscriptionsHelper.swift
//
// Created by Andrés Boedo on 16/8/21.
import StoreKit
class ManageSubscriptionsHelper {
private let systemInfo: SystemInfo
private let customerInfoManager: CustomerInfoManager
private let currentUserProvider: CurrentUserProvider
init(systemInfo: SystemInfo,
customerInfoManager: CustomerInfoManager,
currentUserProvider: CurrentUserProvider) {
self.systemInfo = systemInfo
self.customerInfoManager = customerInfoManager
self.currentUserProvider = currentUserProvider
}
#if os(iOS) || os(macOS)
@available(watchOS, unavailable)
@available(tvOS, unavailable)
func showManageSubscriptions(completion: @escaping (Result<Void, PurchasesError>) -> Void) {
let currentAppUserID = self.currentUserProvider.currentAppUserID
self.customerInfoManager.customerInfo(appUserID: currentAppUserID,
fetchPolicy: .cachedOrFetched) { @Sendable result in
let result: Result<URL, PurchasesError> = result
.mapError { error in
let message = Strings.failed_to_get_management_url_error_unknown(error: error)
return ErrorUtils.customerInfoError(withMessage: message.description, error: error)
}
.flatMap { customerInfo in
guard let managementURL = customerInfo.managementURL else {
Logger.debug(Strings.management_url_nil_opening_default)
return .success(SystemInfo.appleSubscriptionsURL)
}
return .success(managementURL)
}
switch result {
case let .success(url):
if SystemInfo.isAppleSubscription(managementURL: url) {
self.showAppleManageSubscriptions(managementURL: url, completion: completion)
} else {
self.openURL(url, completion: completion)
}
case let .failure(error):
completion(.failure(error))
}
}
}
#endif
}
// @unchecked because:
// - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe.
extension ManageSubscriptionsHelper: @unchecked Sendable {}
// MARK: - Private
@available(watchOS, unavailable)
@available(tvOS, unavailable)
private extension ManageSubscriptionsHelper {
func showAppleManageSubscriptions(managementURL: URL,
completion: @escaping (Result<Void, PurchasesError>) -> Void) {
#if os(iOS) && !targetEnvironment(macCatalyst)
if #available(iOS 15.0, *),
// showManageSubscriptions doesn't work on iOS apps running on Apple Silicon
// https://developer.apple.com/documentation/storekit/appstore/3803198-showmanagesubscriptions#
!ProcessInfo().isiOSAppOnMac {
Async.call(with: completion) {
return await self.showSK2ManageSubscriptions()
}
return
}
#endif
openURL(managementURL, completion: completion)
}
func openURL(_ url: URL, completion: @escaping (Result<Void, PurchasesError>) -> Void) {
#if os(iOS)
openURLIfNotAppExtension(url: url)
#elseif os(macOS)
NSWorkspace.shared.open(url)
#endif
completion(.success(()))
}
#if os(iOS)
// we can't directly reference UIApplication.shared in case this SDK is embedded into an app extension.
// so we ensure that it's not running in an app extension and use selectors to call UIApplication methods.
func openURLIfNotAppExtension(url: URL) {
guard !systemInfo.isAppExtension,
let application = systemInfo.sharedUIApplication else { return }
// NSInvocation is needed because the method takes three arguments
// and performSelector works for up to 2
typealias ClosureType = @convention(c) (AnyObject, Selector, NSURL, NSDictionary?, Any?) -> Void
let selector: Selector = NSSelectorFromString("openURL:options:completionHandler:")
let methodIMP: IMP! = application.method(for: selector)
let openURLMethod = unsafeBitCast(methodIMP, to: ClosureType.self)
openURLMethod(application, selector, url as NSURL, nil, nil)
}
@MainActor
@available(iOS 15.0, *)
@available(macOS, unavailable)
func showSK2ManageSubscriptions() async -> Result<Void, PurchasesError> {
guard let application = systemInfo.sharedUIApplication,
let windowScene = application.currentWindowScene else {
let message = Strings.failed_to_get_window_scene
return .failure(ErrorUtils.storeProblemError(withMessage: message.description))
}
#if os(iOS)
// Note: we're ignoring the result of AppStore.showManageSubscriptions(in:) because as of
// iOS 15.2, it only returns after the sheet is dismissed, which isn't desired.
_ = Task<Void, Never> {
do {
try await AppStore.showManageSubscriptions(in: windowScene)
Logger.info(Strings.susbscription_management_sheet_dismissed)
} catch {
let message = Strings.error_from_appstore_show_manage_subscription(error: error)
Logger.appleError(message)
}
}
return .success(())
#else
fatalError(Strings.manageSubscription.show_manage_subscriptions_called_in_unsupported_platform.description)
#endif
}
#endif
}
|
bb3eeb9dbfc8f8622cd76d4689d29b4d
| 37.48366 | 117 | 0.648607 | false | false | false | false |
yaroslav-zhurakovskiy/PainlessInjection
|
refs/heads/master
|
Tests/Fixtures/Modules.swift
|
mit
|
1
|
//
// Modules.swift
// PainlessInjection
//
// Created by Yaroslav Zhurakovskiy on 7/11/16.
// Copyright © 2016 Yaroslav Zhurakovskiy. All rights reserved.
//
import Foundation
import PainlessInjection
import XCTest
class EmptyTestModule: Module {
override func load() {
}
}
class ModuleWithDependency: Module {
var dependency: Dependency!
required init() {
super.init()
}
override func load() {
define(String.self) { "Hello" } . decorate { dependency in
self.dependency = dependency
return dependency
}
}
func assertDependencyType(_ type: Any.Type, file: StaticString = #file, line: UInt = #line) {
XCTAssertTrue(
dependency.type == type,
"Type should be String but got \(dependency.type)",
file: file,
line: line
)
}
}
|
a866304ba59f634fde16447ac69957f4
| 20.756098 | 97 | 0.596413 | false | false | false | false |
SwiftStudies/OysterKit
|
refs/heads/master
|
Sources/stlrc/Framework/Extensions/DictionaryExtensions.swift
|
bsd-2-clause
|
1
|
//
// DictionaryExtensions.swift
// CommandKit
//
// Created by Sean Alling on 11/8/17.
//
import Foundation
extension Array where Element == Command {
/**
*/
var numberOfTabs: Int {
let keys = self.map({ $0.name })
let largestKey = keys.reduce(into: "", { largest, newValue in
largest = newValue.count > largest.count ? newValue : largest
})
let rawNumberOfTabs = largestKey.count / 4
let modulo = 10 % rawNumberOfTabs
return (modulo == 0) ? (rawNumberOfTabs + 1) : rawNumberOfTabs
}
}
extension Array where Element == Option {
/**
*/
var numberOfTabs: Int {
let keys = self.map({ $0.shortForm ?? $0.longForm })
let largestKey = keys.reduce(into: "", { largest, newValue in
largest = newValue.count > largest.count ? newValue : largest
})
let rawNumberOfTabs = largestKey.count < 4 ? 1 : largestKey.count / 4
let modulo = 10 % rawNumberOfTabs
return (modulo == 0) ? (rawNumberOfTabs + 1) : rawNumberOfTabs
}
}
|
4e512a77209e0e41d48ff62cf7e070e0
| 26.74359 | 77 | 0.588725 | false | false | false | false |
lotpb/iosSQLswift
|
refs/heads/master
|
mySQLswift/ContactController.swift
|
gpl-2.0
|
1
|
//
// ContactController.swift
// mySQLswift
//
// Created by Peter Balsamo on 1/20/16.
// Copyright © 2016 Peter Balsamo. All rights reserved.
//
import UIKit
import Contacts
class ContactController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak private var tableView: UITableView!
@IBOutlet weak private var searchBar: UISearchBar!
private var contacts = [CNContact]()
private var authStatus: CNAuthorizationStatus = .Denied {
didSet { // switch enabled search bar, depending contacts permission
searchBar.userInteractionEnabled = authStatus == .Authorized
if authStatus == .Authorized { // all search
contacts = fetchContacts("")
tableView.reloadData()
}
}
}
private let kCellID = "Cell"
// =========================================================================
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
checkAuthorization()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: kCellID)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// =========================================================================
// MARK: - UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
contacts = fetchContacts(searchText)
tableView.reloadData()
}
// =========================================================================
//MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kCellID, forIndexPath: indexPath)
let contact = contacts[indexPath.row]
// get the full name
let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "NO NAME"
cell.textLabel?.text = fullName
return cell
}
// =========================================================================
//MARK: - UITableViewDelegate
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let deleteActionHandler = { (action: UITableViewRowAction, index: NSIndexPath) in
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { [unowned self] (action: UIAlertAction) in
// set the data to be deleted
let request = CNSaveRequest()
let contact = self.contacts[index.row].mutableCopy() as! CNMutableContact
request.deleteContact(contact)
do {
// save
let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "NO NAME"
let store = CNContactStore()
try store.executeSaveRequest(request)
NSLog("\(fullName) Deleted")
// update table
self.contacts.removeAtIndex(index.row)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.deleteRowsAtIndexPaths([index], withRowAnimation: .Fade)
})
} catch let error as NSError {
NSLog("Delete error \(error.localizedDescription)")
}
})
let cancelAction = UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.Default, handler: { [unowned self] (action: UIAlertAction) in
self.tableView.editing = false
})
// show alert
self.showAlert(title: "Delete Contact", message: "OK?", actions: [okAction, cancelAction])
}
return [UITableViewRowAction(style: .Destructive, title: "Delete", handler: deleteActionHandler)]
}
// =========================================================================
// MARK: - IBAction
@IBAction func tapped(sender: AnyObject) {
view.endEditing(true)
}
// =========================================================================
// MARK: - Helpers
private func checkAuthorization() {
// get current status
let status = CNContactStore.authorizationStatusForEntityType(.Contacts)
authStatus = status
switch status {
case .NotDetermined: // case of first access
CNContactStore().requestAccessForEntityType(.Contacts) { [unowned self] (granted, error) in
if granted {
NSLog("Permission allowed")
self.authStatus = .Authorized
} else {
NSLog("Permission denied")
self.authStatus = .Denied
}
}
case .Restricted, .Denied:
NSLog("Unauthorized")
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .Default, handler: { (action: UIAlertAction) in
let url = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(url!)
})
showAlert(
title: "Permission Denied",
message: "You have not permission to access contacts. Please allow the access the Settings screen.",
actions: [okAction, settingsAction])
case .Authorized:
NSLog("Authorized")
}
}
// fetch the contact of matching names
private func fetchContacts(name: String) -> [CNContact] {
let store = CNContactStore()
do {
let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)])
if name.isEmpty { // all search
request.predicate = nil
} else {
request.predicate = CNContact.predicateForContactsMatchingName(name)
}
var contacts = [CNContact]()
try store.enumerateContactsWithFetchRequest(request, usingBlock: { (contact, error) in
contacts.append(contact)
})
return contacts
} catch let error as NSError {
NSLog("Fetch error \(error.localizedDescription)")
return []
}
}
private func showAlert(title title: String, message: String, actions: [UIAlertAction]) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
for action in actions {
alert.addAction(action)
}
dispatch_async(dispatch_get_main_queue(), { [unowned self] () in
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
|
c5735393d0fc9432ddb509ab896da488
| 36.733668 | 149 | 0.545551 | false | false | false | false |
ryuichis/swift-ast
|
refs/heads/master
|
Tests/ParserTests/Expression/Primary/ParserKeyPathExpressionTests.swift
|
apache-2.0
|
2
|
/*
Copyright 2017-2018 Ryuichi Intellectual Property and the Yanagiba project 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 XCTest
@testable import AST
class ParserKeyPathExpressionTests: XCTestCase {
func testOneComponent() {
parseExpressionAndTest("\\.foo", "\\.foo", testClosure: { expr in
guard let keyPathExpr = expr as? KeyPathExpression else {
XCTFail("Failed in getting a key path expression")
return
}
XCTAssertNil(keyPathExpr.type)
XCTAssertEqual(keyPathExpr.components.count, 1)
ASTTextEqual(keyPathExpr.components[0].0, "foo")
XCTAssertTrue(keyPathExpr.components[0].1.isEmpty)
})
}
func testMultipleComponents() {
parseExpressionAndTest("\\.foo.bar.a.b.c", "\\.foo.bar.a.b.c", testClosure: { expr in
guard let keyPathExpr = expr as? KeyPathExpression else {
XCTFail("Failed in getting a key path expression")
return
}
XCTAssertNil(keyPathExpr.type)
XCTAssertEqual(keyPathExpr.components.count, 5)
ASTTextEqual(keyPathExpr.components[0].0, "foo")
XCTAssertTrue(keyPathExpr.components[0].1.isEmpty)
ASTTextEqual(keyPathExpr.components[1].0, "bar")
XCTAssertTrue(keyPathExpr.components[1].1.isEmpty)
ASTTextEqual(keyPathExpr.components[2].0, "a")
XCTAssertTrue(keyPathExpr.components[2].1.isEmpty)
ASTTextEqual(keyPathExpr.components[3].0, "b")
XCTAssertTrue(keyPathExpr.components[3].1.isEmpty)
ASTTextEqual(keyPathExpr.components[4].0, "c")
XCTAssertTrue(keyPathExpr.components[4].1.isEmpty)
})
}
func testComponentsWithPostfixes() { // swift-lint:suppress(high_cyclomatic_complexity,high_ncss)
parseExpressionAndTest(
"\\.?.!.[foo, bar].a?.b!.c[foo, bar].?!?!.![x]!?[y][z]!",
"\\.?.!.[foo, bar].a?.b!.c[foo, bar].?!?!.![x]!?[y][z]!",
testClosure: { expr in
guard let keyPathExpr = expr as? KeyPathExpression else {
XCTFail("Failed in getting a key path expression")
return
}
XCTAssertNil(keyPathExpr.type)
XCTAssertEqual(keyPathExpr.components.count, 8)
XCTAssertNil(keyPathExpr.components[0].0)
let postfixes0 = keyPathExpr.components[0].1
XCTAssertEqual(postfixes0.count, 1)
guard case .question = postfixes0[0] else {
XCTFail("Failed in getting a question postfix for keypath expression component 0.")
return
}
XCTAssertNil(keyPathExpr.components[1].0)
let postfixes1 = keyPathExpr.components[1].1
XCTAssertEqual(postfixes1.count, 1)
guard case .exclaim = postfixes1[0] else {
XCTFail("Failed in getting an exclaim postfix for keypath expression component 1.")
return
}
XCTAssertNil(keyPathExpr.components[2].0)
let postfixes2 = keyPathExpr.components[2].1
XCTAssertEqual(postfixes2.count, 1)
guard case .subscript(let arg2) = postfixes2[0], arg2.count == 2 else {
XCTFail("Failed in getting a subscript postfix for keypath expression component 2.")
return
}
ASTTextEqual(keyPathExpr.components[3].0, "a")
let postfixes3 = keyPathExpr.components[3].1
XCTAssertEqual(postfixes3.count, 1)
guard case .question = postfixes3[0] else {
XCTFail("Failed in getting a question postfix for keypath expression component 3.")
return
}
ASTTextEqual(keyPathExpr.components[4].0, "b")
let postfixes4 = keyPathExpr.components[4].1
XCTAssertEqual(postfixes4.count, 1)
guard case .exclaim = postfixes4[0] else {
XCTFail("Failed in getting an exclaim postfix for keypath expression component 4.")
return
}
ASTTextEqual(keyPathExpr.components[5].0, "c")
let postfixes5 = keyPathExpr.components[5].1
XCTAssertEqual(postfixes5.count, 1)
guard case .subscript(let arg5) = postfixes5[0], arg5.count == 2 else {
XCTFail("Failed in getting a subscript postfix for keypath expression component 5.")
return
}
XCTAssertNil(keyPathExpr.components[6].0)
let postfixes6 = keyPathExpr.components[6].1
XCTAssertEqual(postfixes6.count, 4)
guard
case .question = postfixes6[0],
case .exclaim = postfixes6[1],
case .question = postfixes6[2],
case .exclaim = postfixes6[3]
else {
XCTFail("Failed in getting mixed postfixes for keypath expression component 6.")
return
}
XCTAssertNil(keyPathExpr.components[7].0)
let postfixes7 = keyPathExpr.components[7].1
XCTAssertEqual(postfixes7.count, 7)
guard
case .exclaim = postfixes7[0],
case .subscript = postfixes7[1],
case .exclaim = postfixes7[2],
case .question = postfixes7[3],
case .subscript = postfixes7[4],
case .subscript = postfixes7[5],
case .exclaim = postfixes7[6]
else {
XCTFail("Failed in getting mixed postfixes for keypath expression component 7.")
return
}
})
}
func testType() {
parseExpressionAndTest("\\foo.bar", "\\foo.bar", testClosure: { expr in
guard let keyPathExpr = expr as? KeyPathExpression,
let typeIdentifier = keyPathExpr.type as? TypeIdentifier else {
XCTFail("Failed in getting a key path expression")
return
}
XCTAssertEqual(typeIdentifier.names.count, 1)
ASTTextEqual(typeIdentifier.names[0].name, "foo")
XCTAssertNil(typeIdentifier.names[0].genericArgumentClause)
XCTAssertEqual(keyPathExpr.components.count, 1)
ASTTextEqual(keyPathExpr.components[0].0, "bar")
XCTAssertTrue(keyPathExpr.components[0].1.isEmpty)
})
parseExpressionAndTest("\\foo.bar.a.b.c", "\\foo.bar.a.b.c", testClosure: { expr in
guard let keyPathExpr = expr as? KeyPathExpression,
let typeIdentifier = keyPathExpr.type as? TypeIdentifier else {
XCTFail("Failed in getting a key path expression")
return
}
XCTAssertEqual(typeIdentifier.names.count, 1)
ASTTextEqual(typeIdentifier.names[0].name, "foo")
XCTAssertNil(typeIdentifier.names[0].genericArgumentClause)
XCTAssertEqual(keyPathExpr.components.count, 4)
ASTTextEqual(keyPathExpr.components[0].0, "bar")
XCTAssertTrue(keyPathExpr.components[0].1.isEmpty)
ASTTextEqual(keyPathExpr.components[1].0, "a")
XCTAssertTrue(keyPathExpr.components[1].1.isEmpty)
ASTTextEqual(keyPathExpr.components[2].0, "b")
XCTAssertTrue(keyPathExpr.components[2].1.isEmpty)
ASTTextEqual(keyPathExpr.components[3].0, "c")
XCTAssertTrue(keyPathExpr.components[3].1.isEmpty)
})
}
func testSourceRange() {
parseExpressionAndTest("\\.foo", "\\.foo", testClosure: { expr in
XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, 6))
})
}
static var allTests = [
("testOneComponent", testOneComponent),
("testMultipleComponents", testMultipleComponents),
("testComponentsWithPostfixes", testComponentsWithPostfixes),
("testType", testType),
("testSourceRange", testSourceRange),
]
}
|
ef83732a475806e9adc2144e5467f73b
| 37.590909 | 99 | 0.675959 | false | true | false | false |
SemperIdem/SwiftMarkdownParser
|
refs/heads/master
|
Pod/Classes/MarkdownParseKit.swift
|
mit
|
2
|
//
// SundownWrapper.swift
// StackoverflowQuestionsExamples
//
// Created by Semper_Idem on 16/3/21.
// Copyright © 2016年 1-xing. All rights reserved.
//
import Foundation
public class MarkdownParse {
/// converts the markdown in the file to an html string
public static func convertMarkdownFileAtPath(path: String) -> String {
guard let string = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) else { fatalError("Cannot read file path!") }
return convertMarkdownString(string)
}
/// converts the markdown at the url to an html string
public static func convertMarkdownFileAtURL(url: NSURL) -> String {
guard let string = try? String(contentsOfURL: url, encoding: NSUTF8StringEncoding) else { fatalError("Cannot read URL!") }
return convertMarkdownString(string)
}
/// converts the given markdown string to an html string
public static func convertMarkdownString(markdown: String) -> String {
if markdown.isEmpty {
fatalError("Empty string passed into conversion method.")
}
guard let data = markdown.dataUsingEncoding(NSUTF8StringEncoding) else { fatalError("Cannot encoding the data!") }
let ob = bufnew(data.length)
var callbacks = sd_callbacks()
var options = html_renderopt()
sdhtml_renderer(&callbacks, &options, 0)
let md = sd_markdown_new(0, 16, &callbacks, &options)
sd_markdown_render(ob, unsafeBitCast(data.bytes, UnsafeMutablePointer<UInt8>.self), data.length, md)
sd_markdown_free(md)
if ob.memory.size == 0 {
fatalError("Conversion of input string resulted in no html")
}
guard let string = String(bytesNoCopy: ob.memory.data, length: ob.memory.size, encoding: NSUTF8StringEncoding, freeWhenDone: true) else { fatalError("Cannot decoding the data!") }
return string
}
}
|
36ef2ae6b6f3efb07825ef2e28239d8c
| 39.916667 | 187 | 0.667855 | false | false | false | false |
mattwelborn/HSTracker
|
refs/heads/master
|
HSTracker/Importers/Handlers/HearthstoneDecks.swift
|
mit
|
1
|
//
// HearthstoneDecks.swift
// HSTracker
//
// Created by Benjamin Michotte on 25/02/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Kanna
import CleanroomLogger
final class HearthstoneDecks: BaseNetImporter, NetImporterAware {
static let classes = [
"Chaman": "shaman",
"Chasseur": "hunter",
"Démoniste": "warlock",
"Druide": "druid",
"Guerrier": "warrior",
"Mage": "mage",
"Paladin": "paladin",
"Prêtre": "priest",
"Voleur": "rogue"
]
var siteName: String {
return "Hearthstone-Decks"
}
func handleUrl(url: String) -> Bool {
return url.match("hearthstone-decks\\.com")
}
func loadDeck(url: String, completion: Deck? -> Void) throws {
loadHtml(url) { (html) -> Void in
if let html = html, doc = Kanna.HTML(html: html, encoding: NSUTF8StringEncoding) {
var className: String?
if let classNode = doc.at_xpath("//input[@id='classe_nom']") {
if let clazz = classNode["value"] {
className = HearthstoneDecks.classes[clazz]
Log.verbose?.message("found \(className)")
}
}
var deckName: String?
if let deckNode = doc.at_xpath("//div[@id='content']//h1") {
deckName = deckNode.text
Log.verbose?.message("found \(deckName)")
}
var cards = [String: Int]()
for cardNode in doc.xpath("//table[contains(@class,'tabcartes')]//tbody//tr//a") {
if let qty = cardNode["nb_card"],
cardId = cardNode["real_id"],
count = Int(qty) {
cards[cardId] = count
}
}
if let playerClass = className,
cardClass = CardClass(rawValue: playerClass.uppercaseString)
where self.isCount(cards) {
self.saveDeck(deckName, playerClass: cardClass,
cards: cards, isArena: false, completion: completion)
return
}
}
completion(nil)
}
}
}
|
8cb2ce3a53aa76c36b311691fcebe5bf
| 32.140845 | 98 | 0.494263 | false | false | false | false |
jiayoufang/LearnSwift
|
refs/heads/master
|
SwiftTips.playground/Pages/GCD和延迟调用.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import Foundation
//创建目标队列
let workingQueue = DispatchQueue(label: "com.ivan.myqueue")
//派发到刚创建的队列中,GCD会负责线程调度
workingQueue.async {
//在workQueue中异步进行
print("Working....")
//模拟两秒的执行时间
Thread.sleep(forTimeInterval: 2)
print("Work finish")
DispatchQueue.main.async {
print("在主线程中更新UI")
}
}
typealias Task = (_ cancel: Bool) -> Void
func delay(_ time: TimeInterval,task: @escaping () -> ()) -> Task? {
//这个时候就体会到@escaping的含义了
func dispatch_later(block: @escaping () -> ()){
let t = DispatchTime.now() + time
DispatchQueue.main.asyncAfter(deadline: t, execute: block)
}
var closure: (() -> Void)? = task
var result: Task?
let delayedClosure: Task = {
cancel in
if let internalClosure = closure {
if cancel == false {
DispatchQueue.main.async(execute: internalClosure)
}
}
closure = nil
result = nil
}
result = delayedClosure
return result
}
delay(2){
print("aa")
}
//: [Next](@next)
|
235fb3eefa8a15fe7e4db09c3008ebaa
| 18.875 | 68 | 0.575921 | false | false | false | false |
Headmast/openfights
|
refs/heads/master
|
MoneyHelper/Models/Entity/RateEntity.swift
|
apache-2.0
|
1
|
//
// OrderEntity.swift
// MoneyHelper
//
// Created by Kirill Klebanov on 17/09/2017.
// Copyright © 2017 Surf. All rights reserved.
//
import Foundation
import ObjectMapper
public class RateEntity: Mappable {
// MARK: - Nested
// "startDate": "17.09.2017 10:36",
// "operationType": "B",
// "rateValue": "60.01",
// "curCharCode": "USD",
// "curUnitValue": "1",
// "minLimit": "10",
// "department": "018"
private struct Keys {
public static let startDate = "startDate"
public static let operationType = "operationType"
public static let rateValue = "rateValue"
public static let curCharCode = "curCharCode"
public static let curUnitValue = "curUnitValue"
public static let minLimit = "minLimit"
public static let department = "department"
}
// MARK: - Properties
public var startDate: String?
public var operationType: String?
public var rateValue: String?
public var curCharCode: String?
public var curUnitValue: String?
public var minLimit: String?
public var department: String?
public required convenience init?(map: Map) {
self.init()
}
public func mapping(map: Map) {
self.startDate <- map[Keys.startDate]
self.operationType <- map[Keys.operationType]
self.rateValue <- map[Keys.rateValue]
self.curCharCode <- map[Keys.curCharCode]
self.curUnitValue <- map[Keys.curUnitValue]
self.minLimit <- map[Keys.minLimit]
self.department <- map[Keys.department]
}
}
|
48104f7cf420d712a34c4066a76cee02
| 27.178571 | 57 | 0.639417 | false | false | false | false |
fitpay/fitpay-ios-sdk
|
refs/heads/develop
|
FitpaySDK/Notifications/FitpayNotificationsManager.swift
|
mit
|
1
|
import Foundation
open class FitpayNotificationsManager: NSObject, ClientModel {
public static let sharedInstance = FitpayNotificationsManager()
public typealias NotificationsPayload = [AnyHashable: Any]
/// NotificationsEventBlockHandler
///
/// - parameter event: Provides event with payload in eventData property
public typealias NotificationsEventBlockHandler = (_ event: FitpayEvent) -> Void
var notificationToken: String = ""
var client: RestClient?
private let eventsDispatcher = FitpayEventDispatcher()
private var syncCompletedBinding: FitpayEventBinding?
private var syncFailedBinding: FitpayEventBinding?
private var notificationsQueue = [NotificationsPayload]()
private var currentNotification: NotificationsPayload?
private var noActivityTimer: Timer?
// MARK: - Public Functions
public func setRestClient(_ client: RestClient?) {
self.client = client
}
/**
Handle notification from Fitpay platform. It may call syncing process and other stuff.
When all notifications processed we should receive AllNotificationsProcessed event. In completion
(or in other place where handling of hotification completed) to this event
you should call fetchCompletionHandler if this function was called from background.
- parameter payload: payload of notification
*/
open func handleNotification(_ payload: NotificationsPayload) {
log.verbose("NOTIFICATIONS_DATA: handling notification")
let notificationDetail = self.notificationDetailFromNotification(payload)
if (notificationDetail?.type?.lowercased() == "sync") {
notificationDetail?.sendAckSync()
}
notificationsQueue.enqueue(payload)
processNextNotificationIfAvailable()
}
/**
Saves notification token after next sync process.
- parameter token: notifications token which should be provided by Firebase
*/
open func updateNotificationsToken(_ token: String) {
notificationToken = token
}
/**
Binds to the event using NotificationsEventType and a block as callback.
- parameter eventType: type of event which you want to bind to
- parameter completion: completion handler which will be called
*/
open func bindToEvent(eventType: NotificationsEventType, completion: @escaping NotificationsEventBlockHandler) -> FitpayEventBinding? {
return eventsDispatcher.addListenerToEvent(FitpayBlockEventListener(completion: completion), eventId: eventType)
}
/**
Binds to the event using NotificationsEventType and a block as callback.
- parameter eventType: type of event which you want to bind to
- parameter completion: completion handler which will be called
- parameter queue: queue in which completion will be called
*/
open func bindToEvent(eventType: NotificationsEventType, completion: @escaping NotificationsEventBlockHandler, queue: DispatchQueue) -> FitpayEventBinding? {
return eventsDispatcher.addListenerToEvent(FitpayBlockEventListener(completion: completion, queue: queue), eventId: eventType)
}
/// Removes bind.
open func removeSyncBinding(binding: FitpayEventBinding) {
eventsDispatcher.removeBinding(binding)
}
/// Removes all synchronization bindings.
open func removeAllSyncBindings() {
eventsDispatcher.removeAllBindings()
}
open func updateRestClientForNotificationDetail(_ notificationDetail: NotificationDetail?) {
if let notificationDetail = notificationDetail, notificationDetail.client == nil {
notificationDetail.client = self.client
}
}
/// Creates a notification detail from both old and new notification types
public func notificationDetailFromNotification(_ notification: NotificationsPayload?) -> NotificationDetail? {
var notificationDetail: NotificationDetail?
if let fpField2 = notification?["fpField2"] as? String {
notificationDetail = try? NotificationDetail(fpField2)
} else if notification?["source"] as? String == "FitPay" {
notificationDetail = try? NotificationDetail(notification?["payload"])
notificationDetail?.type = notification?["type"] as? String
}
notificationDetail?.client = self.client
return notificationDetail
}
// MARK: - Private Functions
private func processNextNotificationIfAvailable() {
log.verbose("NOTIFICATIONS_DATA: Processing next notification if available.")
guard currentNotification == nil else {
log.verbose("NOTIFICATIONS_DATA: currentNotification was not nil returning.")
return
}
if notificationsQueue.peekAtQueue() == nil {
log.verbose("NOTIFICATIONS_DATA: peeked at queue and found nothing.")
callAllNotificationProcessedCompletion()
return
}
self.currentNotification = notificationsQueue.dequeue()
guard let currentNotification = self.currentNotification else { return }
var notificationType = NotificationType.withoutSync
if (currentNotification["fpField1"] as? String)?.lowercased() == "sync" || (currentNotification["type"] as? String)?.lowercased() == "sync" {
log.debug("NOTIFICATIONS_DATA: notification was of type sync.")
notificationType = NotificationType.withSync
}
callReceivedCompletion(currentNotification, notificationType: notificationType)
switch notificationType {
case .withSync:
let notificationDetail = notificationDetailFromNotification(currentNotification)
guard let userId = notificationDetail?.userId else {
log.error("NOTIFICATIONS_DATA: Recieved notification with no userId. Returning")
return
}
client?.user(id: userId) { (user: User?, err: ErrorResponse?) in
guard let user = user, err == nil else {
log.error("NOTIFICATIONS_DATA: Failed to retrieve user with ID \(userId). Continuing to next notification. Error: \(err!.description)")
self.currentNotification = nil
self.noActivityTimer?.invalidate()
self.processNextNotificationIfAvailable()
return
}
SyncRequestQueue.sharedInstance.add(request: SyncRequest(notification: notificationDetail, initiator: .notification, user: user)) { (_, _) in
self.currentNotification = nil
self.noActivityTimer?.invalidate()
self.noActivityTimer = nil
self.processNextNotificationIfAvailable()
}
}
noActivityTimer?.invalidate()
noActivityTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(FitpayNotificationsManager.handleNoActiviy), userInfo: nil, repeats: false)
case .withoutSync: // just call completion
log.debug("NOTIFICATIONS_DATA: notification was non-sync.")
self.currentNotification = nil
processNextNotificationIfAvailable()
}
}
private func callReceivedCompletion(_ payload: NotificationsPayload, notificationType: NotificationType) {
var eventType: NotificationsEventType
switch notificationType {
case .withSync:
eventType = .receivedSyncNotification
case .withoutSync:
eventType = .receivedSimpleNotification
}
eventsDispatcher.dispatchEvent(FitpayEvent(eventId: eventType, eventData: payload))
}
private func callAllNotificationProcessedCompletion() {
eventsDispatcher.dispatchEvent(FitpayEvent(eventId: NotificationsEventType.allNotificationsProcessed, eventData: [:]))
}
/// Clear current notification and process the next one if available if the current notification times out
@objc private func handleNoActiviy() {
log.verbose("NOTIFICATIONS_DATA: Notification Sync timed out. Sync Request Queue did not return in time, so we continue to the next notification.")
currentNotification = nil
processNextNotificationIfAvailable()
}
}
|
69119fb978ad05e96edcbcfea66e0021
| 42.085427 | 178 | 0.671565 | false | false | false | false |
gerardogrisolini/Webretail
|
refs/heads/master
|
Sources/Webretail/Models/Stock.swift
|
apache-2.0
|
1
|
//
// Stock.swift
// Webretail
//
// Created by Gerardo Grisolini on 27/02/17.
//
//
import StORM
class Stock: PostgresSqlORM, Codable {
public var stockId : Int = 0
public var storeId : Int = 0
public var articleId : Int = 0
public var stockQuantity : Double = 0
public var stockBooked : Double = 0
public var stockCreated : Int = Int.now()
public var stockUpdated : Int = Int.now()
open override func table() -> String { return "stocks" }
open override func to(_ this: StORMRow) {
stockId = this.data["stockid"] as? Int ?? 0
storeId = this.data["storeid"] as? Int ?? 0
articleId = this.data["articleid"] as? Int ?? 0
stockQuantity = Double(this.data["stockquantity"] as? Float ?? 0)
stockBooked = Double(this.data["stockbooked"] as? Float ?? 0)
stockCreated = this.data["stockcreated"] as? Int ?? 0
stockUpdated = this.data["stockupdated"] as? Int ?? 0
}
func rows() -> [Stock] {
var rows = [Stock]()
for i in 0..<self.results.rows.count {
let row = Stock()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
}
|
8e26949a8735f9ecccdbea6999345b1b
| 28.071429 | 73 | 0.576577 | false | false | false | false |
wondervictor/ReFilm
|
refs/heads/master
|
ReFilm/View/CommentCell.swift
|
mit
|
1
|
//
// CommentCell.swift
// ReFilm
//
// Created by VicChan on 5/28/16.
// Copyright © 2016 VicChan. All rights reserved.
//
import UIKit
public class CommentCell: UITableViewCell {
public var nameLabel: UILabel!
public var commentLabel: UILabel!
var width: CGFloat = 0.0
override public func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.configureSubViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configureSubViews() {
self.nameLabel = UILabel();
self.nameLabel.translatesAutoresizingMaskIntoConstraints = false;
self.contentView.addSubview(self.nameLabel)
let nameConstraintTop = NSLayoutConstraint(
item: self.nameLabel,
attribute:.Top,
relatedBy: .Equal,
toItem: self.contentView,
attribute: .Top,
multiplier: 1,
constant: 0)
nameConstraintTop.active = true
let nameConstraintLeft = NSLayoutConstraint(
item: self.nameLabel,
attribute:.Left,
relatedBy: .Equal,
toItem: self.contentView,
attribute: .Left,
multiplier: 1,
constant: 15)
nameConstraintLeft.active = true
let nameConstraintRight = NSLayoutConstraint(
item: self.nameLabel,
attribute:.Right,
relatedBy: .Equal,
toItem: self.contentView,
attribute: .Right,
multiplier: 1,
constant: -15)
nameConstraintRight.active = true
let nameConstraintHeight = NSLayoutConstraint(
item: self.nameLabel,
attribute:.Height,
relatedBy: .Equal,
toItem: self.contentView,
attribute: .Height,
multiplier: 0,
constant: 20)
nameConstraintHeight.active = true
self.nameLabel.textColor = UIColor.orangeColor()
self.nameLabel.font = UIFont(name: "HelveticaNeue", size: 13)
self.commentLabel = UILabel()
self.commentLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(self.commentLabel)
let commentTop = NSLayoutConstraint(
item: self.commentLabel,
attribute:.Top,
relatedBy: .Equal,
toItem: self.nameLabel,
attribute: .Bottom,
multiplier: 1,
constant: 0)
commentTop.active = true
let commentLeft = NSLayoutConstraint(
item: self.commentLabel,
attribute:.Left,
relatedBy: .Equal,
toItem: self.contentView,
attribute: .Left,
multiplier: 1,
constant: 15)
commentLeft.active = true
let commentRight = NSLayoutConstraint(
item: self.commentLabel,
attribute:.Right,
relatedBy: .Equal,
toItem: self.contentView,
attribute: .Right,
multiplier: 1,
constant: -15)
commentRight.active = true
let commentBottom = NSLayoutConstraint(
item: self.commentLabel,
attribute:.Bottom,
relatedBy: .Equal,
toItem: self.contentView,
attribute: .Bottom,
multiplier: 1,
constant: 0)
commentBottom.active = true
self.commentLabel.textColor = UIColor.blackColor()
self.commentLabel.font = UIFont(name: "HelveticaNeue", size: 13)
self.commentLabel.numberOfLines = 0
/*
CAShapeLayer *lineLayer = [CAShapeLayer layer];
lineLayer.strokeColor = [UIColor greenColor].CGColor;
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 20);
CGPathAddLineToPoint(path, NULL, MAIN_WIDTH-30, 20);
lineLayer.path = path;
CGPathRelease(path);
[titleLabel.layer addSublayer:lineLayer];
*/
}
override public func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
a5f911ae26b23f25a5be38d90fafc37e
| 28.79085 | 75 | 0.5724 | false | false | false | false |
horizon-institute/babyface-ios
|
refs/heads/master
|
src/AppDelegate.swift
|
gpl-3.0
|
1
|
//
// AppDelegate.swift
// babyface
//
// Created by Kevin Glover on 27/03/2015.
// Copyright (c) 2015 Horizon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
let navigationController = UINavigationController()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
UIApplication.sharedApplication().statusBarStyle = .Default
navigationController.navigationBar.translucent = true
navigationController.setNavigationBarHidden(true, animated: false)
navigationController.setToolbarHidden(true, animated: false)
navigationController.toolbar.translucent = true
navigationController.pushViewController(WelcomeViewController(), animated: false)
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let window = window
{
window.backgroundColor = UIColor.whiteColor()
window.rootViewController = navigationController
window.makeKeyAndVisible()
window.layoutIfNeeded()
}
return true
}
func applicationWillResignActive(application: UIApplication)
{
}
func applicationDidEnterBackground(application: UIApplication)
{
}
func applicationWillEnterForeground(application: UIApplication)
{
}
func applicationDidBecomeActive(application: UIApplication)
{
}
func applicationWillTerminate(application: UIApplication)
{
}
}
|
2154310e55684ce9979de7197858afd8
| 23.810345 | 122 | 0.784423 | false | false | false | false |
flodolo/firefox-ios
|
refs/heads/main
|
Client/Frontend/Browser/QRCodeViewController.swift
|
mpl-2.0
|
2
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import AVFoundation
import Shared
protocol QRCodeViewControllerDelegate: AnyObject {
func didScanQRCodeWithURL(_ url: URL)
func didScanQRCodeWithText(_ text: String)
}
class QRCodeViewController: UIViewController {
private struct UX {
static let navigationBarBackgroundColor = UIColor.black
static let navigationBarTitleColor = UIColor.Photon.White100
static let maskViewBackgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
static let isLightingNavigationItemColor = UIColor(red: 0.45, green: 0.67, blue: 0.84, alpha: 1)
static let viewBackgroundDeniedColor = UIColor.black
static let scanLineHeight: CGFloat = 6
}
var qrCodeDelegate: QRCodeViewControllerDelegate?
fileprivate lazy var captureSession: AVCaptureSession = {
let session = AVCaptureSession()
session.sessionPreset = AVCaptureSession.Preset.high
return session
}()
private lazy var captureDevice: AVCaptureDevice? = {
return AVCaptureDevice.default(for: AVMediaType.video)
}()
private var videoPreviewLayer: AVCaptureVideoPreviewLayer?
private let scanLine: UIImageView = .build { imageView in
imageView.image = UIImage(named: ImageIdentifiers.qrCodeScanLine)
}
private let scanBorder: UIImageView = .build { imageView in
imageView.image = UIImage(named: ImageIdentifiers.qrCodeScanBorder)
}
private lazy var instructionsLabel: UILabel = .build { label in
label.text = .ScanQRCodeInstructionsLabel
label.textColor = UIColor.Photon.White100
label.textAlignment = .center
label.numberOfLines = 0
}
private var maskView: UIView = .build { view in
view.backgroundColor = UX.maskViewBackgroundColor
}
private var isAnimationing: Bool = false
private var isLightOn: Bool = false
private var shapeLayer = CAShapeLayer()
private var scanLineTopConstraint: NSLayoutConstraint!
private var scanBorderWidthConstraint: NSLayoutConstraint!
private var scanBorderSize: CGFloat {
let minSize = min(view.frame.width, view.frame.height)
var scanBorderSize = minSize / 3 * 2
if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.orientation.isLandscape {
scanBorderSize = minSize / 2
}
return scanBorderSize
}
override func viewDidLoad() {
super.viewDidLoad()
guard let captureDevice = self.captureDevice else {
dismiss(animated: false)
return
}
self.navigationItem.title = .ScanQRCodeViewTitle
// Setup the NavigationBar
self.navigationController?.navigationBar.barTintColor = UX.navigationBarBackgroundColor
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UX.navigationBarTitleColor]
// Setup the NavigationItem
self.navigationItem.leftBarButtonItem = UIBarButtonItem(
image: UIImage(named: ImageIdentifiers.qrCodeGoBack)?.imageFlippedForRightToLeftLayoutDirection(),
style: .plain,
target: self,
action: #selector(goBack))
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.Photon.White100
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
image: UIImage(named: ImageIdentifiers.qrCodeLight),
style: .plain,
target: self,
action: #selector(openLight))
if captureDevice.hasTorch {
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.Photon.White100
} else {
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.Photon.Grey50
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
let getAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if getAuthorizationStatus != .denied {
setupCamera()
} else {
view.backgroundColor = UX.viewBackgroundDeniedColor
self.navigationItem.rightBarButtonItem?.isEnabled = false
let alert = UIAlertController(title: "", message: .ScanQRCodePermissionErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: .ScanQRCodeErrorOKButton,
style: .default,
handler: { (action) -> Void in
self.dismiss(animated: true)
}))
self.present(alert, animated: true, completion: nil)
}
setupVideoPreviewLayer()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupConstraints()
isAnimationing = true
startScanLineAnimation()
applyShapeLayer()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.captureSession.stopRunning()
stopScanLineAnimation()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
applyShapeLayer()
}
private func applyShapeLayer() {
view.layoutIfNeeded()
shapeLayer.removeFromSuperlayer()
let rectPath = UIBezierPath(rect: view.bounds)
rectPath.append(UIBezierPath(rect: scanBorder.frame).reversing())
shapeLayer.path = rectPath.cgPath
maskView.layer.mask = shapeLayer
}
private func setupConstraints() {
view.addSubview(maskView)
view.addSubview(scanBorder)
view.addSubview(scanLine)
view.addSubview(instructionsLabel)
scanLineTopConstraint = scanLine.topAnchor.constraint(equalTo: scanBorder.topAnchor,
constant: UX.scanLineHeight)
scanBorderWidthConstraint = scanBorder.widthAnchor.constraint(equalToConstant: scanBorderSize)
NSLayoutConstraint.activate([
maskView.topAnchor.constraint(equalTo: view.topAnchor),
maskView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
maskView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
maskView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
scanBorder.centerXAnchor.constraint(equalTo: view.centerXAnchor),
scanBorder.centerYAnchor.constraint(equalTo: view.centerYAnchor),
scanBorderWidthConstraint,
scanBorder.heightAnchor.constraint(equalTo: scanBorder.widthAnchor),
scanLineTopConstraint,
scanLine.leadingAnchor.constraint(equalTo: scanBorder.leadingAnchor),
scanLine.widthAnchor.constraint(equalTo: scanBorder.widthAnchor),
scanLine.heightAnchor.constraint(equalToConstant: UX.scanLineHeight),
instructionsLabel.topAnchor.constraint(equalTo: scanBorder.bottomAnchor, constant: 30),
instructionsLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
instructionsLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
])
}
private func updateContraintsAfterTransition() {
scanBorderWidthConstraint.constant = scanBorderSize
}
private func setupVideoPreviewLayer() {
guard let videoPreviewLayer = self.videoPreviewLayer else { return }
videoPreviewLayer.frame = UIScreen.main.bounds
switch UIDevice.current.orientation {
case .portrait:
videoPreviewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
case .landscapeLeft:
videoPreviewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.landscapeRight
case .landscapeRight:
videoPreviewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.landscapeLeft
case .portraitUpsideDown:
videoPreviewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown
default:
videoPreviewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
}
}
@objc func startScanLineAnimation() {
if !isAnimationing {
return
}
view.layoutIfNeeded()
view.setNeedsLayout()
UIView.animate(withDuration: 2.4,
delay: 0,
options: [.repeat],
animations: {
self.scanLineTopConstraint.constant = self.scanBorder.frame.size.height - UX.scanLineHeight
self.view.layoutIfNeeded()
}) { (value: Bool) in
self.scanLineTopConstraint.constant = UX.scanLineHeight
self.perform(#selector(self.startScanLineAnimation), with: nil, afterDelay: 0)
}
}
func stopScanLineAnimation() {
isAnimationing = false
}
@objc func goBack() {
self.dismiss(animated: true, completion: nil)
}
@objc func openLight() {
guard let captureDevice = self.captureDevice else { return }
if isLightOn {
do {
try captureDevice.lockForConfiguration()
captureDevice.torchMode = AVCaptureDevice.TorchMode.off
captureDevice.unlockForConfiguration()
navigationItem.rightBarButtonItem?.image = UIImage(named: ImageIdentifiers.qrCodeLight)
navigationItem.rightBarButtonItem?.tintColor = UIColor.Photon.White100
} catch {
print(error)
}
} else {
do {
try captureDevice.lockForConfiguration()
captureDevice.torchMode = AVCaptureDevice.TorchMode.on
captureDevice.unlockForConfiguration()
navigationItem.rightBarButtonItem?.image = UIImage(named: ImageIdentifiers.qrCodeLightTurnedOn)
navigationItem.rightBarButtonItem?.tintColor = UX.isLightingNavigationItemColor
} catch {
print(error)
}
}
isLightOn = !isLightOn
}
func setupCamera() {
guard let captureDevice = self.captureDevice else {
dismiss(animated: false)
return
}
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(input)
} catch {
print(error)
}
let output = AVCaptureMetadataOutput()
if captureSession.canAddOutput(output) {
captureSession.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
}
let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer.frame = UIScreen.main.bounds
view.layer.addSublayer(videoPreviewLayer)
self.videoPreviewLayer = videoPreviewLayer
captureSession.startRunning()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.updateContraintsAfterTransition()
self.setupVideoPreviewLayer()
}, completion: nil)
}
}
extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection) {
if metadataObjects.isEmpty {
self.captureSession.stopRunning()
let alert = AlertController(title: "", message: .ScanQRCodeInvalidDataErrorMessage, preferredStyle: .alert)
alert.addAction(
UIAlertAction(title: .ScanQRCodeErrorOKButton,
style: .default,
handler: { (UIAlertAction) in
self.captureSession.startRunning()
}),
accessibilityIdentifier: AccessibilityIdentifiers.Settings.FirefoxAccount.qrScanFailedAlertOkButton)
self.present(alert, animated: true, completion: nil)
} else {
self.captureSession.stopRunning()
stopScanLineAnimation()
self.dismiss(animated: true, completion: {
guard let metaData = metadataObjects.first as? AVMetadataMachineReadableCodeObject,
let qrCodeDelegate = self.qrCodeDelegate,
let text = metaData.stringValue
else {
SentryIntegration.shared.sendWithStacktrace(
message: "Unable to scan QR code",
tag: .general)
return
}
if let url = URIFixup.getURL(text) {
qrCodeDelegate.didScanQRCodeWithURL(url)
} else {
qrCodeDelegate.didScanQRCodeWithText(text)
}
})
}
}
}
class QRCodeNavigationController: UINavigationController {
override open var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
|
b10ba41023a4544ec7e90736731926c0
| 38.926901 | 139 | 0.653094 | false | false | false | false |
ben-ng/swift
|
refs/heads/master
|
stdlib/public/core/StringComparable.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
/// Compare two strings using the Unicode collation algorithm in the
/// deterministic comparison mode. (The strings which are equivalent according
/// to their NFD form are considered equal. Strings which are equivalent
/// according to the plain Unicode collation algorithm are additionally ordered
/// based on their NFD.)
///
/// See Unicode Technical Standard #10.
///
/// The behavior is equivalent to `NSString.compare()` with default options.
///
/// - returns:
/// * an unspecified value less than zero if `lhs < rhs`,
/// * zero if `lhs == rhs`,
/// * an unspecified value greater than zero if `lhs > rhs`.
@_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollation")
public func _stdlib_compareNSStringDeterministicUnicodeCollation(
_ lhs: AnyObject, _ rhs: AnyObject
) -> Int32
@_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollationPtr")
public func _stdlib_compareNSStringDeterministicUnicodeCollationPointer(
_ lhs: OpaquePointer, _ rhs: OpaquePointer
) -> Int32
#endif
extension String {
#if _runtime(_ObjC)
/// This is consistent with Foundation, but incorrect as defined by Unicode.
/// Unicode weights some ASCII punctuation in a different order than ASCII
/// value. Such as:
///
/// 0022 ; [*02FF.0020.0002] # QUOTATION MARK
/// 0023 ; [*038B.0020.0002] # NUMBER SIGN
/// 0025 ; [*038C.0020.0002] # PERCENT SIGN
/// 0026 ; [*0389.0020.0002] # AMPERSAND
/// 0027 ; [*02F8.0020.0002] # APOSTROPHE
///
/// - Precondition: Both `self` and `rhs` are ASCII strings.
public // @testable
func _compareASCII(_ rhs: String) -> Int {
var compare = Int(_swift_stdlib_memcmp(
self._core.startASCII, rhs._core.startASCII,
min(self._core.count, rhs._core.count)))
if compare == 0 {
compare = self._core.count - rhs._core.count
}
// This efficiently normalizes the result to -1, 0, or 1 to match the
// behavior of NSString's compare function.
return (compare > 0 ? 1 : 0) - (compare < 0 ? 1 : 0)
}
#endif
/// Compares two strings with the Unicode Collation Algorithm.
@inline(never)
@_semantics("stdlib_binary_only") // Hide the CF/ICU dependency
public // @testable
func _compareDeterministicUnicodeCollation(_ rhs: String) -> Int {
// Note: this operation should be consistent with equality comparison of
// Character.
#if _runtime(_ObjC)
if self._core.hasContiguousStorage && rhs._core.hasContiguousStorage {
let lhsStr = _NSContiguousString(self._core)
let rhsStr = _NSContiguousString(rhs._core)
let res = lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) {
return Int(
_stdlib_compareNSStringDeterministicUnicodeCollationPointer($0, $1))
}
return res
}
return Int(_stdlib_compareNSStringDeterministicUnicodeCollation(
_bridgeToObjectiveCImpl(), rhs._bridgeToObjectiveCImpl()))
#else
switch (_core.isASCII, rhs._core.isASCII) {
case (true, false):
return Int(_swift_stdlib_unicode_compare_utf8_utf16(
_core.startASCII, Int32(_core.count),
rhs._core.startUTF16, Int32(rhs._core.count)))
case (false, true):
// Just invert it and recurse for this case.
return -rhs._compareDeterministicUnicodeCollation(self)
case (false, false):
return Int(_swift_stdlib_unicode_compare_utf16_utf16(
_core.startUTF16, Int32(_core.count),
rhs._core.startUTF16, Int32(rhs._core.count)))
case (true, true):
return Int(_swift_stdlib_unicode_compare_utf8_utf8(
_core.startASCII, Int32(_core.count),
rhs._core.startASCII, Int32(rhs._core.count)))
}
#endif
}
public // @testable
func _compareString(_ rhs: String) -> Int {
#if _runtime(_ObjC)
// We only want to perform this optimization on objc runtimes. Elsewhere,
// we will make it follow the unicode collation algorithm even for ASCII.
// This is consistent with Foundation, but incorrect as defined by Unicode.
if _core.isASCII && rhs._core.isASCII {
return _compareASCII(rhs)
}
#endif
return _compareDeterministicUnicodeCollation(rhs)
}
}
extension String : Equatable {
public static func == (lhs: String, rhs: String) -> Bool {
#if _runtime(_ObjC)
// We only want to perform this optimization on objc runtimes. Elsewhere,
// we will make it follow the unicode collation algorithm even for ASCII.
// This is consistent with Foundation, but incorrect as defined by Unicode.
if lhs._core.isASCII && rhs._core.isASCII {
if lhs._core.count != rhs._core.count {
return false
}
return _swift_stdlib_memcmp(
lhs._core.startASCII, rhs._core.startASCII,
rhs._core.count) == 0
}
#endif
return lhs._compareString(rhs) == 0
}
}
extension String : Comparable {
public static func < (lhs: String, rhs: String) -> Bool {
return lhs._compareString(rhs) < 0
}
}
|
e2c6b5086275e24f60fe96056a552775
| 36.616438 | 80 | 0.662418 | false | false | false | false |
hulinSun/MyRx
|
refs/heads/master
|
MyRx/MyRx/Classes/Core/Service/MatchService.swift
|
mit
|
1
|
//
// MatchService.swift
// MyRx
//
// Created by Hony on 2016/12/29.
// Copyright © 2016年 Hony. All rights reserved.
//
import UIKit
import Moya
/**
虽然是HTTPS.这里火柴盒的接口信息可以抓取到,参数也可以拿到,但是无奈无奈走了头校验,调不了接口.只能做本地json 读取了。但是这里 假装 调接口 。熟悉一下 moya = =
参数是这样的
{
"lastid": "0",
"source": "APP",
"uid": "1248932",
"register_id": "",
"platform": "IOS",
"udid": "e0164119fcedd620533b1a6a163454b13b4be0e9",
"user_id": "1248932",
"version": "4.9.0",
"token_key": "MTI0ODkzMizmiafov7dfLCw2ZGFmMzs5YWMwNmU0OWM0OWY5MTgzNjc0MGVlZTA5Njk5ZDBhYg=="
}
https://soa.ihuochaihe.com:442/v1/thread/momentsad // 主页 好友界面接口
https://soa.ihuochaihe.com:442/v1/thread/likemomentsad 主页 欢喜界面接口
https:soa.ihuochaihe.com:442/fei/index/index // 柴扉
你会发现未授权 = =
*/
/// 主页火柴service
enum MatchService: String {
case momentsad //好友界面
case likemomentsad //欢喜界面
case chaifei // 柴扉
}
extension MatchService: TargetType {
var baseURL: URL { return URL(string:"https://soa.ihuochaihe.com:442")! }
var path: String {
switch self {
case .momentsad:
return "/v1/thread/momentsad"
case .likemomentsad:
return "/v1/thread/likemomentsad"
case .chaifei:
return "/fei/index/index"
}
}
var method: Moya.Method {
switch self {
case .momentsad, .likemomentsad , .chaifei:
return .post
}
}
var parameters: [String: Any]? {
return nil
}
/// 模拟假数据用
var sampleData: Data {
return JSONTool.dataWith(name: self.rawValue)
}
var task: Task {
return .request
}
}
// MARK: - Helpers
private extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
var utf8Encoded: Data {
return self.data(using: .utf8)!
}
}
|
18007ef1cad73eb8529cc6ffb084d82f
| 19.231579 | 92 | 0.609781 | false | false | false | false |
weijingyunIOS/JYMultiLevelView
|
refs/heads/master
|
JYMultiLevel_RAC/JYMultiLevel_RAC/UtilityClass/OptionalReturn.swift
|
mit
|
1
|
//
// JYOptionalReturn.swift
// MultiLevel
//
// Created by weijingyun on 16/11/26.
// Copyright © 2016年 weijingyun. All rights reserved.
//
import Foundation
public struct NilError: Error, CustomStringConvertible {
public var description: String { return _description }
public init(error:String, file: String, line: Int) {
_description = error
#if DEBUG
_description = _description + " DEBUG --- Nil returned at "
+ (file as NSString).lastPathComponent + ":\(line)"
#endif
}
private var _description: String
}
extension Optional {
public func unwrap(_ error:String = "", file: String = #file, line: Int = #line) throws -> Wrapped {
guard let unwrapped = self else { throw NilError(error:error, file: file, line: line) }
return unwrapped
}
}
|
f9a0da6739945b2a7da4fe794949950f
| 26.774194 | 104 | 0.62137 | false | false | false | false |
HarrisHan/Snapseed
|
refs/heads/master
|
Snapseed/Snapseed/SnapPanGestureRecognizer.swift
|
mit
|
1
|
//
// SnapPanGestureRecognizer.swift
// Snapseed
//
// Created by harris on 08/02/2017.
// Copyright © 2017 harris. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
enum snapPanGestureRecognizerDirection {
case snapPanGestureRecognizerDirectionVertical
case snapPanGestureRecognizerDirectionHorizental
}
class SnapPanGestureRecognizer: UIPanGestureRecognizer {
var direction:snapPanGestureRecognizerDirection?
var moveX:CGFloat = 0.0
var moveY:CGFloat = 0.0
var drag:Bool = false
static let kDirectionPanThreshold:Float = 5.0
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if state == .failed { return }
let nowPoint = touches.first?.location(in: self.view)
let prePoint = touches.first?.previousLocation(in: self.view)
moveX += (prePoint?.x)! - (nowPoint?.x)!
moveY += (prePoint?.y)! - (nowPoint?.y)!
if !drag {
if fabsf(Float(moveX)) > SnapPanGestureRecognizer.kDirectionPanThreshold {
if direction! == .snapPanGestureRecognizerDirectionVertical {
self.state = .failed
} else {
drag = true
}
} else if fabsf(Float(moveY)) > SnapPanGestureRecognizer.kDirectionPanThreshold {
if direction! == .snapPanGestureRecognizerDirectionHorizental {
self.state = .failed
} else {
drag = true
}
}
}
}
override func reset() {
super.reset()
drag = false
moveX = 0
moveY = 0
}
}
|
076be8ecb93f2f3712b3db3ce07d442c
| 27.709677 | 93 | 0.589326 | false | false | false | false |
puyanLiu/LPYFramework
|
refs/heads/master
|
第三方框架改造/YHAlertView/YHAlertView/QQMAlertHelp.swift
|
apache-2.0
|
1
|
//
// QQMAlertHelp.swift
// YHAlertView
//
// Created by liupuyan on 2017/6/27.
// Copyright © 2017年 samuelandkevin. All rights reserved.
//
import UIKit
class QQMAlertHelp: NSObject {
/// 知道了按钮
///
/// - Parameter message: <#message description#>
class func showAlertKnow(message: String) {
showAlert(title: nil, message: message, buttonText: "知道了", action: nil)
}
/// 单个按钮
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText: <#buttonText description#>
/// - action: <#action description#>
class func showAlert(title: String?, message: String?, buttonText: String, action: OperationBlock?) {
let alertV = QQMAlertView(title: title, message: message, buttonTitle1: buttonText, style1: .confirm, action1: action, buttonTitle2: nil, style2: nil, action2: nil)
alertV.show()
}
/// 两个按钮
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText1: <#buttonText1 description#>
/// - action1: <#action1 description#>
/// - buttonText2: <#buttonText2 description#>
/// - action2: <#action2 description#>
class func showAlert(title: String?, message: String?, buttonText1: String, action1: OperationBlock?, buttonText2: String, action2: OperationBlock?) {
let alertV = QQMAlertView(title: title, message: message, buttonTitle1: buttonText1, style1: .cancel, action1: action1, buttonTitle2: buttonText2, style2: .confirm, action2: action2)
alertV.show()
}
/// 单个按钮 html
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText: <#buttonText description#>
/// - action: <#action description#>
class func showAlert(title: String?, messageHtml: String?, buttonText: String, action: OperationBlock?) {
let alertV = QQMAlertView(title: title, messageHtml: messageHtml, buttonTitle1: buttonText, style1: .confirm, action1: action, buttonTitle2: nil, style2: nil, action2: nil)
alertV.show()
}
/// 两个按钮 html
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText1: <#buttonText1 description#>
/// - action1: <#action1 description#>
/// - buttonText2: <#buttonText2 description#>
/// - action2: <#action2 description#>
class func showAlert(title: String?, messageHtml: String?, buttonText1: String, action1: OperationBlock?, buttonText2: String, action2: OperationBlock?) {
let alertV = QQMAlertView(title: title, messageHtml: messageHtml, buttonTitle1: buttonText1, style1: .cancel, action1: action1, buttonTitle2: buttonText2, style2: .confirm, action2: action2)
alertV.show()
}
/// 两个按钮
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText1: <#buttonText1 description#>
/// - action1: <#action1 description#>
/// - buttonText2: <#buttonText2 description#>
/// - action2: <#action2 description#>
class func showAlert(title: String?, message: String?, messageTextAlignment: NSTextAlignment, buttonText1: String, action1: OperationBlock?, buttonText2: String, action2: OperationBlock?) {
let alertV = QQMAlertView(title: title, message: message, messageTextAlignment: messageTextAlignment, buttonTitle1: buttonText1, style1: .cancel, action1: action1, buttonTitle2: buttonText2, style2: .confirm, action2: action2)
alertV.show()
}
/// 单个按钮 富文本
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText1: <#buttonText1 description#>
/// - action1: <#action1 description#>
/// - buttonText2: <#buttonText2 description#>
/// - action2: <#action2 description#>
class func showAlert(title: String?, messageAttributedString: NSAttributedString, buttonText: String, action: OperationBlock?) {
let alertV = QQMAlertView(title: title, messageAttributedString: messageAttributedString, buttonTitle1: buttonText, style1: .confirm, action1: action, buttonTitle2: nil, style2: nil, action2: nil)
alertV.show()
}
/// 两个按钮 富文本
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText1: <#buttonText1 description#>
/// - action1: <#action1 description#>
/// - buttonText2: <#buttonText2 description#>
/// - action2: <#action2 description#>
class func showAlert(title: String?, messageAttributedString: NSAttributedString, buttonText1: String, action1: OperationBlock?, buttonText2: String, action2: OperationBlock?) {
let alertV = QQMAlertView(title: title, messageAttributedString: messageAttributedString, buttonTitle1: buttonText1, style1: .cancel, action1: action1, buttonTitle2: buttonText2, style2: .confirm, action2: action2)
alertV.show()
}
/// 两个按钮 富文本
///
/// - Parameters:
/// - title: <#title description#>
/// - message: <#message description#>
/// - buttonText1: <#buttonText1 description#>
/// - action1: <#action1 description#>
/// - buttonText2: <#buttonText2 description#>
/// - action2: <#action2 description#>
class func getAlert(title: String?, messageAttributedString: NSAttributedString, buttonText1: String, action1: OperationBlock?, buttonText2: String, action2: OperationBlock?) -> QQMAlertView {
return QQMAlertView(title: title, messageAttributedString: messageAttributedString, buttonTitle1: buttonText1, style1: .cancel, action1: action1, buttonTitle2: buttonText2, style2: .confirm, action2: action2)
}
}
|
2c03ea7cc53b71c90df3ff10f3a999e9
| 46.039683 | 234 | 0.648726 | false | false | false | false |
KrishMunot/swift
|
refs/heads/master
|
test/decl/protocol/req/recursion.swift
|
apache-2.0
|
9
|
// RUN: %target-parse-verify-swift
protocol SomeProtocol {
associatedtype T
}
extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}}
// rdar://problem/20000145
public protocol P {
associatedtype T
}
public struct S<A: P where A.T == S<A>> {}
// rdar://problem/19840527
class X<T where T == X> { // expected-error{{same-type requirement makes generic parameter 'T' non-generic}}
var type: T { return self.dynamicType } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}}
}
protocol Y {
associatedtype Z = Z // expected-error{{type alias 'Z' circularly references itself}}
}
|
499409f7cceb572efe6de55060cc8b33
| 31.227273 | 136 | 0.699577 | false | false | false | false |
grandiere/box
|
refs/heads/master
|
box/View/GridMap/VGridMapRenderPin.swift
|
mit
|
1
|
import UIKit
import MapKit
class VGridMapRenderPin:MKAnnotationView
{
init(annotation:MGridMapAnnotation)
{
let reuseIdentifier:String = VGridMapRenderPin.reusableIdentifier
super.init(annotation:annotation, reuseIdentifier:reuseIdentifier)
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: public
func hover()
{
guard
let annotation:MGridMapAnnotation = self.annotation as? MGridMapAnnotation
else
{
return
}
let imageAnnotation:UIImage
if isSelected || isHighlighted
{
guard
let image:UIImage = annotation.algo?.annotationImageOn
else
{
return
}
imageAnnotation = image
}
else
{
guard
let image:UIImage = annotation.algo?.annotationImageOff
else
{
return
}
imageAnnotation = image
}
self.image = imageAnnotation
let offsetY:CGFloat = imageAnnotation.size.height / -2.0
centerOffset = CGPoint(x: 0, y:offsetY)
}
}
|
4dbcdc5bc597057daf6a379c1bb5240d
| 18.530864 | 86 | 0.462705 | false | false | false | false |
lnds/9d9l
|
refs/heads/master
|
desafio3/swift/Sources/ordenar_vector/main.swift
|
mit
|
1
|
import Foundation
let tamVector = 23
let posVector = 9
let tamPeriodo = 6
let nInsts = 6
let largoLinea = posVector + nInsts * tamVector * tamPeriodo + 1
let tamSalida = posVector + 1 + tamVector * tamPeriodo + 1
let tamVecEntradaBytes = nInsts * (tamVector * tamPeriodo)
let tamVecSalidaBytes = tamVector * tamPeriodo
let N : Int8 = 78 // letra N
let S : Int8 = 83 // letra S
let D : Int8 = 68 // letra D
let NL : Int8 = 10 // newline
let CERO : Int8 = 48 // caracter '0'
let SPACE : Int8 = 32
var ceroData = ArraySlice<Int8>(repeating: CERO, count: tamPeriodo)
func ordenarVector(_ buf: [Int8], _ trabajo : inout [Int8]) -> Int {
var p = posVector
var n = 0
let tope = largoLinea-1
while p < tope {
if buf[p..<p+tamPeriodo] == ceroData {
p += tamPeriodo
continue
}
var i = 0
var q = 0
while i < n && buf[p..<p+tamPeriodo].lexicographicallyPrecedes(trabajo[q..<q+tamPeriodo]) {
i += 1
q += tamPeriodo
}
if i < n && buf[p..<p+tamPeriodo] == trabajo[q..<q+tamPeriodo] {
p += tamPeriodo
continue
}
if i == n {
q = n * tamPeriodo
for k in 0..<tamPeriodo {
trabajo[q+k] = buf[p+k]
}
} else {
var j = tamVector-1
while j > i {
q = j * tamPeriodo
for k in 0..<tamPeriodo {
trabajo[q+k] = trabajo[q-tamPeriodo+k]
}
j -= 1
}
q = i * tamPeriodo
for j in 0..<tamPeriodo {
trabajo[q+j] = buf[p+j]
}
}
n += 1
p += tamPeriodo
}
return n
}
var trabajo = [Int8](repeating: CERO, count: tamVecEntradaBytes)
var result = [Int8](repeating: SPACE, count: tamSalida+1)
func procesarLinea(_ buf: [Int8], _ nl: Int) -> [Int8] {
if strlen(buf) != UInt(largoLinea) {
print("!!! Largo incorrecto en linea \(nl) \(largoLinea) != \(buf.count)")
return buf
} else {
for i in 0..<tamVecEntradaBytes {
trabajo[i] = CERO
}
for i in 0..<tamSalida {
result[i] = SPACE
}
let tam = ordenarVector(buf, &trabajo)
result[0..<posVector] = buf[0..<posVector]
if tam == 0 {
result[posVector] = N
} else if tam > tamVector {
result[posVector] = S
} else {
result[posVector] = D
for j in 0..<tam*tamPeriodo {
result[j+posVector+1] = trabajo[j]
}
}
result[tamSalida-1] = NL
result[tamSalida] = 0
return result
}
}
let args = ProcessInfo.processInfo.arguments
let argc = ProcessInfo.processInfo.arguments.count
if argc != 3 {
print("Uso: ordenar_vector archivo_entrada archivo_salida")
exit(-1)
} else {
let start = Date()
let entrada = args[1]
let salida = args[2]
let fentrada = fopen(entrada, "rt")
if fentrada == nil {
print("no pudo abrir archivo entrada: \(entrada)")
exit(-1)
}
let fsalida = fopen(salida, "wt")
if fsalida == nil {
print("no pudo abrir archivo salida: \(salida)")
exit(-1)
}
let BUFFER_SIZE : Int32 = 4096
var buf = Array<Int8>(repeating: 0, count: Int(BUFFER_SIZE))
var nl = 0 // numero de linea
while (fgets(&buf, BUFFER_SIZE, fentrada) != nil) {
let bufOut = procesarLinea(buf, nl)
fputs(bufOut, fsalida)
nl += 1
}
fclose(fentrada)
fclose(fsalida)
let end = Date()
let timeInterval = end.timeIntervalSince(start)
let secs = timeInterval.truncatingRemainder(dividingBy:3600.0)
print(String(format:"tiempo ocupado: %05.2f", secs))
}
|
03777da5889ca35a9959167829c22cb3
| 22.633094 | 93 | 0.622527 | false | false | false | false |
netguru/inbbbox-ios
|
refs/heads/develop
|
Inbbbox/Source Files/Providers/Core Data Providers/Shots/ManagedShotsProvider.swift
|
gpl-3.0
|
1
|
//
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
import PromiseKit
import CoreData
class ManagedShotsProvider {
var managedObjectContext = (UIApplication.shared.delegate as? AppDelegate)!.managedObjectContext
func provideMyLikedShots() -> Promise<[ShotType]?> {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: ManagedShot.entityName)
fetchRequest.predicate = NSPredicate(format: "liked == true")
return Promise<[ShotType]?> { fulfill, reject in
do {
if let managedShots = try managedObjectContext.fetch(fetchRequest) as? [ManagedShot] {
fulfill(managedShots.map { $0 as ShotType })
}
} catch {
reject(error)
}
}
}
func provideManagedLikedShots() -> Promise<[LikedShot]?> {
return Promise<[LikedShot]?> { fulfill, reject in
firstly {
provideMyLikedShots()
}.then { managedShots -> Void in
if let shots = managedShots{
return fulfill(shots.map { LikedShot(likeIdentifier: $0.identifier, createdAt: Date(), shot: $0) })
}
fulfill(nil)
}.catch(execute: reject)
}
}
func provideShotsForBucket(_ bucket: BucketType) -> Promise<[ShotType]?> {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: ManagedShot.entityName)
fetchRequest.predicate = NSPredicate(format: "ANY buckets.mngd_identifier == %@", bucket.identifier)
return Promise<[ShotType]?> { fulfill, reject in
do {
if let managedShots = try managedObjectContext.fetch(fetchRequest) as? [ManagedShot] {
fulfill(managedShots.map { $0 as ShotType })
}
} catch {
reject(error)
}
}
}
}
|
95d628e70ff9eea22fa63a1ed6e7cab3
| 33.75 | 119 | 0.584275 | false | false | false | false |
gmilos/swift
|
refs/heads/master
|
test/SILGen/objc_init_ref_delegation.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
extension Gizmo {
// CHECK-LABEL: sil hidden @_TFE24objc_init_ref_delegationCSo5Gizmoc
convenience init(int i: Int) {
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[ORIG_SELF:%[0-9]+]] : $Gizmo):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Gizmo }
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Gizmo
// CHECK: store [[ORIG_SELF]] to [init] [[SELFMUI]] : $*Gizmo
// SEMANTIC ARC TODO: Another case of needing a mutable borrow load.
// CHECK: [[SELF:%[0-9]+]] = load_borrow [[SELFMUI]] : $*Gizmo
// CHECK: [[INIT_DELEG:%[0-9]+]] = class_method [volatile] [[SELF]] : $Gizmo, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo! , $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: [[SELF_RET:%[0-9]+]] = apply [[INIT_DELEG]]([[I]], [[SELF]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: [[SELF4:%.*]] = load [copy] [[SELFMUI]]
// CHECK: destroy_value [[SELF_BOX:%[0-9]+]] : ${ var Gizmo }
// CHECK: return [[SELF4]] : $Gizmo
self.init(bellsOn:i)
}
}
|
b4affc326c17b4c2235f0bf9977a65f1
| 54.958333 | 225 | 0.578555 | false | false | false | false |
FirstPersonSF/FPKit
|
refs/heads/master
|
FPKit/FPKitTests/FPLazyImageViewSpec.swift
|
mit
|
1
|
//
// FPLazyImageViewSpec.swift
// FPKit
//
// Created by Fernando Toledo on 1/21/16.
// Copyright © 2016 First Person. All rights reserved.
//
import Foundation
import Quick
import Nimble
import FPKit
class FPLazyImageViewSpec: QuickSpec {
override func spec() {
describe("a lazy image view", closure: {
let validImageURL = NSURL(string: "http://assets.firstperson.is/img/global/1P_logo_redorange_meta.png")
let invalidImageURL = NSURL(string: "http://firstperson.is/")
let invalidServerURL = NSURL(string: "http://nonexistentimagedomain.com")
var lazyImage: FPLazyImageView!
context("when loading from a valid image URL", closure: {
beforeEach({
lazyImage = FPLazyImageView(imageURL: validImageURL!, placeholderImage: nil)
lazyImage.startDownload()
})
it("has no image", closure: {
expect(lazyImage.image).to(beNil())
})
it("starts downloading an image", closure: {
expect(lazyImage.downloading).to(beTrue())
})
it("finishes downloading the image", closure: {
expect(lazyImage.downloaded).toEventually(beTrue())
})
it("sets the downloaded image as the UIImage source", closure: {
expect(lazyImage.image).toEventuallyNot(beNil())
})
})
context("when loading from an invalid image URL", closure: {
beforeEach({
lazyImage = FPLazyImageView(imageURL: invalidImageURL!, placeholderImage: nil)
lazyImage.startDownload()
})
it("has no image", closure: {
expect(lazyImage.image).to(beNil())
})
it("starts downloading an image", closure: {
expect(lazyImage.downloading).to(beTrue())
})
it("never downloads an image", closure: {
waitUntil(timeout: 5, action: { done in
lazyImage.completionHandler = { imageView, result in
expect(result.isFailure).to(beTrue())
expect(lazyImage.downloading).to(beFalse())
expect(lazyImage.downloaded).to(beFalse())
expect(lazyImage.image).to(beNil())
done()
}
})
})
})
context("when loading from an invalid server URL", closure: {
beforeEach({
lazyImage = FPLazyImageView(imageURL: invalidServerURL!, placeholderImage: nil)
lazyImage.startDownload()
})
it("has no image", closure: {
expect(lazyImage.image).to(beNil())
})
it("starts downloading an image", closure: {
expect(lazyImage.downloading).to(beTrue())
})
it("never downloads an image", closure: {
waitUntil(timeout: 5, action: { done in
lazyImage.completionHandler = { imageView, result in
expect(result.isFailure).to(beTrue())
expect(lazyImage.downloading).to(beFalse())
expect(lazyImage.downloaded).to(beFalse())
expect(lazyImage.image).to(beNil())
done()
}
})
})
})
})
}
}
|
549754060edb4ae561cdd096889a9298
| 36.081081 | 115 | 0.446902 | false | false | false | false |
oacastefanita/PollsFramework
|
refs/heads/master
|
PollsFramework/Classes/PollsFactory.swift
|
mit
|
1
|
import CoreData
open class PollsFactory: NSObject {
/// Create a Dictionary from any given object that is a subclass of NSObject
///
/// - Parameter object: Object to be created into dictionary
/// - Returns: Dictionary resulted from object
open class func createDicFromObject(_ object: Any) -> [String:AnyObject]{
var parameters = [String : Any]()
for (name, type) in NSObject.getTypesOfProperties(in: classFromString((object as! NSObject).className).self as! NSObject.Type)!{
if let newObj = (object as? NSObject)?.value(forKey: name) as? NSManagedObject {
parameters[name] = PollsFactory.createDicFromObject(((object as! NSObject).value(forKey: name))!)
}
else if name.hasPrefix("kId") {
var entityName = name.replacingOccurrences(of:"kId", with:"")
if entityName.contains("_") {
entityName = entityName.components(separatedBy: "_").first!
}
if let valueEntity = (object as! NSObject).value(forKey: name) {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let predicate = NSPredicate(format: "id\(entityName) = '\(((object as! NSObject).value(forKey: name))!)'")
fetch.predicate = predicate
if let result = try? DATA_CONTROLLER.managedObjectContext.fetch(fetch), result.count > 0 {
var fieldName = name.replacingOccurrences(of:"kId", with:"")
if fieldName.contains("_") {
fieldName = fieldName.components(separatedBy: "_").last!
}
parameters[fieldName] = PollsFactory.createDicFromObject(result.first!)
}
}
}
else if let newObj = (object as! NSObject).value(forKey: name) as? NSSet{
if newObj.count > 0{
var array = [Any]()
for item in newObj.allObjects{
array.append(PollsFactory.createDicFromObject(item))
}
parameters[name] = array
}
} else {
if let value = (object as! NSObject).value(forKey: name){
if type is Bool || (type as! AnyObject).description.range(of:"Bool") != nil{
parameters[name] = (value as! Bool) ? true : false
continue
}
if value is String && value as! String == ""{
continue
}
if value is Int64 && value as! Int64 == 0{
continue
}
parameters[name] = (object as! NSObject).value(forKey: name)
}
}
}
return parameters as [String : AnyObject]
}
/// Populate object propertie from Dictionary
///
/// - Parameters:
/// - object: Object to be populated
/// - dict: Dictionary with new object data
open class func populateObject(_ object: Any, fromDict dict: [String : AnyObject]){
for (name, type) in NSObject.getTypesOfProperties(in: classFromString((object as! NSObject).className).self as! NSObject.Type)!{
if name.hasPrefix("kId") {
var entityName = name.replacingOccurrences(of:"kId", with:"")
if entityName.contains("_") {
entityName = entityName.components(separatedBy: "_").first!
}
var fieldName = name.replacingOccurrences(of:"kId", with:"")
if fieldName.contains("_") {
fieldName = fieldName.components(separatedBy: "_").last!
}
if let subDict = dict[fieldName] as? [String : AnyObject]{
var newEntity:NSManagedObject!
if let found = PollsFrameworkController.sharedInstance.dataController().updateEntity(entityName, idPropertyName:"id", dictionary: subDict) {
newEntity = found
}
else {
newEntity = NSEntityDescription.insertNewObject(forEntityName: "\(entityName)", into: POLLS_FRAMEWORK.dataController().managedObjectContext)
populateObject(newEntity, fromDict: subDict)
}
if let value = subDict["id"] as? String {
(newEntity as! NSObject).setValue(value, forKey: "id\(entityName)")
(object as! NSObject).setValue(value, forKey: name)
}
}
else if let entityValue = (object as! NSObject).value(forKey: name) {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let predicate = NSPredicate(format: "id\(entityName) = '\(entityValue)'")
fetch.predicate = predicate
if let result = try? DATA_CONTROLLER.managedObjectContext.fetch(fetch), result.count > 0 {
// if let value = (result.first as! NSObject).value(forKey:fieldName) {
(object as! NSObject).setValue(result.first, forKey: fieldName)
// }
}
}
} else if let subDict = dict[name] as? [String : AnyObject]{
if "\(type)" == "NSObject"{
(object as! NSObject).setValue(subDict, forKey: name)
} else{
// let entity = NSEntityDescription.insertNewObject(forEntityName: "\(type)", into: POLLS_FRAMEWORK.dataController().managedObjectContext)
// populateObject(entity, fromDict: subDict)
// (object as! NSObject).setValue(entity, forKey: name)
}
} else {
if "\(type)" == "NSSet"{
}else{
if !(dict[name] is NSNull) && dict[name] != nil{
(object as! NSObject).setValue(dict[name], forKey: name)
}
}
}
}
}
/// Create and popule a GetPolls object
///
/// - Returns: Newly created GetPolls object
open class func createGetPollsViewModel() -> GetPollsStruct{
var viewModel = GetPollsStruct()
viewModel.viewAll = true
viewModel.pollId = 1
return viewModel
}
}
|
f190ea511217c88c7bb36966f17bb59a
| 47.914286 | 164 | 0.501752 | false | false | false | false |
uhnmdi/CCContinuousGlucose
|
refs/heads/master
|
CCContinuousGlucose/Classes/ContinuousGlucoseSOCP.swift
|
mit
|
1
|
//
// ContinuousGlucoseSOCP.swift
// Pods
//
// Created by Kevin Tallevi on 4/19/17.
//
// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.cgm_specific_ops_control_point.xml
import Foundation
import CoreBluetooth
import CCBluetooth
public class ContinuousGlucoseSOCP : NSObject {
private let socpResponseOpCodeRange = NSRange(location:0, length: 1)
private let cgmCommunicationIntervalRange = NSRange(location:1, length: 1)
private let patientHighAlertLevelRange = NSRange(location:1, length: 2)
private let patientLowAlertLevelRange = NSRange(location:1, length: 2)
private let hypoAlertLevelRange = NSRange(location:1, length: 2)
private let hyperAlertLevelRange = NSRange(location:1, length: 2)
private let rateOfDecreaseAlertLevelRange = NSRange(location:1, length: 2)
private let rateOfIncreaseAlertLevelRange = NSRange(location:1, length: 2)
public var cgmCommunicationInterval: Int = 0
public var patientHighAlertLevel: UInt16 = 0
public var patientLowAlertLevel: UInt16 = 0
public var hypoAlertLevel: UInt16 = 0
public var hyperAlertLevel: UInt16 = 0
public var rateOfDecreaseAlertLevel: Float = 0
public var rateOfIncreaseAlertLevel: Float = 0
public var continuousGlucoseCalibration: ContinuousGlucoseCalibration!
enum Fields: Int {
case reserved,
setCGMCommunicationInterval,
getCGMCommunicationInterval,
cgmCommunicationIntervalResponse,
setGlucoseCalibrationValue,
getGlucoseCalibrationValue,
glucoseCalibrationValueResponse,
setPatientHighAlertLevel,
getPatientHighAlertLevel,
patientHighAlertLevelResponse,
setPatientLowAlertLevel,
getPatientLowAlertLevel,
patientLowAlertLevelResponse,
setHypoAlertLevel,
getHypoAlertLevel,
hypoAlertLevelResponse,
setHyperAlertLevel,
getHyperAlertLevel,
hyperAlertLevelResponse,
setRateOfDecreaseAlertLevel,
getRateOfDecreaseAlertLevel,
rateOfDecreaseAlertLevelResponse,
setRateOfIncreaseAlertLevel,
getRateOfIncreaseAlertLevel,
rateOfIncreaseAlertLevelResponse,
resetDeviceSpecificAlert,
startTheSession,
stopTheSession,
responseCode
}
public override init() {
super.init()
}
public func parseSOCP(data: NSData) {
let socpResponseType = (data.subdata(with: socpResponseOpCodeRange) as NSData!)
var socpResponse: Int = 0
socpResponseType?.getBytes(&socpResponse, length: 1)
switch (socpResponse) {
case ContinuousGlucoseSOCP.Fields.cgmCommunicationIntervalResponse.rawValue:
let communicationIntervalData = (data.subdata(with: cgmCommunicationIntervalRange) as NSData!)
communicationIntervalData?.getBytes(&self.cgmCommunicationInterval, length: 1)
return
case ContinuousGlucoseSOCP.Fields.glucoseCalibrationValueResponse.rawValue:
self.continuousGlucoseCalibration = ContinuousGlucoseCalibration(data: data)
return
case ContinuousGlucoseSOCP.Fields.patientHighAlertLevelResponse.rawValue:
let patientHighAlertLevelData = (data.subdata(with: patientHighAlertLevelRange) as NSData!)
patientHighAlertLevelData?.getBytes(&self.patientHighAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.patientLowAlertLevelResponse.rawValue:
let patientLowAlertLevelData = (data.subdata(with: patientLowAlertLevelRange) as NSData!)
patientLowAlertLevelData?.getBytes(&self.patientLowAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.hypoAlertLevelResponse.rawValue:
let hypoAlertLevelData = (data.subdata(with: hypoAlertLevelRange) as NSData!)
hypoAlertLevelData?.getBytes(&self.hypoAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.hyperAlertLevelResponse.rawValue:
let hyperAlertLevelData = (data.subdata(with: hyperAlertLevelRange) as NSData!)
hyperAlertLevelData?.getBytes(&self.hyperAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.rateOfDecreaseAlertLevelResponse.rawValue:
let rateOfDecreaseAlertLevelData = (data.subdata(with: rateOfDecreaseAlertLevelRange) as NSData!)
self.rateOfDecreaseAlertLevel = (rateOfDecreaseAlertLevelData?.shortFloatToFloat())!
return
case ContinuousGlucoseSOCP.Fields.rateOfIncreaseAlertLevelResponse.rawValue:
let rateOfIncreaseAlertLevelData = (data.subdata(with: rateOfIncreaseAlertLevelRange) as NSData!)
self.rateOfIncreaseAlertLevel = (rateOfIncreaseAlertLevelData?.shortFloatToFloat())!
return
default:
return
}
}
}
|
f384e6ea8fc9b3fdbb4fc73f259c3032
| 44.90991 | 136 | 0.7031 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes
|
refs/heads/master
|
Example/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift
|
apache-2.0
|
13
|
//
// PriorityQueue.swift
// Platform
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct PriorityQueue<Element> {
private let _hasHigherPriority: (Element, Element) -> Bool
private let _isEqual: (Element, Element) -> Bool
private var _elements = [Element]()
init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) {
_hasHigherPriority = hasHigherPriority
_isEqual = isEqual
}
mutating func enqueue(_ element: Element) {
_elements.append(element)
bubbleToHigherPriority(_elements.count - 1)
}
func peek() -> Element? {
return _elements.first
}
var isEmpty: Bool {
return _elements.count == 0
}
mutating func dequeue() -> Element? {
guard let front = peek() else {
return nil
}
removeAt(0)
return front
}
mutating func remove(_ element: Element) {
for i in 0 ..< _elements.count {
if _isEqual(_elements[i], element) {
removeAt(i)
return
}
}
}
private mutating func removeAt(_ index: Int) {
let removingLast = index == _elements.count - 1
if !removingLast {
_elements.swapAt(index, _elements.count - 1)
}
_ = _elements.popLast()
if !removingLast {
bubbleToHigherPriority(index)
bubbleToLowerPriority(index)
}
}
private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while unbalancedIndex > 0 {
let parentIndex = (unbalancedIndex - 1) / 2
guard _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) else { break }
_elements.swapAt(unbalancedIndex, parentIndex)
unbalancedIndex = parentIndex
}
}
private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while true {
let leftChildIndex = unbalancedIndex * 2 + 1
let rightChildIndex = unbalancedIndex * 2 + 2
var highestPriorityIndex = unbalancedIndex
if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = leftChildIndex
}
if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = rightChildIndex
}
guard highestPriorityIndex != unbalancedIndex else { break }
_elements.swapAt(highestPriorityIndex, unbalancedIndex)
unbalancedIndex = highestPriorityIndex
}
}
}
extension PriorityQueue : CustomDebugStringConvertible {
var debugDescription: String {
return _elements.debugDescription
}
}
|
8fb495978c71d94a4fcc6e687c0c826d
| 28.927928 | 133 | 0.622216 | false | false | false | false |
3DprintFIT/octoprint-ios-client
|
refs/heads/dev
|
OctoPhone/Coordinators/FilesCoordinator.swift
|
mit
|
1
|
//
// FilesCoordinator.swift
// OctoPhone
//
// Created by Josef Dolezal on 04/03/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Foundation
import UIKit
import Icons
/// Stored files list coordinator
final class FilesCoordinator: TabCoordinator {
override func start() {
let viewModel = FilesViewModel(delegate: self, provider: provider, contextManager: contextManager)
let controller = FilesViewController(viewModel: viewModel)
controller.title = tr(.files)
controller.tabBarItem = UITabBarItem(withIcon: ._429Icon, size: CGSize(width: 22, height: 22),
title: tr(.files))
navigationController?.pushViewController(controller, animated: false)
}
}
extension FilesCoordinator: FilesViewControllerDelegate {
func selectedFile(_ file: File) {
let coordinator = FileDetailCoordinator(navigationController: navigationController,
contextManager: contextManager, provider: provider,
fileID: file.name)
childCoordinators.append(coordinator)
coordinator.completed = { [weak self] in
_ = self?.childCoordinators.popLast()
}
coordinator.start()
}
}
|
0928a4e5a9ae2bc8d92124c7ce0c62ea
| 32.05 | 106 | 0.635401 | false | false | false | false |
mibaldi/IOS_MIMO_APP
|
refs/heads/master
|
iosAPP/ingredients/KitchenViewController.swift
|
apache-2.0
|
1
|
//
// KitchenViewController.swift
// iosAPP
//
// Created by MIMO on 14/2/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import UIKit
import CoreData
class KitchenViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var myKitchen: UITableView!
@IBOutlet weak var addIngredient: UIButton!
@IBOutlet weak var titleLabel: UILabel!
var ingredients = [Ingredient]()
var sections = [[Ingredient]]()
override func viewDidLoad() {
super.viewDidLoad()
setText()
self.myKitchen.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Ingredient")
let background = CAGradientLayer().blueToWhite()
background.frame = self.view.bounds
self.view.layer.insertSublayer(background, atIndex: 0)
}
func setText(){
titleLabel.text = NSLocalizedString("TUSINGREDIENTES",comment:"Tus Ingredientes")
addIngredient.setTitle(NSLocalizedString("AÑADIRINGREDIENTE",comment:"Añadir Ingrediente"), forState: .Normal)
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.addBorderBottom(size: 1, color: UIColor.blackColor())
header.textLabel?.textAlignment = .Center
}
@IBAction func actionButton(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if appDelegate.isConected {
let instance = self.storyboard!.instantiateViewControllerWithIdentifier("categoryView") as? IngredientsViewController
self.navigationController?.pushViewController(instance!, animated: true)
}else{
self.view.makeToast(NSLocalizedString("SINCONEXION",comment:"No tienes conexión"), duration: 2, position: .Top)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if titleLabel != nil {
sections.removeAll()
do{
var ingredients1 = try IngredientDataHelper.findIngredientsInStorage()!
var ingredients2 = try IngredientDataHelper.findIngredientsNotInStorage()!
ingredients1.sortInPlace({ $0.name < $1.name })
ingredients2.sortInPlace({ $0.name < $1.name })
sections.append(ingredients1)
sections.append(ingredients2)
myKitchen.reloadData()
}catch _{
print("Error al recibir los ingredientes")
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.myKitchen.dequeueReusableCellWithIdentifier("Ingredient")!
let section = sections[indexPath.section]
cell.addBorderBottom(size: 0.5, color: UIColor(red: 78, green: 159, blue: 255, alpha: 0))
cell.backgroundColor = UIColor.whiteColor()
cell.textLabel!.text = section[indexPath.row].name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1{
let ingredient = sections[1][indexPath.row]
do{
try Ingredient.updateIngredientStorage(ingredient)
sections[indexPath.section].removeAtIndex(indexPath.row)
myKitchen.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
sections[0].append(ingredient)
sections[0].sortInPlace({ $0.name < $1.name })
let index = sections[0].indexOf(ingredient)
myKitchen.insertRowsAtIndexPaths([NSIndexPath(forRow: index!, inSection: 0)], withRowAnimation: .Automatic)
}catch _{
print("Error al insertar ingrediente en storage")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func deleteIngredientStore(ingredient: Ingredient){
do{
try Ingredient.deleteIngredientStorage(ingredient)
}catch _{
print("Error al eliminar del storage")
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
var res = false
if indexPath.section == 0{
res = true
}
return res
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete{
var section = sections[indexPath.section]
let ingredient = section[indexPath.row]
sections[indexPath.section].removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
deleteIngredientStore(ingredient)
sections[1].append(ingredient)
sections[1].sortInPlace({ $0.name < $1.name })
let index = sections[1].indexOf(ingredient)
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index!, inSection: 1)], withRowAnimation: .Automatic)
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0{
return NSLocalizedString("ALMACEN",comment:"Almacén")
}else{
return NSLocalizedString("HISTORICO",comment:"Histórico")
}
}
}
|
4d5b29aea77f053c0782aecc8c0abfc7
| 34.875 | 148 | 0.640119 | false | false | false | false |
SereivoanYong/Charts
|
refs/heads/master
|
Source/Charts/Charts/PieChartView.swift
|
apache-2.0
|
1
|
//
// PieChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
/// View that represents a pie chart. Draws cake like slices.
open class PieChartView: BasePieRadarChartView {
/// maximum angle for this pie
fileprivate var _maxAngle: CGFloat = 360.0
internal override func initialize() {
super.initialize()
renderer = PieRenderer(chart: self, animator: animator, viewPortHandler: viewPortHandler)
_xAxis = nil
self.highlighter = PieHighlighter(chart: self)
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
if data == nil {
return
}
let context = UIGraphicsGetCurrentContext()!
renderer!.drawData(context: context)
if valuesToHighlight() {
renderer!.drawHighlighted(context: context, indices: _indicesToHighlight)
}
renderer!.drawExtras(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
internal override func calculateOffsets() {
super.calculateOffsets()
// prevent nullpointer when no data set
if data == nil {
return
}
let radius = diameter / 2.0
let c = centerOffsets
let shift = (data as? PieData)?.dataSet?.selectionShift ?? 0.0
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
circleBox = CGRect(x: (c.x - radius) + shift, y: (c.y - radius) + shift, width: diameter - shift * 2.0, height: diameter - shift * 2.0)
}
internal override func calcMinMax() {
calcAngles()
}
open override func getMarkerPosition(highlight: Highlight) -> CGPoint {
let center = centerCircleBox
var r = radius
var off = r / 10.0 * 3.6
if isDrawHoleEnabled {
off = (r - (r * holeRadiusPercent)) / 2.0
}
r -= off // offset to keep things inside the chart
let rotationAngle = self.rotationAngle
let entryIndex = Int(highlight.x)
// offset needed to center the drawn text in the slice
let offset = drawAngles[entryIndex] / 2.0
// calculate the text position
let x = r * cos(((rotationAngle + absoluteAngles[entryIndex] - offset) * animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x
let y = r * sin(((rotationAngle + absoluteAngles[entryIndex] - offset) * animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y
return CGPoint(x: x, y: y)
}
/// calculates the needed angles for the chart slices
fileprivate func calcAngles() {
drawAngles.removeAll(keepingCapacity: false)
absoluteAngles.removeAll(keepingCapacity: false)
guard let data = data else { return }
let entryCount = data.entryCount
drawAngles.reserveCapacity(entryCount)
absoluteAngles.reserveCapacity(entryCount)
let yValueSum = (data as! PieData).yValueSum
var cnt = 0
for set in data.dataSets {
for entry in set.entries {
drawAngles.append(calcAngle(value: abs(entry.y), yValueSum: yValueSum))
if cnt == 0 {
absoluteAngles.append(drawAngles[cnt])
} else {
absoluteAngles.append(absoluteAngles[cnt - 1] + drawAngles[cnt])
}
cnt += 1
}
}
}
/// Checks if the given index is set to be highlighted.
open func needsHighlight(index: Int) -> Bool {
// no highlight
if !valuesToHighlight() {
return false
}
for i in 0 ..< _indicesToHighlight.count {
// check if the xvalue for the given dataset needs highlight
if Int(_indicesToHighlight[i].x) == index {
return true
}
}
return false
}
/// calculates the needed angle for a given value
fileprivate func calcAngle(_ value: CGFloat) -> CGFloat {
return calcAngle(value: value, yValueSum: (data as! PieData).yValueSum)
}
/// calculates the needed angle for a given value
fileprivate func calcAngle(value: CGFloat, yValueSum: CGFloat) -> CGFloat {
return value / yValueSum * _maxAngle
}
/// This will throw an exception, PieChart has no XAxis object.
open override var xAxis: XAxis {
fatalError("PieChart has no XAxis")
}
open override func indexForAngle(_ angle: CGFloat) -> Int {
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
for i in 0 ..< absoluteAngles.count {
if absoluteAngles[i] > a {
return i
}
}
return -1 // return -1 if no index found
}
/// - returns: The index of the DataSet this x-index belongs to.
open func dataSetIndexForIndex(_ xValue: CGFloat) -> Int {
var dataSets = data?.dataSets ?? []
for i in 0 ..< dataSets.count {
if (dataSets[i].entryForXValue(xValue, closestToY: .nan) != nil) {
return i
}
}
return -1
}
/// - returns: An integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
open fileprivate(set) var drawAngles: [CGFloat] = []
/// - returns: The absolute angles of the different chart slices (where the
/// slices end)
open fileprivate(set) var absoluteAngles: [CGFloat] = []
/// The color for the hole that is drawn in the center of the PieChart (if enabled).
///
/// - note: Use holeTransparent with holeColor = nil to make the hole transparent.*
open var holeColor: UIColor? = .white {
didSet {
setNeedsDisplay()
}
}
/// if true, the hole will see-through to the inner tips of the slices
///
/// **default**: `false`
open var isDrawSlicesUnderHoleEnabled: Bool = false {
didSet {
setNeedsDisplay()
}
}
/// `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot
///
/// **default**: `false`
open var isDrawHoleEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
/// the text that is displayed in the center of the pie-chart
open var centerText: String? {
get {
return centerAttributedText?.string
}
set {
var attrString: NSMutableAttributedString?
if newValue == nil {
attrString = nil
} else {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
attrString = NSMutableAttributedString(string: newValue!)
attrString?.setAttributes([NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSParagraphStyleAttributeName: paragraphStyle],
range: NSMakeRange(0, attrString!.length))
}
centerAttributedText = attrString
}
}
/// the text that is displayed in the center of the pie-chart
open var centerAttributedText: NSAttributedString? {
didSet {
setNeedsDisplay()
}
}
/// Sets the offset the center text should have from it's original position in dp. Default x = 0, y = 0
open var centerTextOffset: CGPoint = .zero {
didSet {
setNeedsDisplay()
}
}
/// `true` if drawing the center text is enabled
open var isDrawCenterTextEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
internal override var requiredLegendOffset: CGFloat {
return legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat {
return 0.0
}
open override var radius: CGFloat {
return circleBox.width / 2.0
}
/// - returns: The circlebox, the boundingbox of the pie-chart slices
open fileprivate(set) var circleBox: CGRect = .zero
/// - returns: The center of the circlebox
open var centerCircleBox: CGPoint {
return CGPoint(x: circleBox.midX, y: circleBox.midY)
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.5 (50%) (half the pie)
open var holeRadiusPercent: CGFloat = 0.5 {
didSet {
setNeedsDisplay()
}
}
/// The color that the transparent-circle should have.
///
/// **default**: `nil`
open var transparentCircleColor: UIColor? = UIColor(white: 1.0, alpha: 105.0/255.0) {
didSet {
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default
open var transparentCircleRadiusPercent: CGFloat = 0.55 {
didSet {
setNeedsDisplay()
}
}
/// The color the entry labels are drawn with.
open var entryLabelColor: UIColor? = .white {
didSet {
setNeedsDisplay()
}
}
/// The font the entry labels are drawn with.
open var entryLabelFont: UIFont? = .systemFont(ofSize: 13.0) {
didSet {
setNeedsDisplay()
}
}
/// Set this to true to draw the enrty labels into the pie slices
open var isDrawEntryLabelsEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
open var isUsePercentValuesEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
open var centerTextRadiusPercent: CGFloat = 1.0 {
didSet {
setNeedsDisplay()
}
}
/// The max angle that is used for calculating the pie-circle.
/// 360 means it's a full pie-chart, 180 results in a half-pie-chart.
/// **default**: 360.0
open var maxAngle: CGFloat {
get {
return _maxAngle
}
set {
_maxAngle = newValue
if _maxAngle > 360.0 {
_maxAngle = 360.0
}
if _maxAngle < 90.0 {
_maxAngle = 90.0
}
}
}
}
|
191ff28e0750b15213f2726d0669d242
| 27.165312 | 187 | 0.64072 | false | false | false | false |
matthewsot/DNSwift
|
refs/heads/master
|
SystemCollectionsGeneric/SystemCollectionsGeneric/List.swift
|
mit
|
1
|
import Foundation
import DNSwift
public class List<E where E:Equatable>: IList {
typealias T = E;
private var Objects: [T];
public var Count: Int {
get {
return Objects.count
}
};
public var Capacity: Int; //todo: consider implementing this
public init() {
Capacity = Int.max;
self.Objects = Array<T>();
}
public init(objs: [T])
{
Capacity = Int.max;
self.Objects = objs;
}
//IEnumerable
public func GetEnumerator<IE where IE:IEnumerator>() -> IE {
return Enumerator(objs: Objects) as IE;
}
public func generate() -> Enumerator<T> {
return Enumerator(objs: self.Objects);
}
//ICollection
public var IsReadOnly: Bool { get { return false; } };
//TODO: replace some of these AnyObjects with T
//Methods
public func Add(item: T) {
Objects.append(item);
}
public func Clear() {
Objects.removeAll(keepCapacity: false);
}
public func Contains(item: T) -> Bool {
return contains(Objects, item);
}
public func CopyTo(inout array: [T]) {
array.removeAll(keepCapacity: false);
for item in Objects {
array.append(item);
}
}
public func CopyTo(inout array: [T], arrayIndex: Int) {
for (index, item) in enumerate(Objects) {
array.insert(item, atIndex: arrayIndex + index);
}
}
public func CopyTo(index: Int, inout array: [T], arrayIndex: Int, count: Int) {
for i in 0..<count {
if(index + i <= Objects.count) {
array.insert(Objects[(index + i)], atIndex: i + arrayIndex);
}
}
}
public func Remove(item: T) {
Objects.removeAtIndex(Objects.IndexOf(item));
}
//IList
public func IndexOf(obj: T) -> Int {
return Objects.IndexOf(obj);
}
public func AddRange(objs: Array<T>) {
for obj in objs {
Objects.append(obj);
}
}
//AsReadOnly
//BinarySearch(T)
//BinarySearch(T, IComparer<T>)
//BinarySearch(Int, Int, T, IComparer<T>)
public func ConvertAll<O>() -> List<O> {
var newList = List<O>();
for item in Objects {
newList.Add(item as O);
}
return newList;
}
public func Equals(obj: NSObject) -> Bool {
return obj === self;
}
public func Exists(predicate: (T) -> Bool) -> Bool {
return self.Any(predicate);
}
//Finalize
public func Find(predicate: (T) -> Bool) -> T {
return self.First(predicate);
}
public func FindAll(predicate: (T) -> Bool) -> List<T> {
return self.Where(predicate);
}
public func FindIndex(predicate: (T) -> Bool) -> Int {
for (index, item) in enumerate(Objects) {
if(predicate(item)) {
return index;
}
}
return -1;
}
//TODO: rewrite the next two so they don't enumerate the whole thing.
//something with for i in 0..count
public func FindIndex(startIndex: Int, predicate: (T) -> Bool) -> Int {
for (index, item) in enumerate(Objects) {
if(index < startIndex)
{
continue;
}
if(predicate(item)) {
return index;
}
}
return -1;
}
public func FindIndex(startIndex: Int, count: Int, predicate: (T) -> Bool) -> Int {
for(index, item) in enumerate(Objects) {
if(index < startIndex) {
continue;
}
if(index > (startIndex + count)) {
break;
}
if(predicate(item)) {
return index;
}
}
return -1;
}
public func FindLast(predicate: (T) -> Bool) -> T {
return self.Where(predicate).Last();
}
//FindLastIndex(predicate)
//FindLastIndex(Int, predicate)
//FindLastIndex(Int, Int, predicate)
//ForEach
//GetHashCode
//GetRange
//GetType
//IndexOf(T, Int)
//IndexOf(T, Int, Int)
public func Insert(index: Int, obj item: T) {
Objects.insert(item, atIndex: index);
}
public func InsertRange(startingIndex: Int, objs: Array<T>) {
for (index, item) in enumerate(objs) {
Objects.insert(item, atIndex: (startingIndex + index));
}
}
//LastIndexOf(T)
//LastIndexOf(T, Int)
//LastIndexOf(T, Int, Int)
//MemberwiseClone
public func RemoveAll() {
Objects.removeAll(keepCapacity: false);
}
public func RemoveAll(predicate: (T) -> Bool) {
for (index, item) in enumerate(Objects) {
if(predicate(item)) {
Objects.removeAtIndex(index);
}
}
}
public func RemoveAt(index: Int) {
Objects.removeAtIndex(index);
}
public func RemoveRange(objs: Array<T>) {
for obj: T in objs {
self.Remove(obj);
}
}
public func Reverse() -> List<T> {
return List(objs: Objects.reverse());
}
//Reverse(Int, Int)
//Sort()
//Sort(comparison)
//Sort(icomparer)
//Sort(Int,Int,IComparer)
public func ToArray() -> [T] {
return self.Objects;
}
public func ToString() -> String {
//TODO: figure out what the native .NET libraries return for this
return "List";
}
//TrimExcess
/*public func TrueForAll(predicate: (T) -> Bool) -> Bool {
return self.Where(predicate).Count == self.Count;
}*/
//Extension methods
public func Where(predicate: (T) -> Bool) -> List<T> {
return List(objs: self.Objects.filter(predicate));
}
public func Last() -> T { //TODO nil check/count == 0
return self.Objects[self.Count - 1];
}
public func Any() -> Bool {
return Count > 0;
}
public func Any(predicate: (T) -> Bool) -> Bool {
return self.Where(predicate).Any();
}
public func First() -> T {
return self.Objects[0];
}
public func First(predicate: (T) -> Bool) -> T {
return self.Where(predicate).First();
}
/*public func FirstOrDefault() -> T? {
return self.Objects.FirstOrDefault();
}
public func FirstOrDefault(predicate: (T) -> Bool) -> T? {
return self.Objects.FirstOrDefault(predicate);
}*/
}
|
9b49d33069c646b5c598726656004039
| 23.688889 | 87 | 0.52198 | false | false | false | false |
allevato/SwiftCGI
|
refs/heads/master
|
Sources/SwiftCGI/CGIHTTPResponse.swift
|
apache-2.0
|
1
|
// Copyright 2015 Tony Allevato
//
// 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.
/// Implements the `HTTPResponse` protocol for responses in both CGI and FastCGI applications.
class CGIHTTPResponse: HTTPResponse, WriteNotifyingOutputStreamDelegate {
var headers: HTTPHeaders
var status: HTTPStatus
let contentStream: OutputStream
var contentLength: Int {
get {
if let value = headers["Content-Length"], length = Int(value) {
return length
}
return 0
}
set {
headers["Content-Length"] = String(newValue)
}
}
var contentType: String {
get {
if let value = headers["Content-Type"] {
return value
}
return ""
}
set {
headers["Content-Type"] = newValue
}
}
/// Creates a new response with the given content output stream.
///
/// - Parameter contentStream: The output stream to which the response message will be written.
init(contentStream: OutputStream) {
headers = HTTPHeaders()
headers["Content-Type"] = "text/plain;charset=utf8"
status = .OK
let notifyingStream = WriteNotifyingOutputStream(outputStream: contentStream)
self.contentStream = notifyingStream
notifyingStream.delegate = self
}
func outputStreamWillBeginWriting(outputStream: OutputStream) throws {
// Write the HTTP header lines of the response message before any body content is written.
try outputStream.write("Status: \(status.code)\n")
for (header, value) in headers {
try outputStream.write("\(header): \(value)\n")
}
try outputStream.write("\n")
}
}
|
826e5feabe426a19df512b8eb6a8b596
| 30.044118 | 97 | 0.693036 | false | false | false | false |
CodaFi/swift-compiler-crashes
|
refs/heads/master
|
crashes-duplicates/01185-swift-parser-parsetypeidentifier.swift
|
mit
|
12
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b<c {
enum b {
func b
var _ = b
func k<q {
enum k {
}
}
class x {
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
}
protocol y {
}
struct D : y {
func y<v k r {
}
class y<D> {
}
}
func l<c>(m: (l, c) -> c) -> (l, c) -> c {
f { i
}, k)
class l {
class func m {
b let k: String = {
}()
struct q<q : n, p: n where p.q == q.q> {
}
o q: n = { m, i j
l {
k m p<i) {
}
}
}
}lass func c()
}
s}
class a<f : b, : b where f.d == g> {
}
struct j<l : o> {
}
func a<l>() -> [j<l>] {
}
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
}
class l: f{ class func n {}
func a<i>() {
b b {
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
}
struct j<n : b> : b {
}
enum e<b> : d {
func c<b>() -> b {
}
}
protocol d {
}
enum A : String {
}
if c == .b {
}
struct c<f : h> {
var b: [c<f>] {
g []e f() {
}
}
protocol c : b { func b
class j {
func y((Any, j))(v: (Any, AnyObject)) {
}
|
6892838eed830e4c69619d83c25921f2
| 10.934066 | 87 | 0.486188 | false | false | false | false |
BigxMac/firefox-ios
|
refs/heads/master
|
Storage/SQL/SQLiteRemoteClientsAndTabs.swift
|
mpl-2.0
|
5
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = XCGLogger.defaultInstance()
public class SQLiteRemoteClientsAndTabs: RemoteClientsAndTabs {
let db: BrowserDB
let clients = RemoteClientsTable<RemoteClient>()
let tabs = RemoteTabsTable<RemoteTab>()
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(clients)
db.createOrUpdate(tabs)
}
private func doWipe(f: (conn: SQLiteDBConnection, inout err: NSError?) -> ()) -> Deferred<Result<()>> {
let deferred = Deferred<Result<()>>(defaultQueue: dispatch_get_main_queue())
var err: NSError?
db.transaction(&err) { connection, _ in
f(conn: connection, err: &err)
if let err = err {
let databaseError = DatabaseError(err: err)
log.debug("Wipe failed: \(databaseError)")
deferred.fill(Result(failure: databaseError))
} else {
deferred.fill(Result(success: ()))
}
return true
}
return deferred
}
public func wipeClients() -> Deferred<Result<()>> {
return self.doWipe { (conn, inout err: NSError?) -> () in
self.clients.delete(conn, item: nil, err: &err)
}
}
public func wipeTabs() -> Deferred<Result<()>> {
return self.doWipe { (conn, inout err: NSError?) -> () in
self.tabs.delete(conn, item: nil, err: &err)
}
}
public func clear() -> Deferred<Result<()>> {
return self.doWipe { (conn, inout err: NSError?) -> () in
self.tabs.delete(conn, item: nil, err: &err)
self.clients.delete(conn, item: nil, err: &err)
}
}
public func insertOrUpdateTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> {
return self.insertOrUpdateTabsForClientGUID(nil, tabs: tabs)
}
public func insertOrUpdateTabsForClientGUID(clientGUID: String?, tabs: [RemoteTab]) -> Deferred<Result<Int>> {
let deferred = Deferred<Result<Int>>(defaultQueue: dispatch_get_main_queue())
let deleteQuery = "DELETE FROM \(self.tabs.name) WHERE client_guid IS ?"
let deleteArgs: [AnyObject?] = [clientGUID]
var err: NSError?
db.transaction(&err) { connection, _ in
// Delete any existing tabs.
if let error = connection.executeChange(deleteQuery, withArgs: deleteArgs) {
deferred.fill(Result(failure: DatabaseError(err: err)))
return false
}
// Insert replacement tabs.
var inserted = 0
var err: NSError?
for tab in tabs {
// We trust that each tab's clientGUID matches the supplied client!
// Really tabs shouldn't have a GUID at all. Future cleanup!
self.tabs.insert(connection, item: tab, err: &err)
if let err = err {
deferred.fill(Result(failure: DatabaseError(err: err)))
return false
}
inserted++;
}
deferred.fill(Result(success: inserted))
return true
}
return deferred
}
public func insertOrUpdateClients(clients: [RemoteClient]) -> Deferred<Result<()>> {
let deferred = Deferred<Result<()>>(defaultQueue: dispatch_get_main_queue())
var err: NSError?
// TODO: insert multiple clients in a single query.
// ORM systems are foolish.
db.transaction(&err) { connection, _ in
// Update or insert client records.
for client in clients {
let updated = self.clients.update(connection, item: client, err: &err)
log.info("Updated clients: \(updated)")
if err == nil && updated == 0 {
let inserted = self.clients.insert(connection, item: client, err: &err)
log.info("Inserted clients: \(inserted)")
}
if let err = err {
let databaseError = DatabaseError(err: err)
log.debug("insertOrUpdateClients failed: \(databaseError)")
deferred.fill(Result(failure: databaseError))
return false
}
}
deferred.fill(Result(success: ()))
return true
}
return deferred
}
public func insertOrUpdateClient(client: RemoteClient) -> Deferred<Result<()>> {
return insertOrUpdateClients([client])
}
public func getClients() -> Deferred<Result<[RemoteClient]>> {
var err: NSError?
let clientCursor = db.withReadableConnection(&err) { connection, _ in
return self.clients.query(connection, options: nil)
}
if let err = err {
clientCursor.close()
return Deferred(value: Result(failure: DatabaseError(err: err)))
}
let clients = clientCursor.asArray()
clientCursor.close()
return Deferred(value: Result(success: clients))
}
public func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
var err: NSError?
// Now find the clients.
let clientCursor = db.withReadableConnection(&err) { connection, _ in
return self.clients.query(connection, options: nil)
}
if let err = err {
clientCursor.close()
return Deferred(value: Result(failure: DatabaseError(err: err)))
}
let clients = clientCursor.asArray()
clientCursor.close()
log.info("Found \(clients.count) clients in the DB.")
let tabCursor = db.withReadableConnection(&err) { connection, _ in
return self.tabs.query(connection, options: nil)
}
log.info("Found \(tabCursor.count) raw tabs in the DB.")
if let err = err {
tabCursor.close()
return Deferred(value: Result(failure: DatabaseError(err: err)))
}
let deferred = Deferred<Result<[ClientAndTabs]>>(defaultQueue: dispatch_get_main_queue())
// Aggregate clientGUID -> RemoteTab.
var acc = [String: [RemoteTab]]()
for tab in tabCursor {
if let tab = tab, guid = tab.clientGUID {
if acc[guid] == nil {
acc[guid] = [tab]
} else {
acc[guid]!.append(tab)
}
} else {
log.error("Couldn't cast tab \(tab) to RemoteTab.")
}
}
tabCursor.close()
log.info("Accumulated tabs with client GUIDs \(acc.keys).")
// Most recent first.
let sort: (RemoteTab, RemoteTab) -> Bool = { $0.lastUsed > $1.lastUsed }
let fillTabs: (RemoteClient) -> ClientAndTabs = { client in
var tabs: [RemoteTab]? = nil
if let guid: String = client.guid {
tabs = acc[guid] // ?.sorted(sort) // The sort should be unnecessary: the DB does that.
}
return ClientAndTabs(client: client, tabs: tabs ?? [])
}
let removeLocalClient: (RemoteClient) -> Bool = { client in
return client.guid != nil
}
// Why is this whole function synchronous?
deferred.fill(Result(success: clients.filter(removeLocalClient).map(fillTabs)))
return deferred
}
public func onRemovedAccount() -> Success {
log.info("Clearing clients and tabs after account removal.")
// TODO: Bug 1168690 - delete our client and tabs records from the server.
return self.clear()
}
private let debug_enabled = true
private func debug(msg: String) {
if debug_enabled {
log.info(msg)
}
}
}
|
dd0f2aaaabcf3d8f3d255046e022f1ac
| 33.174468 | 114 | 0.564687 | false | false | false | false |
CoderKingdom/swiftExtensions
|
refs/heads/develop
|
2015/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift
|
apache-2.0
|
30
|
#if os(Linux)
import Glibc
#endif
import Foundation
internal let DefaultDelta = 0.0001
internal func isCloseTo(actualValue: NMBDoubleConvertible?, expectedValue: NMBDoubleConvertible, delta: Double, failureMessage: FailureMessage) -> Bool {
failureMessage.postfixMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))"
failureMessage.actualValue = "<\(stringify(actualValue))>"
return actualValue != nil && abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(expectedValue: Double, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<Double> {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage)
}
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<NMBDoubleConvertible> {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage)
}
}
#if _runtime(_ObjC)
public class NMBObjCBeCloseToMatcher : NSObject, NMBMatcher {
var _expected: NSNumber
var _delta: CDouble
init(expected: NSNumber, within: CDouble) {
_expected = expected
_delta = within
}
public func matches(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.matches(expr, failureMessage: failureMessage)
}
public func doesNotMatch(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.doesNotMatch(expr, failureMessage: failureMessage)
}
public var within: (CDouble) -> NMBObjCBeCloseToMatcher {
return ({ delta in
return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta)
})
}
}
extension NMBObjCMatcher {
public class func beCloseToMatcher(expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher {
return NMBObjCBeCloseToMatcher(expected: expected, within: within)
}
}
#endif
public func beCloseTo(expectedValues: [Double], within delta: Double = DefaultDelta) -> NonNilMatcherFunc <[Double]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))"
if let actual = try actualExpression.evaluate() {
failureMessage.actualValue = "<\(stringify(actual))>"
if actual.count != expectedValues.count {
return false
} else {
for (index, actualItem) in actual.enumerate() {
if fabs(actualItem - expectedValues[index]) > delta {
return false
}
}
return true
}
}
return false
}
}
// MARK: - Operators
infix operator ≈ {
associativity none
precedence 130
}
public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<Double>, rhs: Double) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
public func ==(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
// make this higher precedence than exponents so the Doubles either end aren't pulled in
// unexpectantly
infix operator ± { precedence 170 }
public func ±(lhs: Double, rhs: Double) -> (expected: Double, delta: Double) {
return (expected: lhs, delta: rhs)
}
|
b870d789ca742b24395f3365f9d48a30
| 38.120968 | 153 | 0.688106 | false | false | false | false |
haskellswift/swift-package-manager
|
refs/heads/master
|
Sources/PackageModel/Module.swift
|
apache-2.0
|
2
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
-----------------------------------------------------------------------
A Target is a collection of sources and configuration that can be built
into a product.
TODO should be a protocol
*/
import Basic
@_exported import enum PackageDescription.SystemPackageProvider
public protocol ModuleProtocol {
var name: String { get }
var c99name: String { get }
var dependencies: [Module] { get set }
var recursiveDependencies: [Module] { get }
var isTest: Bool { get }
}
public enum ModuleType {
case executable, library, systemModule
}
public class Module: ModuleProtocol {
/// The name of the module.
///
/// NOTE: This name is not the language-level module (i.e., the importable
/// name) name in many cases, instead use c99name if you need uniqueness.
public let name: String
/// The dependencies of this module, once loaded.
public var dependencies: [Module]
/// The language-level module name.
public var c99name: String
/// Whether this is a test module.
//
// FIXME: This should probably be rolled into the type.
public let isTest: Bool
/// Suffix that's expected for test modules.
public static let testModuleNameSuffix = "Tests"
/// The "type" of module.
public let type: ModuleType
/// The sources for the module.
public let sources: Sources
public init(name: String, type: ModuleType, sources: Sources, isTest: Bool = false) throws {
self.name = name
self.type = type
self.sources = sources
self.dependencies = []
self.c99name = self.name.mangledToC99ExtendedIdentifier()
self.isTest = isTest
}
/// The transitive closure of the module dependencies, in build order.
//
// FIXME: This should be cached, once we have an immutable model.
public var recursiveDependencies: [Module] {
return (try! topologicalSort(dependencies, successors: { $0.dependencies })).reversed()
}
/// The base prefix for the test module, used to associate with the target it tests.
public var basename: String {
guard isTest else {
fatalError("\(type(of: self)) should be a test module to access basename.")
}
precondition(name.hasSuffix(Module.testModuleNameSuffix))
return name[name.startIndex..<name.index(name.endIndex, offsetBy: -Module.testModuleNameSuffix.characters.count)]
}
}
extension Module: Hashable, Equatable {
public var hashValue: Int { return c99name.hashValue }
}
public func ==(lhs: Module, rhs: Module) -> Bool {
return lhs.c99name == rhs.c99name
}
public class SwiftModule: Module {
public init(name: String, isTest: Bool = false, sources: Sources) throws {
// Compute the module type.
let isLibrary = !sources.relativePaths.contains { path in
let file = path.basename.lowercased()
// Look for a main.xxx file avoiding cases like main.xxx.xxx
return file.hasPrefix("main.") && file.characters.filter({$0 == "."}).count == 1
}
let type: ModuleType = isLibrary ? .library : .executable
try super.init(name: name, type: type, sources: sources, isTest: isTest)
}
}
public class CModule: Module {
public let path: AbsolutePath
public let pkgConfig: RelativePath?
public let providers: [SystemPackageProvider]?
public init(name: String, type: ModuleType = .systemModule, sources: Sources, path: AbsolutePath, isTest: Bool = false, pkgConfig: RelativePath? = nil, providers: [SystemPackageProvider]? = nil) throws {
self.path = path
self.pkgConfig = pkgConfig
self.providers = providers
try super.init(name: name, type: type, sources: sources, isTest: false)
}
}
public class ClangModule: Module {
public var includeDir: AbsolutePath {
return sources.root.appending(component: "include")
}
public init(name: String, isTest: Bool = false, sources: Sources) throws {
// Compute the module type.
let isLibrary = !sources.relativePaths.contains { path in
let file = path.basename.lowercased()
// Look for a main.xxx file avoiding cases like main.xxx.xxx
return file.hasPrefix("main.") && file.characters.filter({$0 == "."}).count == 1
}
let type: ModuleType = isLibrary ? .library : .executable
try super.init(name: name, type: type, sources: sources, isTest: isTest)
}
}
extension Module: CustomStringConvertible {
public var description: String {
return "\(type(of: self))(\(name))"
}
}
|
86f561162e5776ef308f21cd735c640f
| 33.375 | 207 | 0.656566 | false | true | false | false |
werner-freytag/DockTime
|
refs/heads/master
|
ClockBundle-White/Layers/FaceBackgroundLayer.swift
|
mit
|
1
|
//
// Created by Werner on 02.02.18.
// Copyright © 2018-2021 Werner Freytag. All rights reserved.
//
import AppKit.NSBezierPath
import QuartzCore.CAGradientLayer
class FaceBackgroundLayer: CAGradientLayer {
let renderBounds = CGRect(x: 0, y: 0, width: 280, height: 280)
override init() {
super.init()
frame = renderBounds
colors = [NSColor(white: 1, alpha: 1).cgColor, NSColor(white: 0.93, alpha: 0.9).cgColor]
let maskLayer = CAShapeLayer()
maskLayer.path = NSBezierPath(ovalIn: frame).cgPath
mask = maskLayer
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
5b7cc33fc09a9629ac24547583ff88f0
| 24.75 | 96 | 0.649098 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.