repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
BabyShung/SplashWindow
ZHExtensions/ZHExtensions/ZHExtensions/UIButtonExtension.swift
1
1184
import UIKit public extension UIButton { /// If you have set an image in self, this will try to center both titleLabel /// and imageView /// - Parameter padding: padding between btn and imageView public func centerVertically(padding: CGFloat = 2.0) { guard let imageView = imageView, let titleLabel = titleLabel else { return } let imageSize = imageView.frame.size let titleSize = titleLabel.frame.size let totalHeight = imageSize.height + titleSize.height + padding imageEdgeInsets = UIEdgeInsetsMake(-(totalHeight - imageSize.height), 0, 0, -titleSize.width) titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, -(totalHeight - titleSize.height), 0) contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0) } }
mit
c7ccae2fdfb18d8bf458d47c68680d96
42.851852
84
0.460304
6.883721
false
false
false
false
nathawes/swift
stdlib/public/Darwin/Foundation/NSFastEnumeration.swift
9
4854
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module /// A dummy value to be used as the target for `mutationsPtr` in fast enumeration implementations. private var _fastEnumerationMutationsTarget: CUnsignedLong = 0 /// A dummy pointer to be used as `mutationsPtr` in fast enumeration implementations. private let _fastEnumerationMutationsPtr = UnsafeMutablePointer<CUnsignedLong>(&_fastEnumerationMutationsTarget) //===----------------------------------------------------------------------===// // Fast enumeration //===----------------------------------------------------------------------===// public struct NSFastEnumerationIterator : IteratorProtocol { var enumerable: NSFastEnumeration var objects: (Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?, Unmanaged<AnyObject>?) = (nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) var state = NSFastEnumerationState(state: 0, itemsPtr: nil, mutationsPtr: _fastEnumerationMutationsPtr, extra: (0, 0, 0, 0, 0)) var index = 0 var count = 0 var useObjectsBuffer = false public init(_ enumerable: NSFastEnumeration) { self.enumerable = enumerable } public mutating func next() -> Any? { if index + 1 > count { index = 0 // ensure NO ivars of self are actually captured let enumeratedObject = enumerable var localState = state var localObjects = objects (count, useObjectsBuffer) = withUnsafeMutablePointer(to: &localObjects) { let buffer = AutoreleasingUnsafeMutablePointer<AnyObject?>($0) return withUnsafeMutablePointer(to: &localState) { (statePtr: UnsafeMutablePointer<NSFastEnumerationState>) -> (Int, Bool) in let result = enumeratedObject.countByEnumerating(with: statePtr, objects: buffer, count: 16) if statePtr.pointee.itemsPtr == buffer { // Most cocoa classes will emit their own inner pointer buffers instead of traversing this path. Notable exceptions include NSDictionary and NSSet return (result, true) } else { // this is the common case for things like NSArray return (result, false) } } } state = localState // restore the state value objects = localObjects // copy the object pointers back to the self storage if count == 0 { return nil } } defer { index += 1 } if !useObjectsBuffer { return state.itemsPtr![index] } else { switch index { case 0: return objects.0!.takeUnretainedValue() case 1: return objects.1!.takeUnretainedValue() case 2: return objects.2!.takeUnretainedValue() case 3: return objects.3!.takeUnretainedValue() case 4: return objects.4!.takeUnretainedValue() case 5: return objects.5!.takeUnretainedValue() case 6: return objects.6!.takeUnretainedValue() case 7: return objects.7!.takeUnretainedValue() case 8: return objects.8!.takeUnretainedValue() case 9: return objects.9!.takeUnretainedValue() case 10: return objects.10!.takeUnretainedValue() case 11: return objects.11!.takeUnretainedValue() case 12: return objects.12!.takeUnretainedValue() case 13: return objects.13!.takeUnretainedValue() case 14: return objects.14!.takeUnretainedValue() case 15: return objects.15!.takeUnretainedValue() default: fatalError("Access beyond storage buffer") } } } } extension NSEnumerator : Sequence { /// Return an *iterator* over the *enumerator*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } }
apache-2.0
fe89cefe186f4b40490c89c14a8b39d9
49.5625
468
0.598888
5.572905
false
false
false
false
yonbergman/swift-gameoflife
gameoflife/Point.swift
2
808
// // point.swift // gameoflife // // Created by Yonatan Bergman on 6/4/14. // Copyright (c) 2014 Yonatan Bergman. All rights reserved. // import Foundation struct Point : Hashable, Equatable { var x:Int = 0 var y:Int = 0 var hashValue: Int { return x * 10000 + y } // Get the surrounding cells around this point func neighbours() -> Array<Point>{ var result:Array<Point> = [] for xModifier in (-1...1){ for yModifier in (-1...1){ if xModifier != 0 || yModifier != 0 { result.append(Point(x: self.x + xModifier, y: self.y + yModifier)) } } } return result } } func ==(lhs: Point, rhs: Point) -> Bool{ return lhs.x == rhs.x && lhs.y == rhs.y }
mit
b5154002385769dcc0aed0a32d53721c
22.085714
86
0.52104
3.559471
false
false
false
false
PerfectlySoft/Perfect-TensorFlow
Sources/PerfectTensorFlow/APILoader.swift
1
71506
// // APILoader.swift // Perfect-TensorFlow // // Created by Rockford Wei on 2017-05-18. // Copyright © 2017 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2017 - 2018 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import TensorFlowAPI /// Static C API of TensorFlow public class TFLib { /// Exceptions public enum Panic: Error { case /// Exceptions in dynamic library loading DLL(reason: String), /// Exceptions in api binding SYM(reason: String), /// Exceptions in calling CALL, /// One of the parameters passed to the wrapper is not acceptable INVALID, /// fault with reason FAULT(reason: String) } /// TF_Code holds an error code. The enum values here are identical to /// corresponding values in error_codes.proto. public enum Code: Int { /// -1 is added by Perfect case UNDEFINED = -1, OK = 0, CANCELLED = 1, UNKNOWN = 2, INVALID_ARGUMENT = 3, DEADLINE_EXCEEDED = 4, NOT_FOUND = 5, ALREADY_EXISTS = 6, PERMISSION_DENIED = 7, UNAUTHENTICATED = 16, RESOURCE_EXHAUSTED = 8, FAILED_PRECONDITION = 9, ABORTED = 10, OUT_OF_RANGE = 11, UNIMPLEMENTED = 12, INTERNAL = 13, UNAVAILABLE = 14, DATA_LOSS = 15 } public static var libDLL = UnsafeMutableRawPointer(bitPattern: 0) public static func LoadFunction <T> (_ library: UnsafeMutableRawPointer?, _ symbol: String) throws -> T { guard let lib = library else { throw Panic.DLL(reason: String(cString: dlerror())) }//end guard guard let sym = dlsym(lib, symbol) else { throw Panic.SYM(reason: String(cString: dlerror())) }//end guard return unsafeBitCast(sym, to: T.self) } public static var Version: @convention(c) () -> UnsafePointer<CChar>? = { return nil } public static var DataTypeSize: @convention(c) (Int32) -> Int = { _ in return 0 } /// Return a new status object. public static var NewStatus: @convention(c) () -> OpaquePointer? = { return OpaquePointer(bitPattern: 0) } /// Delete a previously created status object. public static var DeleteStatus: @convention(c) (OpaquePointer) -> Void = { _ in } /// Record <code, msg> in *s. Any previous information is lost. /// A common use is to clear a status: TF_SetStatus(s, TF_OK, ""); public static var SetStatus: @convention(c) (OpaquePointer, Int32, UnsafePointer<CChar>?) -> Void = { _, _ , _ in } /// Return the code record in *s. public static var GetCode: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } /// Return a pointer to the (null-terminated) error message in *s. The /// return value points to memory that is only usable until the next /// mutation to *s. Always returns an empty string if TF_GetCode(s) is /// TF_OK. public static var Message: @convention(c) (OpaquePointer) -> UnsafePointer<CChar>? = { _ in return UnsafePointer(bitPattern: 0) } public static var NewBufferFromString: @convention(c) (UnsafePointer<CChar>, Int) -> UnsafeMutablePointer<TF_Buffer>? = { _, _ in nil } public static var NewBuffer: @convention(c) () -> UnsafeMutablePointer<TF_Buffer>? = { return nil } public static var DeleteBuffer: @convention(c) (UnsafeMutablePointer<TF_Buffer>) -> Void = { _ in } /// TF_Tensor holds a multi-dimensional array of elements of a single data type. /// For all types other than TF_STRING, the data buffer stores elements /// in row major order. E.g. if data is treated as a vector of TF_DataType: /// /// element 0: index (0, ..., 0) /// element 1: index (0, ..., 1) /// ... /// /// The format for TF_STRING tensors is: /// start_offset: array[uint64] /// data: byte[...] /// /// The string length (as a varint), followed by the contents of the string /// is encoded at data[start_offset[i]]]. TF_StringEncode and TF_StringDecode /// facilitate this encoding. /// Return a new tensor that holds the bytes data[0,len-1]. /// /// The data will be deallocated by a subsequent call to TF_DeleteTensor via: /// (*deallocator)(data, len, deallocator_arg) /// Clients must provide a custom deallocator function so they can pass in /// memory managed by something like numpy. public static var NewTensor: @convention(c) (Int32, UnsafePointer<Int64>?, Int32, UnsafeMutablePointer<Int8>?, Int, ((UnsafeMutablePointer<Int8>?, Int, OpaquePointer?) -> Void), OpaquePointer?) -> OpaquePointer? = { _, _, _, _, _, _, _ in return nil } /// Allocate and return a new Tensor. /// /// This function is an alternative to TF_NewTensor and should be used when /// memory is allocated to pass the Tensor to the C API. The allocated memory /// satisfies TensorFlow's memory alignment preferences and should be preferred /// over calling malloc and free. /// /// The caller must set the Tensor values by writing them to the pointer returned /// by TF_TensorData with length TF_TensorByteSize. public static var AllocateTensor: @convention(c) (Int32, UnsafePointer<Int64>?, Int32, Int) -> OpaquePointer? = { _, _, _, _ in return nil } /// Destroy a tensor. public static var DeleteTensor: @convention(c) (OpaquePointer) -> Void = { _ in } /// Return the type of a tensor element. public static var TensorType: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } /// Return the number of dimensions that the tensor has. public static var NumDims: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } /// Return the length of the tensor in the "dim_index" dimension. /// REQUIRES: 0 <= dim_index < TF_NumDims(tensor) public static var Dim: @convention(c) (OpaquePointer, Int32) -> Int64 = { _, _ in return 0 } /// Return the size of the underlying data in bytes. public static var TensorByteSize: @convention(c) (OpaquePointer) -> Int = { _ in return 0 } /// Return a pointer to the underlying data buffer. public static var TensorData: @convention(c) (OpaquePointer) -> UnsafeMutableRawPointer? = { _ in return nil } /// Encode the string `src` (`src_len` bytes long) into `dst` in the format /// required by TF_STRING tensors. Does not write to memory more than `dst_len` /// bytes beyond `*dst`. `dst_len` should be at least /// TF_StringEncodedSize(src_len). /// /// On success returns the size in bytes of the encoded string. /// Returns an error into `status` otherwise. public static var StringEncode: @convention(c) (UnsafePointer<CChar>, Int, UnsafeMutablePointer<CChar>, Int, OpaquePointer) -> Int = { _, _, _, _, _ in return 0} /// Decode a string encoded using TF_StringEncode. /// /// On success, sets `*dst` to the start of the decoded string and `*dst_len` to /// its length. Returns the number of bytes starting at `src` consumed while /// decoding. `*dst` points to memory within the encoded buffer. On failure, /// `*dst` and `*dst_len` are undefined and an error is set in `status`. /// /// Does not read memory more than `src_len` bytes beyond `src`. public static var StringDecode: @convention(c) (UnsafePointer<CChar>, Int, UnsafePointer<UnsafeMutablePointer<CChar>?>, UnsafeMutablePointer<Int>, OpaquePointer) -> Int = { _, _, _, _, _ in return 0 } /// Return the size in bytes required to encode a string `len` bytes long into a /// TF_STRING tensor. public static var StringEncodedSize: @convention(c) (Int) -> Int = { _ in return 0 } /// TF_SessionOptions holds options that can be passed during session creation. public static var NewSessionOptions: @convention(c) ( ) -> OpaquePointer? = { nil } /// Set the target in TF_SessionOptions.options. /// target can be empty, a single entry, or a comma separated list of entries. /// Each entry is in one of the following formats : /// "local" /// ip:port /// host:port public static var SetTarget: @convention(c) (OpaquePointer, UnsafePointer<CChar>) -> Void = { _, _ in } /// Set the config in TF_SessionOptions.options. /// config should be a serialized tensorflow.ConfigProto proto. /// If config was not parsed successfully as a ConfigProto, record the /// error information in *status. public static var SetConfig: @convention(c) (OpaquePointer, UnsafePointer<CChar>, Int, OpaquePointer) -> Void = { _, _, _, _ in } /// Destroy an options object. public static var DeleteSessionOptions: @convention(c) (OpaquePointer) -> Void = { _ in } /// Return a new graph object. public static var NewGraph: @convention(c) ( ) -> OpaquePointer? = { return nil } /// Destroy an options object. Graph will be deleted once no more /// TFSession's are referencing it. public static var DeleteGraph: @convention(c) (OpaquePointer) -> Void = { _ in } /// Sets the shape of the Tensor referenced by `output` in `graph` to /// the shape described by `dims` and `num_dims`. /// /// If the number of dimensions is unknown, `num_dims` must be /// set to -1 and dims can be null. If a dimension is unknown, /// the corresponding entry in the `dims` array must be -1. /// /// This does not overwrite the existing shape associated with `output`, /// but merges the input shape with the existing shape. For example, /// setting a shape of [-1, 2] with an existing shape [2, -1] would set /// a final shape of [2, 2] based on shape merging semantics. // /// Returns an error into `status` if: /// * `output` is not in `graph`. /// * An invalid shape is being set (e.g., the shape being set /// is incompatible with the existing shape). public static var GraphSetTensorShape: @convention(c) (OpaquePointer, TF_Output, UnsafePointer<Int64>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Returns the number of dimensions of the Tensor referenced by `output` /// in `graph`. /// /// If the number of dimensions in the shape is unknown, returns -1. /// /// Returns an error into `status` if: /// * `output` is not in `graph`. public static var GraphGetTensorNumDims: @convention(c) (OpaquePointer, TF_Output, OpaquePointer) -> Int32 = { _, _, _ in return 0 } /// Returns the shape of the Tensor referenced by `output` in `graph` /// into `dims`. `dims` must be an array large enough to hold `num_dims` /// entries (e.g., the return value of TF_GraphGetTensorNumDims). /// /// If the number of dimensions in the shape is unknown or the shape is /// a scalar, `dims` will remain untouched. Otherwise, each element of /// `dims` will be set corresponding to the size of the dimension. An /// unknown dimension is represented by `-1`. /// /// Returns an error into `status` if: /// * `output` is not in `graph`. /// * `num_dims` does not match the actual number of dimensions. public static var GraphGetTensorShape: @convention(c) (OpaquePointer, TF_Output, UnsafeMutablePointer<Int64>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Operation will only be added to *graph when TF_FinishOperation() is /// called (assuming TF_FinishOperation() does not return an error). /// *graph must not be deleted until after TF_FinishOperation() is /// called. public static var NewOperation: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<CChar>) -> OpaquePointer? = { _, _, _ in return nil } /// Specify the device for `desc`. Defaults to empty, meaning unconstrained. public static var SetDevice: @convention(c) (OpaquePointer, UnsafePointer<CChar>) -> Void = { _, _ in } /// The calls to TF_AddInput and TF_AddInputList must match (in number, /// order, and type) the op declaration. For example, the "Concat" op /// has registration: /// REGISTER_OP("Concat") /// .Input("concat_dim: int32") /// .Input("values: N * T") /// .Output("output: T") /// .Attr("N: int >= 2") /// .Attr("T: type"); /// that defines two inputs, "concat_dim" and "values" (in that order). /// You must use TF_AddInput() for the first input (since it takes a /// single tensor), and TF_AddInputList() for the second input (since /// it takes a list, even if you were to pass a list with a single /// tensor), as in: /// TF_OperationDescription* desc = TF_NewOperation(graph, "Concat", "c"); /// TF_Output concat_dim_input = {...}; /// TF_AddInput(desc, concat_dim_input); /// TF_Output values_inputs[5] = {{...}, ..., {...}}; /// TF_AddInputList(desc, values_inputs, 5); /// /// For inputs that take a single tensor. public static var AddInput: @convention(c) (OpaquePointer, TF_Output) -> Void = { _, _ in } // For inputs that take a list of tensors. // inputs must point to TF_Output[num_inputs]. public static var AddInputList: @convention(c) (OpaquePointer, UnsafePointer<TF_Output>, Int32) -> Void = { _, _, _ in } /// Call once per control input to `desc`. public static var AddControlInput: @convention(c) (OpaquePointer, OpaquePointer) -> Void = { _, _ in } /// Request that `desc` be co-located on the device where `op` /// is placed. /// /// Use of this is discouraged since the implementation of device placement is /// subject to change. Primarily intended for public libraries public static var ColocateWith: @convention(c) (OpaquePointer, OpaquePointer) -> Void = { _, _ in } /// Call some TF_SetAttr*() function for every attr that is not /// inferred from an input and doesn't have a default value you wish to /// keep. /// /// `value` must point to a string of length `length` bytes. public static var SetAttrString: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<CChar>, Int) -> Void = { _, _, _, _ in } /// `values` and `lengths` each must have lengths `num_values`. /// `values[i]` must point to a string of length `lengths[i]` bytes. public static var SetAttrStringList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<UnsafePointer<CChar>>?, UnsafePointer<Int>?, Int32) -> Void = { _, _, _, _, _ in } public static var SetAttrInt: @convention(c) (OpaquePointer, UnsafePointer<CChar>, Int64) -> Void = { _, _, _ in } public static var SetAttrIntList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<Int64>, Int32) -> Void = { _, _, _, _ in } public static var SetAttrFloat: @convention(c) (OpaquePointer, UnsafePointer<CChar>, float_t) -> Void = { _, _, _ in } public static var SetAttrFloatList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<float_t>, Int32) -> Void = { _, _, _, _ in } public static var SetAttrBool: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UInt8) -> Void = { _, _, _ in } public static var SetAttrBoolList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<UInt8>, Int32) -> Void = { _, _, _, _ in } public static var SetAttrType: @convention(c) (OpaquePointer, UnsafePointer<CChar>, Int32) -> Void = { _, _, _ in } public static var SetAttrTypeList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<Int32>, Int32) -> Void = { _, _, _, _ in } /// Set `num_dims` to -1 to represent "unknown rank". Otherwise, /// `dims` points to an array of length `num_dims`. `dims[i]` must be /// >= -1, with -1 meaning "unknown dimension". public static var SetAttrShape: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<Int64>, Int32) -> Void = { _ , _ , _, _ in } /// `dims` and `num_dims` must point to arrays of length `num_shapes`. /// Set `num_dims[i]` to -1 to represent "unknown rank". Otherwise, /// `dims[i]` points to an array of length `num_dims[i]`. `dims[i][j]` // must be >= -1, with -1 meaning "unknown dimension". public static var SetAttrShapeList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<UnsafePointer<Int64>>, UnsafeMutablePointer<Int32>, Int32) -> Void = { _, _, _, _, _ in } /// `proto` must point to an array of `proto_len` bytes representing a /// binary-serialized TensorShapeProto. public static var SetAttrTensorShapeProto: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<CChar>, Int, OpaquePointer) -> Void = { _, _, _, _, _ in } /// `protos` and `proto_lens` must point to arrays of length `num_shapes`. /// `protos[i]` must point to an array of `proto_lens[i]` bytes /// representing a binary-serialized TensorShapeProto. public static var SetAttrTensorShapeProtoList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<UnsafePointer<CChar>>, UnsafePointer<Int>, Int32, OpaquePointer) -> Void = { _, _, _, _, _, _ in } public static var SetAttrTensor: @convention(c) (OpaquePointer, UnsafePointer<CChar>, OpaquePointer, OpaquePointer) -> Void = { _, _, _, _ in } public static var SetAttrTensorList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<OpaquePointer>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } public static var SetAttrValueProto: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafePointer<CChar>, Int, OpaquePointer) -> Void = { _, _, _, _, _ in } /// If this function succeeds: /// * *status is set to an OK value, /// * a TF_Operation is added to the graph, /// * a non-null value pointing to the added operation is returned -- /// this value is valid until the underlying graph is deleted. /// Otherwise: /// * *status is set to a non-OK value, /// * the graph is not modified, /// * a null value is returned. /// In either case, it deletes `desc`. public static var FinishOperation: @convention(c) (OpaquePointer, OpaquePointer) -> OpaquePointer = { op, _ in return op } /// TF_Operation functions. Operations are immutable once created, so /// these are all query functions. public static var OperationName: @convention(c) (OpaquePointer) -> UnsafePointer<CChar>? = { _ in return nil } public static var OperationOpType: @convention(c) (OpaquePointer) -> UnsafePointer<CChar>? = { _ in return nil } public static var OperationDevice: @convention(c) (OpaquePointer) -> UnsafePointer<CChar>? = { _ in return nil } public static var OperationNumOutputs: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } public static var OperationOutputType: @convention(c) (TF_Output) -> Int32 = { _ in return 0 } public static var OperationOutputListLength: @convention(c) (OpaquePointer, UnsafePointer<CChar>, OpaquePointer) -> Int32 = { _, _, _ in return 0 } public static var OperationNumInputs: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } public static var OperationInputType: @convention(c) (TF_Input) -> Int32 = { _ in return 0 } public static var OperationInputListLength: @convention(c) (OpaquePointer, UnsafePointer<CChar>, OpaquePointer) -> Int32 = { _, _, _ in return 0 } /// In this code: /// TF_Output producer = TF_OperationInput(consumer); /// There is an edge from producer.oper's output (given by /// producer.index) to consumer.oper's input (given by consumer.index). public static var OperationInput: @convention(c) (TF_Input) -> TF_Output = { _ in TF_Output() } /// Get the number of current consumers of a specific output of an /// operation. Note that this number can change when new operations /// are added to the graph. public static var OperationOutputNumConsumers: @convention(c) (TF_Output) -> Int32 = { _ in return 0 } /// Get list of all current consumers of a specific output of an /// operation. `consumers` must point to an array of length at least /// `max_consumers` (ideally set to /// TF_OperationOutputNumConsumers(oper_out)). Beware that a concurrent /// modification of the graph can increase the number of consumers of /// an operation. Returns the number of output consumers (should match /// TF_OperationOutputNumConsumers(oper_out)). public static var OperationOutputConsumers: @convention(c) (TF_Output, UnsafeMutablePointer<TF_Input>, Int32) -> Int32 = { _, _, _ in return 0 } /// Get the number of control inputs to an operation. public static var OperationNumControlInputs: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } /// Get list of all control inputs to an operation. `control_inputs` must /// point to an array of length `max_control_inputs` (ideally set to /// TF_OperationNumControlInputs(oper)). Returns the number of control /// inputs (should match TF_OperationNumControlInputs(oper)). public static var OperationGetControlInputs: @convention(c) (OpaquePointer, UnsafeMutablePointer<OpaquePointer>, Int32) -> Int32 = { _, _, _ in return 0 } /// Get the number of operations that have `*oper` as a control input. /// Note that this number can change when new operations are added to /// the graph. public static var OperationNumControlOutputs: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } /// Get the list of operations that have `*oper` as a control input. /// `control_outputs` must point to an array of length at least /// `max_control_outputs` (ideally set to /// TF_OperationNumControlOutputs(oper)). Beware that a concurrent /// modification of the graph can increase the number of control /// outputs. Returns the number of control outputs (should match /// TF_OperationNumControlOutputs(oper)). public static var OperationGetControlOutputs: @convention(c) (OpaquePointer, UnsafeMutablePointer<OpaquePointer>, Int32) -> Int32 = { _, _, _ in return 0 } /// Returns metadata about the value of the attribute `attr_name` of `oper`. public static var OperationGetAttrMetadata: @convention(c) (OpaquePointer, UnsafePointer<CChar>, OpaquePointer) -> TF_AttrMetadata = { _, _, _ in return TF_AttrMetadata() } /// Fills in `value` with the value of the attribute `attr_name`. `value` must /// point to an array of length at least `max_length` (ideally set to /// TF_AttrMetadata.total_size from TF_OperationGetAttrMetadata(oper, /// attr_name)). public static var OperationGetAttrString: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutableRawPointer, Int, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Get the list of strings in the value of the attribute `attr_name`. Fills in /// `values` and `lengths`, each of which must point to an array of length at /// least `max_values`. /// /// The elements of values will point to addresses in `storage` which must be at /// least `storage_size` bytes in length. Ideally, max_values would be set to /// TF_AttrMetadata.list_size and `storage` would be at least /// TF_AttrMetadata.total_size, obtained from TF_OperationGetAttrMetadata(oper, /// attr_name). /// /// Fails if storage_size is too small to hold the requested number of strings. public static var OperationGetAttrStringList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<UnsafeMutablePointer<CChar>>, UnsafeMutablePointer<Int>, Int32, UnsafeMutablePointer<CChar>, Int, OpaquePointer) -> Void = { _, _, _, _, _, _, _, _ in } public static var OperationGetAttrInt: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<Int64>, OpaquePointer) -> Void = { _, _, _, _ in } // Fills in `values` with the value of the attribute `attr_name` of `oper`. // `values` must point to an array of length at least `max_values` (ideally set // TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, // attr_name)). public static var OperationGetAttrIntList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<Int64>, Int32, OpaquePointer) -> Void = { _, _ , _, _, _ in } /// Fills in `values` with the value of the attribute `attr_name` of `oper`. /// `values` must point to an array of length at least `max_values` (ideally set /// TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, /// attr_name)). public static var OperationGetAttrFloat: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<float_t>, OpaquePointer) -> Void = { _, _, _, _ in } //// Fills in `values` with the value of the attribute `attr_name` of `oper`. /// `values` must point to an array of length at least `max_values` (ideally set /// to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, /// attr_name)). public static var OperationGetAttrFloatList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<float_t>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } public static var OperationGetAttrBool: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<UInt8>, OpaquePointer) -> Void = { _, _, _, _ in } /// Fills in `values` with the value of the attribute `attr_name` of `oper`. /// `values` must point to an array of length at least `max_values` (ideally set /// to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, /// attr_name)). public static var OperationGetAttrBoolList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<UInt8>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } public static var OperationGetAttrType: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<Int32>, OpaquePointer) -> Void = { _, _, _, _ in } /// Fills in `values` with the value of the attribute `attr_name` of `oper`. /// `values` must point to an array of length at least `max_values` (ideally set /// to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, /// attr_name)). public static var OperationGetAttrTypeList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<Int32>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Fills in `value` with the value of the attribute `attr_name` of `oper`. /// `values` must point to an array of length at least `num_dims` (ideally set to /// TF_Attr_Meta.size from TF_OperationGetAttrMetadata(oper, attr_name)). public static var OperationGetAttrShape: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<Int64>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Fills in `dims` with the list of shapes in the attribute `attr_name` of /// `oper` and `num_dims` with the corresponding number of dimensions. On return, /// for every i where `num_dims[i]` > 0, `dims[i]` will be an array of /// `num_dims[i]` elements. A value of -1 for `num_dims[i]` indicates that the /// i-th shape in the list is unknown. /// /// The elements of `dims` will point to addresses in `storage` which must be /// large enough to hold at least `storage_size` int64_ts. Ideally, `num_shapes` /// would be set to TF_AttrMetadata.list_size and `storage_size` would be set to /// TF_AttrMetadata.total_size from TF_OperationGetAttrMetadata(oper, /// attr_name). /// /// Fails if storage_size is insufficient to hold the requested shapes. public static var OperationGetAttrShapeList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<UnsafeMutablePointer<Int64>>, UnsafeMutablePointer<Int32>, Int32, UnsafeMutablePointer<Int64>, Int32, OpaquePointer) -> Void = { _, _, _, _, _, _, _, _ in } /// Sets `value` to the binary-serialized TensorShapeProto of the value of /// `attr_name` attribute of `oper`'. public static var OperationGetAttrTensorShapeProto: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<TF_Buffer>, OpaquePointer) -> Void = { _, _, _, _ in } /// Fills in `values` with binary-serialized TensorShapeProto values of the /// attribute `attr_name` of `oper`. `values` must point to an array of length at /// least `num_values` (ideally set to TF_AttrMetadata.list_size from /// TF_OperationGetAttrMetadata(oper, attr_name)). public static var OperationGetAttrTensorShapeProtoList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<UnsafeMutablePointer<TF_Buffer>>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Gets the TF_Tensor valued attribute of `attr_name` of `oper`. /// /// Allocates a new TF_Tensor which the caller is expected to take /// ownership of (and can deallocate using TF_DeleteTensor). public static var OperationGetAttrTensor: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<OpaquePointer?>, OpaquePointer) -> Void = { _, _, _, _ in } /// Fills in `values` with the TF_Tensor values of the attribute `attr_name` of /// `oper`. `values` must point to an array of TF_Tensor* of length at least /// `max_values` (ideally set to TF_AttrMetadata.list_size from /// TF_OperationGetAttrMetadata(oper, attr_name)). /// /// The caller takes ownership of all the non-null TF_Tensor* entries in `values` /// (which can be deleted using TF_DeleteTensor(values[i])). public static var OperationGetAttrTensorList: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<OpaquePointer>, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Sets `output_attr_value` to the binary-serialized AttrValue proto /// representation of the value of the `attr_name` attr of `oper`. public static var OperationGetAttrValueProto: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UnsafeMutablePointer<TF_Buffer>, OpaquePointer) -> Void = { _, _, _, _ in } /// Returns the operation in the graph with `oper_name`. Returns nullptr if /// no operation found. public static var GraphOperationByName: @convention(c) (OpaquePointer, UnsafePointer<CChar>) -> OpaquePointer? = { _, _ in return nil } /// Iterate through the operations of a graph. To use: /// size_t pos = 0; /// TF_Operation* oper; /// while ((oper = TF_GraphNextOperation(graph, &pos)) != nullptr) { /// DoSomethingWithOperation(oper); /// } public static var GraphNextOperation: @convention(c) (OpaquePointer, UnsafeMutablePointer<Int>) -> OpaquePointer? = { _, _ in return nil } /// Write out a serialized representation of `graph` (as a GraphDef protocol /// message) to `output_graph_def` (allocated by TF_NewBuffer()). /// `output_graph_def`'s underlying buffer will be freed when TF_DeleteBuffer() /// is called. /// /// May fail on very large graphs in the future. public static var GraphToGraphDef: @convention(c) (OpaquePointer, UnsafeMutablePointer<TF_Buffer>, OpaquePointer) -> Void = { _, _, _ in } /// TF_ImportGraphDefOptions holds options that can be passed to /// TF_GraphImportGraphDef. public static var NewImportGraphDefOptions: @convention(c) () -> OpaquePointer? = { return nil } public static var DeleteImportGraphDefOptions: @convention(c) (OpaquePointer) -> Void = { _ in } /// Set the prefix to be prepended to the names of nodes in `graph_def` that will /// be imported into `graph`. public static var ImportGraphDefOptionsSetPrefix: @convention(c) (OpaquePointer, UnsafePointer<CChar>) -> Void = { _, _ in } /// Set any imported nodes with input `src_name:src_index` to have that input /// replaced with `dst`. `src_name` refers to a node in the graph to be imported, /// `dst` references a node already existing in the graph being imported into. public static var ImportGraphDefOptionsAddInputMapping: @convention(c) (OpaquePointer, UnsafePointer<CChar>, Int32, TF_Output) -> Void = { _, _, _, _ in } /// Set any imported nodes with control input `src_name` to have that input /// replaced with `dst`. `src_name` refers to a node in the graph to be imported, /// `dst` references an operation already existing in the graph being imported /// into. public static var ImportGraphDefOptionsRemapControlDependency: @convention(c) (OpaquePointer, UnsafePointer<CChar>, OpaquePointer) -> Void = { _, _, _ in } /// Cause the imported graph to have a control dependency on `oper`. `oper` /// should exist in the graph being imported into. public static var ImportGraphDefOptionsAddControlDependency: @convention(c) (OpaquePointer, OpaquePointer) -> Void = { _, _ in } /// Add an output in `graph_def` to be returned via the `return_outputs` output /// parameter of TF_GraphImportGraphDef(). If the output is remapped via an input /// mapping, the corresponding existing tensor in `graph` will be returned. public static var ImportGraphDefOptionsAddReturnOutput: @convention(c) (OpaquePointer, UnsafePointer<CChar>, Int32) -> Void = { _, _, _ in } /// Returns the number of return outputs added via /// TF_ImportGraphDefOptionsAddReturnOutput(). public static var ImportGraphDefOptionsNumReturnOutputs: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } /// Import the graph serialized in `graph_def` into `graph`. /// /// `num_return_outputs` must be the number of return outputs added (i.e. the /// result of TF_ImportGraphDefOptionsNumReturnOutputs()). If /// `num_return_outputs` is non-zero, `return_outputs` must be of length /// `num_return_outputs`. Otherwise it can be null. public static var GraphImportGraphDefWithReturnOutputs: @convention(c) (OpaquePointer, UnsafePointer<TF_Buffer>, OpaquePointer, UnsafeMutablePointer<TF_Output>, Int32, OpaquePointer) -> Void = { _, _, _, _, _, _ in } /// Import the graph serialized in `graph_def` into `graph`. /// Convenience function for when no return outputs have been added. public static var GraphImportGraphDef: @convention(c) (OpaquePointer, UnsafePointer<TF_Buffer>, OpaquePointer, OpaquePointer) -> Void = { _, _, _, _ in } /// Note: The following function may fail on very large protos in the future. public static var OperationToNodeDef: @convention(c) (OpaquePointer, UnsafeMutablePointer<TF_Buffer>, OpaquePointer) -> Void = { _, _, _ in } /// Creates a TF_WhileParams for creating a while loop in `g`. `inputs` are /// outputs that already exist in `g` used as initial values for the loop /// variables. /// /// The returned TF_WhileParams will have all fields initialized except /// `cond_output`, `body_outputs`, and `name`. The `body_outputs` buffer will be /// allocated to size `ninputs`. The caller should build `cond_graph` and /// `body_graph` starting from the inputs, and store the final outputs in /// `cond_output` and `body_outputs`. /// /// If `status` is OK, the caller must call either TF_FinishWhile or /// TF_AbortWhile on the returned TF_WhileParams. If `status` isn't OK, the /// returned TF_WhileParams is not valid, and the caller should not call /// TF_FinishWhile() or TF_AbortWhile(). /// /// Missing functionality (TODO): /// - Gradients (not yet implmented for any ops) /// - Reference-type inputs /// - Directly referencing external tensors from the cond/body graphs (this is /// possible in the Python API) public static var NewWhile: @convention(c) (OpaquePointer, UnsafePointer<TF_Output>, Int32, OpaquePointer) -> TF_WhileParams = { _, _, _, _ in return TF_WhileParams() } /// Builds the while loop specified by `params` and returns the output tensors of /// the while loop in `outputs`. `outputs` should be allocated to size /// `params.ninputs`. /// /// `params` is no longer valid once this returns. /// /// Either this or TF_AbortWhile() must be called after a successful /// TF_NewWhile() call. public static var FinishWhile: @convention(c) (UnsafePointer<TF_WhileParams>, OpaquePointer, UnsafeMutablePointer<TF_Output>) -> Void = { _, _, _ in } /// Frees `params`s resources without building a while loop. `params` is no /// longer valid after this returns. Either this or TF_FinishWhile() must be /// called after a successful TF_NewWhile() call. public static var AbortWhile: @convention(c) (UnsafePointer<TF_WhileParams>) -> Void = { _ in } /// Adds operations to compute the partial derivatives of sum of `y`s w.r.t `x`s, /// i.e., d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2... /// `dx` are used as initial gradients (which represent the symbolic partial /// derivatives of some loss function `L` w.r.t. `y`). /// `dx` must be nullptr or have size `ny`. /// If `dx` is nullptr, the implementation will use dx of `OnesLike` for all /// shapes in `y`. /// The partial derivatives are returned in `dy`. `dy` should be allocated to /// size `nx`. /// /// WARNING: This function does not yet support all the gradients that python /// supports. See /// https://www.tensorflow.org/code/tensorflow/cc/gradients/README.md /// for instructions on how to add C++ more gradients. public static var AddGradients: @convention(c) (OpaquePointer, UnsafePointer<TF_Output>?, Int32, UnsafePointer<TF_Output>?, Int32, UnsafePointer<TF_Output>?, OpaquePointer, UnsafeMutablePointer<TF_Output>?) -> Void = { _, _, _, _, _, _, _, _ in } /// Return a new execution session with the associated graph, or NULL on error. /// /// *graph must be a valid graph (not deleted or nullptr). This function will /// prevent the graph from being deleted until TF_DeleteSession() is called. /// Does not take ownership of opts. public static var NewSession: @convention(c) (OpaquePointer, OpaquePointer, OpaquePointer) -> OpaquePointer? = { _, _, _ in return nil } /// This function creates a new TF_Session (which is created on success) using /// `session_options`, and then initializes state (restoring tensors and other /// assets) using `run_options`. /// /// Any NULL and non-NULL value combinations for (`run_options, `meta_graph_def`) /// are valid. /// /// - `export_dir` must be set to the path of the exported SavedModel. /// - `tags` must include the set of tags used to identify one MetaGraphDef in /// the SavedModel. /// - `graph` must be a graph newly allocated with TF_NewGraph(). /// /// If successful, populates `graph` with the contents of the Graph and /// `meta_graph_def` with the MetaGraphDef of the loaded model. public static var LoadSessionFromSavedModel: @convention(c) (OpaquePointer, UnsafePointer<TF_Buffer>, UnsafePointer<CChar>, UnsafePointer<UnsafeMutablePointer<CChar>?>, Int32, OpaquePointer, UnsafeMutablePointer<TF_Buffer>, OpaquePointer) -> OpaquePointer? = { _, _, _, _, _, _, _, _ in return nil } /// Close a session. /// /// Contacts any other processes associated with the session, if applicable. /// May not be called after TF_DeleteSession(). public static var CloseSession: @convention(c) (OpaquePointer, OpaquePointer) -> Void = { _, _ in } /// Destroy a session object. /// /// Even if error information is recorded in *status, this call discards all /// local resources associated with the session. The session may not be used /// during or after this call (and the session drops its reference to the /// corresponding graph). public static var DeleteSession: @convention(c) (OpaquePointer, OpaquePointer) -> Void = { _, _ in } /// Run the graph associated with the session starting with the supplied inputs /// (inputs[0,ninputs-1] with corresponding values in input_values[0,ninputs-1]). /// /// Any NULL and non-NULL value combinations for (`run_options`, /// `run_metadata`) are valid. /// /// - `run_options` may be NULL, in which case it will be ignored; or /// non-NULL, in which case it must point to a `TF_Buffer` containing the /// serialized representation of a `RunOptions` protocol buffer. /// - `run_metadata` may be NULL, in which case it will be ignored; or /// non-NULL, in which case it must point to an empty, freshly allocated /// `TF_Buffer` that may be updated to contain the serialized representation /// of a `RunMetadata` protocol buffer. /// /// The caller retains ownership of `input_values` (which can be deleted using /// TF_DeleteTensor). The caller also retains ownership of `run_options` and/or /// `run_metadata` (when not NULL) and should manually call TF_DeleteBuffer on /// them. /// /// On success, the tensors corresponding to outputs[0,noutputs-1] are placed in /// output_values[]. Ownership of the elements of output_values[] is transferred /// to the caller, which must eventually call TF_DeleteTensor on them. /// /// On failure, output_values[] contains NULLs. public static var SessionRun: @convention(c) (OpaquePointer, UnsafePointer<TF_Buffer>?, UnsafePointer<TF_Output>?, UnsafePointer<OpaquePointer>?, Int32, UnsafePointer<TF_Output>?, UnsafeMutablePointer<OpaquePointer>?, Int32, UnsafePointer<OpaquePointer>?, Int32, UnsafeMutablePointer<TF_Buffer>?, OpaquePointer) -> Void = { _, _, _, _, _, _, _, _, _, _, _, _ in } /// Lists all devices in a TF_Session. /// /// Caller takes ownership of the returned TF_DeviceList* which must eventually /// be freed with a call to TF_DeleteDeviceList. public static var SessionListDevices: @convention(c) (OpaquePointer, OpaquePointer) -> OpaquePointer? = { _, _ in return nil } /// Deallocates the device list. public static var DeleteDeviceList: @convention(c) (OpaquePointer) -> Void = { _ in} /// Counts the number of elements in the device list. public static var DeviceListCount: @convention(c) (OpaquePointer) -> Int32 = { _ in return 0 } /// Retrieves the full name of the device (e.g. /job:worker/replica:0/...) /// The return value will be a pointer to a null terminated string. The caller /// must not modify or delete the string. It will be deallocated upon a call to /// TF_DeleteDeviceList. /// /// If index is out of bounds, an error code will be set in the status object, /// and a null pointer will be returned. public static var DeviceListName: @convention(c) (OpaquePointer, Int32, OpaquePointer) -> UnsafePointer<CChar>? = { _, _, _ in return nil } /// Retrieves the type of the device at the given index. /// /// The caller must not modify or delete the string. It will be deallocated upon /// a call to TF_DeleteDeviceList. /// /// If index is out of bounds, an error code will be set in the status object, /// and a null pointer will be returned. public static var DeviceListType: @convention(c) (OpaquePointer, Int32, OpaquePointer) -> UnsafePointer<CChar>? = { _, _, _ in return nil } /// Retrieve the amount of memory associated with a given device. /// /// If index is out of bounds, an error code will be set in the status object, /// and -1 will be returned. public static var DeviceListMemoryBytes: @convention(c) (OpaquePointer, Int32, OpaquePointer) -> Int64 = { _, _, _ in return 0 } /// Set up the graph with the intended feeds (inputs) and fetches (outputs) for a /// sequence of partial run calls. /// /// On success, returns a handle that is used for subsequent PRun calls. The /// handle should be deleted with TF_DeletePRunHandle when it is no longer /// needed. /// /// On failure, out_status contains a tensorflow::Status with an error /// message. /// NOTE: This is EXPERIMENTAL and subject to change. public static var SessionPRunSetup: @convention(c) (OpaquePointer, UnsafePointer<TF_Output>?, Int32, UnsafePointer<TF_Output>?, Int32, UnsafePointer<OpaquePointer>?, Int32, UnsafePointer<UnsafeMutablePointer<CChar>?>, OpaquePointer) -> Void = { _, _, _, _, _, _, _, _, _ in } /// Continue to run the graph with additional feeds and fetches. The /// execution state is uniquely identified by the handle. /// NOTE: This is EXPERIMENTAL and subject to change. public static var SessionPRun: @convention(c) (OpaquePointer, UnsafeMutablePointer<CChar>, UnsafePointer<TF_Output>?, UnsafePointer<OpaquePointer>?, Int32, UnsafePointer<TF_Output>?, UnsafeMutablePointer<OpaquePointer>?, Int32, UnsafePointer<OpaquePointer>?, Int32, OpaquePointer) -> Void = { _, _, _, _, _, _, _, _, _, _, _ in } /// Deletes a handle allocated by TF_SessionPRunSetup. /// Once called, no more calls to TF_SessionPRun should be made. public static var DeletePRunHandle: @convention(c) (UnsafePointer<CChar>) -> Void = { _ in } /// Load the library specified by library_filename and register the ops and /// kernels present in that library. /// /// Pass "library_filename" to a platform-specific mechanism for dynamically /// loading a library. The rules for determining the exact location of the /// library are platform-specific and are not documented here. /// /// On success, place OK in status and return the newly created library handle. /// The caller owns the library handle. /// /// On failure, place an error status in status and return NULL. public static var LoadLibrary: @convention(c) (UnsafePointer<CChar>, OpaquePointer) -> OpaquePointer? = { _, _ in return nil } /// Get the OpList of OpDefs defined in the library pointed by lib_handle. /// /// Returns a TF_Buffer. The memory pointed to by the result is owned by /// lib_handle. The data in the buffer will be the serialized OpList proto for /// ops defined in the library. public static var GetOpList: @convention(c) (OpaquePointer) -> TF_Buffer = { _ in TF_Buffer() } /// Frees the memory associated with the library handle. /// Does NOT unload the library. public static var DeleteLibraryHandle: @convention(c) (OpaquePointer) -> Void = { _ in } /// Get the OpList of all OpDefs defined in this address space. /// Returns a TF_Buffer, ownership of which is transferred to the caller /// (and can be freed using TF_DeleteBuffer). /// /// The data in the buffer will be the serialized OpList proto for ops registered /// in this address space. public static var GetAllOpList: @convention(c) () -> UnsafeMutablePointer<TF_Buffer>? = { return nil } /// Adds a copy of function `func` and optionally its gradient function `grad` /// to `g`. Once `func`/`grad` is added to `g`, it can be called by creating // an operation using the function's name. /// Any changes to `func`/`grad` (including deleting it) done after this method /// returns, won't affect the copy of `func`/`grad` in `g`. /// If `func` or `grad` are already in `g`, TF_GraphCopyFunction has no /// effect on them, but can establish the function->gradient relationship /// between them if `func` does not already have a gradient. If `func` already /// has a gradient different from `grad`, an error is returned. /// /// `func` must not be null. /// If `grad` is null and `func` is not in `g`, `func` is added without a /// gradient. /// If `grad` is null and `func` is in `g`, TF_GraphCopyFunction is a noop. /// `grad` must have appropriate signature as described in the doc of /// GradientDef in tensorflow/core/framework/function.proto. /// /// If successful, status is set to OK and `func` and `grad` are added to `g`. /// Otherwise, status is set to the encountered error and `g` is unmodified. public static var GraphCopyFunction: @convention(c) (OpaquePointer, OpaquePointer, OpaquePointer?, OpaquePointer) -> Void = { _, _, _, _ in } /// Create a TF_Function from a TF_Graph /// /// Params: /// fn_body - the graph whose operations (or subset of whose operations) will be /// converted to TF_Function. /// fn_name - the name of the new TF_Function. Should match the operation /// name (OpDef.name) regexp [A-Z][A-Za-z0-9_.\\-/]* and be distinct /// from other operation names (at least those registered in graphs /// where this function will be used). /// TODO(iga): Allow null in here and have C API come up with /// a unique name with high probability (similarly to /// _create_hash_str in function.py) /// num_opers - `num_opers` contains the number of elements in the `opers` array /// or a special value of -1 meaning that no array is given. /// The distinction between an empty array of operations and no /// array of operations is necessary to distinguish the case of /// creating a function with no body (e.g. identity or permutation) /// and the case of creating a function whose body contains all /// the nodes in the graph (except for the automatic skipping, see /// below). /// opers - Array of operations to become the body of the function or null. /// - If no array is given (`num_opers` = -1), all the /// operations in `fn_body` will become part of the function /// except operations referenced in `inputs`. These operations /// must have a single output (these operations are typically /// placeholders created for the sole purpose of representing /// an input. We can relax this constraint if there are /// compelling use cases). /// - If an array is given (`num_opers` >= 0), all operations /// in it will become part of the function. In particular, no /// automatic skipping of dummy input operations is performed. /// ninputs - number of elements in `inputs` array /// inputs - array of TF_Outputs that specify the inputs to the function. /// If `ninputs` is zero (the function takes no inputs), `inputs` /// can be null. The names used for function inputs are normalized /// names of the operations (usually placeholders) pointed to by /// `inputs`. These operation names should start with a letter. /// Normalization will convert all letters to lowercase and /// non-alphanumeric characters to '_' to make resulting names match /// the "[a-z][a-z0-9_]*" pattern for operation argument names. /// `inputs` cannot contain the same tensor twice. /// noutputs - number of elements in `outputs` array /// outputs - array of TF_Outputs that specify the outputs of the function. /// If `noutputs` is zero (the function returns no outputs), `outputs` /// can be null. `outputs` can contain the same tensor more than once. /// output_names - The names of the function's outputs. `output_names` array /// must either have the same length as `outputs` /// (i.e. `noutputs`) or be null. In the former case, /// the names should match the regular expression for ArgDef /// names - "[a-z][a-z0-9_]*". In the latter case, /// names for outputs will be generated automatically. /// opts - various options for the function, e.g. XLA's inlining control. /// status - Set to OK on success and an appropriate error on failure. /// /// Note that when the same TF_Output is listed as both an input and an output, /// the corresponding function's output will equal to this input, /// instead of the original node's output. /// /// Callers must also satisfy the following constraints: /// - `inputs` cannot refer to TF_Outputs within a control flow context. For /// example, one cannot use the output of "switch" node as input. /// - No TF_Output of a function (inside any of `inputs`, `outputs`, `fn_body`) /// is allowed to have a reference type. Reference types are not exposed /// through C API and are being deprecated. /// - Every node in the function's body must have all of its inputs (including /// control inputs). In other words, for every node in the body, each input /// must be either listed in `inputs` or must come from another node in /// the body. In particular, it is an error to have a control edge going from /// a node outside of the body into a node in the body. This applies to control /// edges going from nodes referenced in `inputs` to nodes in the body when /// the former nodes are not in the body (automatically skipped or not /// included in explicitly specified body). /// /// Returns: /// On successful, a newly created TF_Function instance. It must be deleted by /// calling TF_DeleteFunction. /// /// On failure, null. /// /// TODO(iga): Add input_names argument and get output_names working (they are /// currently ignored) public static var GraphToFunction: @convention(c) (OpaquePointer, UnsafePointer<CChar>, UInt8, Int32, UnsafePointer<OpaquePointer?>?, Int32, UnsafePointer<TF_Output>?, Int32, UnsafePointer<TF_Output>?, UnsafePointer<UnsafePointer<CChar>?>?, OpaquePointer?, UnsafePointer<CChar>?, OpaquePointer) -> OpaquePointer? = { _, _, _, _, _, _, _, _, _, _, _, _, _ in return nil} /// Write out a serialized representation of `func` (as a FunctionDef protocol /// message) to `output_func_def` (allocated by TF_NewBuffer()). /// `output_func_def`'s underlying buffer will be freed when TF_DeleteBuffer() /// is called. /// /// May fail on very large graphs in the future. public static var FunctionToFunctionDef: @convention(c) (OpaquePointer, UnsafeMutablePointer<TF_Buffer>?, OpaquePointer) -> Void = { _, _, _ in } /// Construct and return the function whose FunctionDef representation is /// serialized in `proto`. `proto_len` must equal the number of bytes /// pointed to by `proto`. /// Returns: /// On success, a newly created TF_Function instance. It must be deleted by /// calling TF_DeleteFunction. /// /// On failure, null. public static var FunctionImportFunctionDef: @convention(c) (UnsafeRawPointer?, Int32, OpaquePointer) -> OpaquePointer? = { _, _, _ in return nil} /// Sets function attribute named `attr_name` to value stored in `proto`. /// If this attribute is already set to another value, it is overridden. /// `proto` should point to a sequence of bytes of length `proto_len` /// representing a binary serialization of an AttrValue protocol /// buffer. public static var FunctionSetAttrValueProto: @convention(c) (OpaquePointer?, UnsafePointer<CChar>?, UnsafeRawPointer?, Int32, OpaquePointer) -> Void = { _, _, _, _, _ in } /// Sets `output_attr_value` to the binary-serialized AttrValue proto /// representation of the value of the `attr_name` attr of `func`. /// If `attr_name` attribute is not present, status is set to an error. public static var FunctionGetAttrValueProto: @convention(c) (OpaquePointer?, UnsafePointer<CChar>?, UnsafePointer<TF_Buffer>?, OpaquePointer) -> Void = { _, _, _, _ in } /// Frees the memory used by the `func` struct. /// TF_DeleteFunction is a noop if `func` is null. /// Deleting a function does not remove it from any graphs it was copied to. public static var DeleteFunction: @convention(c) (OpaquePointer?) -> Void = { _ in } /// Fetches any input mappings requested via /// TF_ImportGraphDefOptionsAddInputMapping() that didn't appear in the GraphDef /// and weren't used as input to any node in the imported graph def. The number /// of fetched mappings is returned in `num_missing_unused_input_mappings`. The /// array of each mapping's source node name is returned in `src_names`, and the /// array of each mapping's source index is returned in `src_indexes`. /// `*src_names`, `*src_indexes`, and the memory backing each string in /// `src_names` are owned by and have the lifetime of `results`. public static var ImportGraphDefResultsMissingUnusedInputMappings: @convention(c) (OpaquePointer?, UnsafeMutablePointer<Int32>?, UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>>?>, UnsafeMutablePointer<UnsafeMutablePointer<Int32>?>?) -> Void = { _, _, _, _ in } /// Import the graph serialized in `graph_def` into `graph`. Returns nullptr and /// a bad status on error. Otherwise, returns a populated /// TF_ImportGraphDefResults instance. The returned instance must be deleted via /// TF_DeleteImportGraphDefResults(). public static var GraphImportGraphDefWithResults: @convention(c) (OpaquePointer?, UnsafeMutablePointer<TF_Buffer>?, OpaquePointer?, OpaquePointer?) -> OpaquePointer? = { _, _, _, _ in return nil} /// Deletes a results object returned by TF_GraphImportGraphDefWithResults(). public static var DeleteImportGraphDefResults: @convention(c) (OpaquePointer?) -> Void = { _ in } /// Set whether to uniquify imported operation names. If true, imported operation /// names will be modified if their name already exists in the graph. If false, /// conflicting names will be treated as an error. Note that this option has no /// effect if a prefix is set, since the prefix will guarantee all names are /// unique. Defaults to false. /// TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsSetUniquifyNames( /// TF_ImportGraphDefOptions* opts, unsigned char uniquify_names); public static var ImportGraphDefOptionsSetUniquifyNames: @convention(c) (OpaquePointer, UInt8) -> Void = { _, _ in } /// If true, the specified prefix will be modified if it already exists as an /// operation name or prefix in the graph. If false, a conflicting prefix will be /// treated as an error. This option has no effect if no prefix is specified. /// TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsSetUniquifyPrefix( /// TF_ImportGraphDefOptions* opts, unsigned char uniquify_prefix); public static var ImportGraphDefOptionsSetUniquifyPrefix: @convention(c) (OpaquePointer, UInt8) -> Void = { _, _ in } /// Creates a new TF_ApiDefMap instance /// op_list_buffer - TF_Buffer instance containing serialized OpList /// https://www.tensorflow.org/code/tensorflow/core/framework/op_def.proto /// for the OpList proto definition. public static var NewApiDefMap: @convention(c) (UnsafePointer<TF_Buffer>?, OpaquePointer?) -> OpaquePointer? = { _, _ in return nil } /// Deallocates a TF_ApiDefMap. public static var DeleteApiDefMap: @convention(c) (OpaquePointer?) -> Void = { _ in } /// Add ApiDefs to the map. /// /// `text` corresponds to a text representation of an ApiDefs protocol message. /// (https://www.tensorflow.org/code/tensorflow/core/framework/api_def.proto). /// /// The provided ApiDefs will be merged with existing ones in the map, with /// precedence given to the newly added version in case of conflicts with /// previous calls to TF_ApiDefMapPut. public static var ApiDefMapPut: @convention(c) (OpaquePointer?, UnsafePointer<CChar>, Int32, OpaquePointer?) -> Void = { _, _, _, _ in } /// Returns a serialized ApiDef protocol buffer for the TensorFlow operation public static var ApiDefMapGet: @convention(c) (OpaquePointer?, UnsafePointer<CChar>, Int32, OpaquePointer?) -> UnsafeMutablePointer<TF_Buffer>? = { _, _, _, _ in return nil } /// Set a 'func' attribute to the specified name. /// `value` must point to a string of length `length` bytes. public static var SetAttrFuncName: @convention(c) (OpaquePointer?, UnsafePointer<CChar>, UnsafePointer<CChar>, Int32) -> Void = { _, _, _, _ in } /// Returns the number of TF_Functions registered in `g`. public static var GraphNumFunctions: @convention(c) (OpaquePointer?) -> Int32 = { _ in return 0 } /// Fills in `funcs` with the TF_Function* registered in `g`. /// `funcs` must point to an array of TF_Function* of length at least /// `max_func`. In usual usage, max_func should be set to the result of /// TF_GraphNumFunctions(g). In this case, all the functions registered in /// `g` will be returned. Else, an unspecified subset. /// /// If successful, returns the number of TF_Function* successfully set in /// `funcs` and sets status to OK. The caller takes ownership of /// all the returned TF_Functions. They must be deleted with TF_DeleteFunction. /// On error, returns 0, sets status to the encountered error, and the contents /// of funcs will be undefined. //TF_CAPI_EXPORT extern int TF_GraphGetFunctions(TF_Graph* g, TF_Function** funcs, // int max_func, TF_Status* status); public static var GraphGetFunctions: @convention(c) (OpaquePointer?, UnsafeMutablePointer<OpaquePointer?>?, Int32, OpaquePointer?) -> Int32 = { _, _, _, _ in return 0} /// Bootstrap of tensorflow library open, **MUST BE CALL BEFORE ANY OPERATIONS** /// - parameters /// - library: the installation path of library TensorFlow for C, /usr/local/lib/libtensorflow.so by default /// - throws: Panic public static func Open (_ library: String = "/usr/local/lib/libtensorflow.so") throws { guard let lib = dlopen(library, RTLD_NOW) else { throw Panic.DLL(reason: String(cString: dlerror())) }//end lib libDLL = lib Version = try LoadFunction(lib, "TF_Version") guard let v = Version() else { throw Panic.DLL(reason: "Unresoved version info") } let ver = String(cString: v) guard ver >= "1.1.0" else { throw Panic.DLL(reason: "Version \(ver) is obsolete and out of support.") } if ver >= "1.6.0" { NewApiDefMap = try LoadFunction(lib, "TF_NewApiDefMap") DeleteApiDefMap = try LoadFunction(lib, "TF_DeleteApiDefMap") ApiDefMapPut = try LoadFunction(lib, "TF_ApiDefMapPut") ApiDefMapGet = try LoadFunction(lib, "TF_ApiDefMapGet") SetAttrFuncName = try LoadFunction(lib, "TF_SetAttrFuncName") GraphNumFunctions = try LoadFunction(lib, "TF_GraphNumFunctions") GraphGetFunctions = try LoadFunction(lib, "TF_GraphGetFunctions") } if ver >= "1.5.0" { GraphImportGraphDefWithResults = try LoadFunction(lib, "TF_GraphImportGraphDefWithResults") DeleteImportGraphDefResults = try LoadFunction(lib, "TF_DeleteImportGraphDefResults") ImportGraphDefResultsMissingUnusedInputMappings = try LoadFunction(lib, "TF_ImportGraphDefResultsMissingUnusedInputMappings") ImportGraphDefOptionsSetUniquifyNames = try LoadFunction(lib, "TF_ImportGraphDefOptionsSetUniquifyNames") ImportGraphDefOptionsSetUniquifyPrefix = try LoadFunction(lib, "TF_ImportGraphDefOptionsSetUniquifyPrefix") } if ver >= "1.4.0" { GraphCopyFunction = try LoadFunction(lib, "TF_GraphCopyFunction") GraphToFunction = try LoadFunction(lib, "TF_GraphToFunction") FunctionToFunctionDef = try LoadFunction(lib, "TF_FunctionToFunctionDef") FunctionImportFunctionDef = try LoadFunction(lib, "TF_FunctionImportFunctionDef") FunctionSetAttrValueProto = try LoadFunction(lib, "TF_FunctionSetAttrValueProto") FunctionGetAttrValueProto = try LoadFunction(lib, "TF_FunctionGetAttrValueProto") DeleteFunction = try LoadFunction(lib, "TF_DeleteFunction") } if ver >= "1.2.1" { SessionListDevices = try LoadFunction(lib, "TF_SessionListDevices") DeleteDeviceList = try LoadFunction(lib, "TF_DeleteDeviceList") DeviceListCount = try LoadFunction(lib, "TF_DeviceListCount") DeviceListName = try LoadFunction(lib, "TF_DeviceListName") DeviceListType = try LoadFunction(lib, "TF_DeviceListType") DeviceListMemoryBytes = try LoadFunction(lib, "TF_DeviceListMemoryBytes") } if ver >= "1.2.0" { AddGradients = try LoadFunction(lib, "TF_AddGradients") } SetAttrValueProto = try LoadFunction(lib, "TF_SetAttrValueProto") GetAllOpList = try LoadFunction(lib, "TF_GetAllOpList") DeleteLibraryHandle = try LoadFunction(lib, "TF_DeleteLibraryHandle") GetOpList = try LoadFunction(lib, "TF_GetOpList") LoadLibrary = try LoadFunction(lib, "TF_LoadLibrary") DeletePRunHandle = try LoadFunction(lib, "TF_DeletePRunHandle") SessionPRun = try LoadFunction(lib, "TF_SessionPRun") SessionPRunSetup = try LoadFunction(lib, "TF_SessionPRunSetup") SessionRun = try LoadFunction(lib, "TF_SessionRun") DeleteSession = try LoadFunction(lib, "TF_DeleteSession") CloseSession = try LoadFunction(lib, "TF_CloseSession") LoadSessionFromSavedModel = try LoadFunction(lib, "TF_LoadSessionFromSavedModel") NewSession = try LoadFunction(lib, "TF_NewSession") AbortWhile = try LoadFunction(lib, "TF_AbortWhile") FinishWhile = try LoadFunction(lib, "TF_FinishWhile") NewWhile = try LoadFunction(lib, "TF_NewWhile") OperationToNodeDef = try LoadFunction(lib, "TF_OperationToNodeDef") GraphImportGraphDef = try LoadFunction(lib, "TF_GraphImportGraphDef") GraphImportGraphDefWithReturnOutputs = try LoadFunction(lib, "TF_GraphImportGraphDefWithReturnOutputs") ImportGraphDefOptionsNumReturnOutputs = try LoadFunction(lib, "TF_ImportGraphDefOptionsNumReturnOutputs") ImportGraphDefOptionsAddReturnOutput = try LoadFunction(lib, "TF_ImportGraphDefOptionsAddReturnOutput") ImportGraphDefOptionsAddControlDependency = try LoadFunction(lib, "TF_ImportGraphDefOptionsAddControlDependency") ImportGraphDefOptionsRemapControlDependency = try LoadFunction(lib, "TF_ImportGraphDefOptionsRemapControlDependency") ImportGraphDefOptionsAddInputMapping = try LoadFunction(lib, "TF_ImportGraphDefOptionsAddInputMapping") ImportGraphDefOptionsSetPrefix = try LoadFunction(lib, "TF_ImportGraphDefOptionsSetPrefix") DeleteImportGraphDefOptions = try LoadFunction(lib, "TF_DeleteImportGraphDefOptions") NewImportGraphDefOptions = try LoadFunction(lib, "TF_NewImportGraphDefOptions") GraphToGraphDef = try LoadFunction(lib, "TF_GraphToGraphDef") GraphNextOperation = try LoadFunction(lib, "TF_GraphNextOperation") GraphOperationByName = try LoadFunction(lib, "TF_GraphOperationByName") OperationGetAttrValueProto = try LoadFunction(lib, "TF_OperationGetAttrValueProto") OperationGetAttrTensorList = try LoadFunction(lib, "TF_OperationGetAttrTensorList") OperationGetAttrTensor = try LoadFunction(lib, "TF_OperationGetAttrTensor") OperationGetAttrTensorShapeProtoList = try LoadFunction(lib, "TF_OperationGetAttrTensorShapeProtoList") OperationGetAttrTensorShapeProto = try LoadFunction(lib, "TF_OperationGetAttrTensorShapeProto") OperationGetAttrShapeList = try LoadFunction(lib, "TF_OperationGetAttrShapeList") OperationGetAttrShape = try LoadFunction(lib, "TF_OperationGetAttrShape") OperationGetAttrTypeList = try LoadFunction(lib, "TF_OperationGetAttrTypeList") OperationGetAttrType = try LoadFunction(lib, "TF_OperationGetAttrType") OperationGetAttrBoolList = try LoadFunction(lib, "TF_OperationGetAttrBoolList") OperationGetAttrBool = try LoadFunction(lib, "TF_OperationGetAttrBool") OperationGetAttrFloatList = try LoadFunction(lib, "TF_OperationGetAttrFloatList") OperationGetAttrFloat = try LoadFunction(lib, "TF_OperationGetAttrFloat") OperationGetAttrInt = try LoadFunction(lib, "TF_OperationGetAttrInt") OperationGetAttrStringList = try LoadFunction(lib, "TF_OperationGetAttrStringList") OperationGetAttrString = try LoadFunction(lib, "TF_OperationGetAttrString") OperationGetAttrMetadata = try LoadFunction(lib, "TF_OperationGetAttrMetadata") OperationGetControlOutputs = try LoadFunction(lib, "TF_OperationGetControlOutputs") OperationNumControlOutputs = try LoadFunction(lib, "TF_OperationNumControlOutputs") OperationGetControlInputs = try LoadFunction(lib, "TF_OperationGetControlInputs") OperationNumControlInputs = try LoadFunction(lib, "TF_OperationNumControlInputs") OperationOutputConsumers = try LoadFunction(lib, "TF_OperationOutputConsumers") OperationOutputNumConsumers = try LoadFunction(lib, "TF_OperationOutputNumConsumers") OperationInput = try LoadFunction(lib, "TF_OperationInput") OperationInputListLength = try LoadFunction(lib, "TF_OperationInputListLength") OperationInputType = try LoadFunction(lib, "TF_OperationInputType") OperationNumInputs = try LoadFunction(lib, "TF_OperationNumInputs") OperationOutputListLength = try LoadFunction(lib, "TF_OperationOutputListLength") OperationOutputType = try LoadFunction(lib, "TF_OperationOutputType") OperationNumOutputs = try LoadFunction(lib, "TF_OperationNumOutputs") OperationDevice = try LoadFunction(lib, "TF_OperationDevice") OperationOpType = try LoadFunction(lib, "TF_OperationOpType") OperationName = try LoadFunction(lib, "TF_OperationName") FinishOperation = try LoadFunction(lib, "TF_FinishOperation") SetAttrTensorList = try LoadFunction(lib, "TF_SetAttrTensorList") SetAttrTensor = try LoadFunction(lib, "TF_SetAttrTensor") SetAttrTensorShapeProtoList = try LoadFunction(lib, "TF_SetAttrTensorShapeProtoList") SetAttrTensorShapeProto = try LoadFunction(lib, "TF_SetAttrTensorShapeProto") SetAttrShapeList = try LoadFunction(lib, "TF_SetAttrShapeList") SetAttrShape = try LoadFunction(lib, "TF_SetAttrShape") SetAttrTypeList = try LoadFunction(lib, "TF_SetAttrTypeList") SetAttrType = try LoadFunction(lib, "TF_SetAttrType") SetAttrBoolList = try LoadFunction(lib, "TF_SetAttrBoolList") SetAttrBool = try LoadFunction(lib, "TF_SetAttrBool") SetAttrFloatList = try LoadFunction(lib, "TF_SetAttrFloatList") SetAttrFloat = try LoadFunction(lib, "TF_SetAttrFloat") SetAttrIntList = try LoadFunction(lib, "TF_SetAttrIntList") SetAttrInt = try LoadFunction(lib, "TF_SetAttrInt") SetAttrStringList = try LoadFunction(lib, "TF_SetAttrStringList") SetAttrString = try LoadFunction(lib, "TF_SetAttrString") ColocateWith = try LoadFunction(lib, "TF_ColocateWith") AddControlInput = try LoadFunction(lib, "TF_AddControlInput") AddInputList = try LoadFunction(lib, "TF_AddInputList") AddInput = try LoadFunction(lib, "TF_AddInput") SetDevice = try LoadFunction(lib, "TF_SetDevice") NewOperation = try LoadFunction(lib, "TF_NewOperation") GraphGetTensorShape = try LoadFunction(lib, "TF_GraphGetTensorShape") GraphGetTensorNumDims = try LoadFunction(lib, "TF_GraphGetTensorNumDims") GraphSetTensorShape = try LoadFunction(lib, "TF_GraphSetTensorShape") DeleteGraph = try LoadFunction(lib, "TF_DeleteGraph") NewGraph = try LoadFunction(lib, "TF_NewGraph") DeleteSessionOptions = try LoadFunction(lib, "TF_DeleteSessionOptions") SetConfig = try LoadFunction(lib, "TF_SetConfig") SetTarget = try LoadFunction(lib, "TF_SetTarget") NewSessionOptions = try LoadFunction(lib, "TF_NewSessionOptions") StringEncodedSize = try LoadFunction(lib, "TF_StringEncodedSize") StringDecode = try LoadFunction(lib, "TF_StringDecode") StringEncode = try LoadFunction(lib, "TF_StringEncode") TensorData = try LoadFunction(lib, "TF_TensorData") TensorByteSize = try LoadFunction(lib, "TF_TensorByteSize") Dim = try LoadFunction(lib, "TF_Dim") NumDims = try LoadFunction(lib, "TF_NumDims") TensorType = try LoadFunction(lib, "TF_TensorType") DeleteTensor = try LoadFunction(lib, "TF_DeleteTensor") AllocateTensor = try LoadFunction(lib, "TF_AllocateTensor") NewTensor = try LoadFunction(lib, "TF_NewTensor") DeleteBuffer = try LoadFunction(lib, "TF_DeleteBuffer") NewBuffer = try LoadFunction(lib, "TF_NewBuffer") NewBufferFromString = try LoadFunction(lib, "TF_NewBufferFromString") Message = try LoadFunction(lib, "TF_Message") GetCode = try LoadFunction(lib, "TF_GetCode") SetStatus = try LoadFunction(lib, "TF_SetStatus") DeleteStatus = try LoadFunction(lib, "TF_DeleteStatus") NewStatus = try LoadFunction(lib, "TF_NewStatus") DataTypeSize = try LoadFunction(lib, "TF_DataTypeSize") }//end open /// static library closing public static func Close() { if let lib = libDLL { _ = dlclose(lib) }//end if }//end func }//end class
apache-2.0
2979e10f4d195f7e673bfcb9f4b8c08b
58.736842
365
0.696287
4.051964
false
false
false
false
crazypoo/PTools
Pods/ChromaColorPicker/Source/ChromaColorPicker.swift
1
9031
// // ChromaColorPicker.swift // ChromaColorPicker // // Created by Jon Cardasis on 3/10/19. // Copyright © 2019 Jonathan Cardasis. All rights reserved. // import UIKit public protocol ChromaColorPickerDelegate: class { /// When a handle's value has changed. func colorPickerHandleDidChange(_ colorPicker: ChromaColorPicker, handle: ChromaColorHandle, to color: UIColor) } @IBDesignable public class ChromaColorPicker: UIControl, ChromaControlStylable { public weak var delegate: ChromaColorPickerDelegate? @IBInspectable public var borderWidth: CGFloat = 6.0 { didSet { layoutNow() } } @IBInspectable public var borderColor: UIColor = .white { didSet { layoutNow() } } @IBInspectable public var showsShadow: Bool = true { didSet { layoutNow() } } /// A brightness slider attached via the `connect(_:)` method. private(set) public weak var brightnessSlider: ChromaBrightnessSlider? { didSet { oldValue?.removeTarget(self, action: nil, for: .valueChanged) } } /// The size handles should be displayed at. public var handleSize: CGSize = defaultHandleSize { didSet { setNeedsLayout() } } /// An extension to handles' hitboxes in the +Y direction. /// Allows for handles to be grabbed more easily. public var handleHitboxExtensionY: CGFloat = 10.0 /// Handles added to the color picker. private(set) public var handles: [ChromaColorHandle] = [] /// The last active handle. private(set) public var currentHandle: ChromaColorHandle? //MARK: - Initialization override public init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } public override func layoutSubviews() { super.layoutSubviews() updateShadowIfNeeded() updateBorderIfNeeded() handles.forEach { handle in let location = colorWheelView.location(of: handle.color) handle.frame.size = handleSize positionHandle(handle, forColorLocation: location) } } // MARK: - Public @discardableResult public func addHandle(at color: UIColor? = nil) -> ChromaColorHandle { let handle = ChromaColorHandle() handle.color = color ?? defaultHandleColorPosition addHandle(handle) return handle } public func addHandle(_ handle: ChromaColorHandle) { handles.append(handle) colorWheelView.addSubview(handle) brightnessSlider?.trackColor = handle.color } public func connect(_ slider: ChromaBrightnessSlider) { slider.addTarget(self, action: #selector(brightnessSliderDidValueChange(_:)), for: .valueChanged) brightnessSlider = slider } // MARK: - Control public override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: colorWheelView) for handle in handles { if extendedHitFrame(for: handle).contains(location) { colorWheelView.bringSubviewToFront(handle) animateHandleScale(handle, shouldGrow: true) if let slider = brightnessSlider { slider.trackColor = handle.color.withBrightness(1) slider.currentValue = slider.value(brightness: handle.color.brightness) } currentHandle = handle return true } } return false } public override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { var location = touch.location(in: colorWheelView) guard let handle = currentHandle else { return false } if !colorWheelView.pointIsInColorWheel(location) { // Touch is outside color wheel and should map to outermost edge. let center = colorWheelView.middlePoint let radius = colorWheelView.radius let angleToCenter = atan2(location.x - center.x, location.y - center.y) let positionOnColorWheelEdge = CGPoint(x: center.x + radius * sin(angleToCenter), y: center.y + radius * cos(angleToCenter)) location = positionOnColorWheelEdge } if let pixelColor = colorWheelView.pixelColor(at: location) { let previousBrightness = handle.color.brightness handle.color = pixelColor.withBrightness(previousBrightness) positionHandle(handle, forColorLocation: location) if let slider = brightnessSlider { slider.trackColor = pixelColor slider.currentValue = slider.value(brightness: previousBrightness) } informDelegateOfColorChange(on: handle) sendActions(for: .valueChanged) } return true } public override func endTracking(_ touch: UITouch?, with event: UIEvent?) { if let handle = currentHandle { animateHandleScale(handle, shouldGrow: false) } sendActions(for: .touchUpInside) } public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // Self should handle all touch events, forwarding if needed. let touchableBounds = bounds.insetBy(dx: -handleSize.width, dy: -handleSize.height) return touchableBounds.contains(point) ? self : super.hitTest(point, with: event) } // MARK: - Private internal let colorWheelView = ColorWheelView() internal var colorWheelViewWidthConstraint: NSLayoutConstraint! internal func commonInit() { self.backgroundColor = UIColor.clear setupColorWheelView() } internal func setupColorWheelView() { colorWheelView.translatesAutoresizingMaskIntoConstraints = false addSubview(colorWheelView) colorWheelViewWidthConstraint = colorWheelView.widthAnchor.constraint(equalTo: self.widthAnchor) NSLayoutConstraint.activate([ colorWheelView.centerXAnchor.constraint(equalTo: self.centerXAnchor), colorWheelView.centerYAnchor.constraint(equalTo: self.centerYAnchor), colorWheelViewWidthConstraint, colorWheelView.heightAnchor.constraint(equalTo: colorWheelView.widthAnchor), ]) } func updateShadowIfNeeded() { if showsShadow { applyDropShadow(shadowProperties(forHeight: bounds.height)) } else { removeDropShadow() } } internal func updateBorderIfNeeded() { // Use view's background as a border so colorWheel subviews (handles) // may appear above the border. backgroundColor = borderWidth > 0 ? borderColor : .clear layer.cornerRadius = bounds.height / 2.0 layer.masksToBounds = false colorWheelViewWidthConstraint.constant = -borderWidth * 2.0 } // MARK: Actions @objc internal func brightnessSliderDidValueChange(_ slider: ChromaBrightnessSlider) { guard let currentHandle = currentHandle else { return } currentHandle.color = slider.currentColor informDelegateOfColorChange(on: currentHandle) } internal func informDelegateOfColorChange(on handle: ChromaColorHandle) { // TEMP: delegate?.colorPickerHandleDidChange(self, handle: handle, to: handle.color) } // MARK: - Helpers internal func extendedHitFrame(for handle: ChromaColorHandle) -> CGRect { var frame = handle.frame frame.size.height += handleHitboxExtensionY return frame } internal func positionHandle(_ handle: ChromaColorHandle, forColorLocation location: CGPoint) { handle.center = location.applying(CGAffineTransform.identity.translatedBy(x: 0, y: -handle.bounds.height / 2)) } internal func animateHandleScale(_ handle: ChromaColorHandle, shouldGrow: Bool) { if shouldGrow && handle.transform.d > 1 { return } // Already grown let scalar: CGFloat = 1.25 var transform: CGAffineTransform = .identity if shouldGrow { let translateY = -handle.bounds.height * (scalar - 1) / 2 transform = CGAffineTransform(scaleX: scalar, y: scalar).translatedBy(x: 0, y: translateY) } UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: .curveEaseInOut, animations: { handle.transform = transform }, completion: nil) } } internal let defaultHandleColorPosition: UIColor = .white internal let defaultHandleSize: CGSize = CGSize(width: 42, height: 52)
mit
fae90e9a1aca02d73956a0116513ac2f
35.12
149
0.637652
5.151169
false
false
false
false
allen-zeng/PromiseKit
Sources/Error.swift
6
6726
import Dispatch import Foundation.NSError import Foundation.NSURLError public enum Error: ErrorType { /** The ErrorType for a rejected `when`. - Parameter 0: The index of the promise that was rejected. - Parameter 1: The error from the promise that rejected this `when`. */ case When(Int, ErrorType) /** The ErrorType for a rejected `join`. - Parameter 0: The promises passed to this `join` that did not *all* fulfill. - Note: The array is untyped because Swift generics are fussy with enums. */ case Join([AnyObject]) /** The closure with form (T?, ErrorType?) was called with (nil, nil) This is invalid as per the calling convention. */ case DoubleOhSux0r /** A handler returned its own promise. 99% of the time, this is likely a programming error. It is also invalid per Promises/A+. */ case ReturnedSelf /** `when()` was called with a concurrency of <= 0 */ case WhenConcurrentlyZero } public enum URLError: ErrorType { /** The URLRequest succeeded but a valid UIImage could not be decoded from the data that was received. */ case InvalidImageData(NSURLRequest, NSData) /** An NSError was received from an underlying Cocoa function. FIXME sucks? */ case UnderlyingCocoaError(NSURLRequest, NSData?, NSURLResponse?, NSError) /** The HTTP request returned a non-200 status code. */ case BadResponse(NSURLRequest, NSData?, NSURLResponse?) /** The data could not be decoded using the encoding specified by the HTTP response headers. */ case StringEncoding(NSURLRequest, NSData, NSURLResponse) /** Usually the `NSURLResponse` is actually an `NSHTTPURLResponse`, if so you can access it using this property. Since it is returned as an unwrapped optional: be sure. */ public var NSHTTPURLResponse: Foundation.NSHTTPURLResponse! { switch self { case .InvalidImageData: return nil case .UnderlyingCocoaError(_, _, let rsp, _): return rsp as! Foundation.NSHTTPURLResponse case .BadResponse(_, _, let rsp): return rsp as! Foundation.NSHTTPURLResponse case .StringEncoding(_, _, let rsp): return rsp as! Foundation.NSHTTPURLResponse } } } public enum JSONError: ErrorType { case UnexpectedRootNode(AnyObject) } public enum CastingError: ErrorType { case CastingAnyPromiseFailed(Any.Type) } //////////////////////////////////////////////////////////// Cancellation private struct ErrorPair: Hashable { let domain: String let code: Int init(_ d: String, _ c: Int) { domain = d; code = c } var hashValue: Int { return "\(domain):\(code)".hashValue } } private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool { return lhs.domain == rhs.domain && lhs.code == rhs.code } extension NSError { @objc public class func cancelledError() -> NSError { let info: [NSObject: AnyObject] = [NSLocalizedDescriptionKey: "The operation was cancelled"] return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info) } /** - Warning: You may only call this method on the main thread. */ @objc public class func registerCancelledErrorDomain(domain: String, code: Int) { cancelledErrorIdentifiers.insert(ErrorPair(domain, code)) } } public protocol CancellableErrorType: ErrorType { var cancelled: Bool { get } } extension NSError: CancellableErrorType { /** - Warning: You may only call this method on the main thread. */ @objc public var cancelled: Bool { if !NSThread.isMainThread() { NSLog("PromiseKit: Warning: `cancelled` called on background thread.") } return cancelledErrorIdentifiers.contains(ErrorPair(domain, code)) } } ////////////////////////////////////////// Predefined Cancellation Errors private var cancelledErrorIdentifiers = Set([ ErrorPair(PMKErrorDomain, PMKOperationCancelled), ErrorPair(NSURLErrorDomain, NSURLErrorCancelled) ]) extension NSURLError: CancellableErrorType { public var cancelled: Bool { return self == .Cancelled } } //////////////////////////////////////////////////////// Unhandled Errors /** The unhandled error handler. If a promise is rejected and no catch handler is called in its chain, the provided handler is called. The default handler logs the error. PMKUnhandledErrorHandler = { error in mylogf("Unhandled error: \(error)") } - Warning: *Important* The handler is executed on an undefined queue. - Warning: *Important* Don’t use promises in your handler, or you risk an infinite error loop. - Returns: The previous unhandled error handler. */ public var PMKUnhandledErrorHandler = { (error: ErrorType) -> Void in dispatch_async(dispatch_get_main_queue()) { let cancelled = (error as? CancellableErrorType)?.cancelled ?? false // ^-------^ must be called on main queue if !cancelled { NSLog("PromiseKit: Unhandled Error: %@", "\(error)") } } } class ErrorConsumptionToken { var consumed = false let error: ErrorType! init(_ error: ErrorType) { self.error = error } init(_ error: NSError) { self.error = error.copy() as! NSError } deinit { if !consumed { PMKUnhandledErrorHandler(error) } } } private var handle: UInt8 = 0 extension NSError { @objc func pmk_consume() { // The association could be nil if the objc_setAssociatedObject // has taken a *really* long time. Or perhaps the user has // overused `zalgo`. Thus we ignore it. This is an unlikely edge // case and the unhandled-error feature is not mission-critical. if let token = objc_getAssociatedObject(self, &handle) as? ErrorConsumptionToken { token.consumed = true } } var token: ErrorConsumptionToken! { return objc_getAssociatedObject(self, &handle) as? ErrorConsumptionToken } } func unconsume(error error: NSError, reusingToken t: ErrorConsumptionToken? = nil) { var token = t if token != nil { objc_setAssociatedObject(error, &handle, token, .OBJC_ASSOCIATION_RETAIN) } else { token = objc_getAssociatedObject(error, &handle) as? ErrorConsumptionToken if token == nil { token = ErrorConsumptionToken(error) objc_setAssociatedObject(error, &handle, token, .OBJC_ASSOCIATION_RETAIN) } } token!.consumed = false }
mit
1f0b635ce9779c078c020becf94552cd
29.017857
100
0.638311
4.659737
false
false
false
false
MounikaAnkam/BooksAuthors
BooksAuthors/BooksViewController.swift
1
6341
// // BooksViewController.swift // BooksAuthors // // Created by Jaini,Santhoshi on 3/20/15. // Copyright (c) 2015 Student. All rights reserved. // import UIKit import CoreData class BooksViewController: UIViewController , UITableViewDataSource , UITableViewDelegate{ var authors:[Author] = [Author]() var books:[Book] = [Book]() var error:NSError? var selectedRow:Int = 0 var managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext @IBOutlet weak var tableView1: UITableView! @IBOutlet weak var tableView2: UITableView! var count:Int = 0 override func viewDidLoad() { super.viewDidLoad() self.tableView2.reloadData() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView.viewWithTag(1) != nil{ return authors.count}else{ if count != 0 { return books.count }else{ return 0} } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView.viewWithTag(1) != nil{ var cell = UITableViewCell() cell = tableView1.dequeueReusableCellWithIdentifier("authors") as UITableViewCell cell.textLabel?.text = authors[indexPath.row].name var formatter: NSDateFormatter = NSDateFormatter() formatter.dateFormat = "dd-MM-yyyy" let stringDate: String = formatter.stringFromDate(authors[indexPath.row].dob) cell.detailTextLabel?.text = String(stringDate) return cell }else{ if count != 0 { var cell = UITableViewCell() cell = tableView2.dequeueReusableCellWithIdentifier("books") as UITableViewCell cell.textLabel?.text = books[indexPath.row].title return cell }else{ var cell = UITableViewCell() cell = tableView2.dequeueReusableCellWithIdentifier("books") as UITableViewCell cell.textLabel?.text = "" return cell } } } override func viewWillAppear(animated: Bool) { self.view.viewWithTag(2)?.reloadInputViews() count = 0 books = [Book]() // var fetchRequest = NSFetchRequest(entityName:"Author") authors = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [Author] self.tableView2.reloadData() self.tableView1.reloadData() } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView1.indexPathForSelectedRow()?.row != nil { count++ self.tableView2.reloadData() books = [Book]() // println(authors[indexPath.row].name) var fetchAuthor = NSFetchRequest(entityName: "Author") fetchAuthor.predicate = NSPredicate(format: "name = %@", authors[indexPath.row].name) var authorReq:[Author] = managedObjectContext?.executeFetchRequest(fetchAuthor, error: nil) as [Author] for bookRecord in authorReq[0].authorToBook{ books.append(bookRecord as Book) } self.tableView2.reloadData() } } func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { selectedRow = indexPath.row } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if tableView.viewWithTag(1) != nil{ return "Authors "}else{ return "Books" } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "newbook"{ (self.view.viewWithTag(2) as UITableView).reloadData() var nbvc = segue.destinationViewController as NewBookViewController var fetchRequest = NSFetchRequest(entityName: "Author") var requiredAuthor:Author! var authorList = managedObjectContext?.executeFetchRequest(fetchRequest, error: nil ) as [Author] for authorRecord in authorList { if self.tableView1.indexPathForSelectedRow() != nil { if authorRecord.name == authors[self.tableView1.indexPathForSelectedRow()!.row].name { println(authors[self.tableView1.indexPathForSelectedRow()!.row].name) requiredAuthor = authorRecord nbvc.selectedAuthor = requiredAuthor }} else{ if authorRecord.name == authors[selectedRow].name { requiredAuthor = authorRecord nbvc.selectedAuthor = requiredAuthor } } } } } }
mit
c6e5364076f98a8d779b264947b875da
25.868644
113
0.532093
6.253452
false
false
false
false
zacwest/ZSWTaggedString
ZSWTaggedString/Classes/ZSWTaggedStringOptions.swift
2
3095
// // ZSWTaggedStringOptions.swift // Pods // // Created by Zachary West on 12/6/15. // // import ZSWTaggedString.Private extension ZSWTaggedStringOptions { /** Dynamic attributes executed for a tag Below parameters are for an example tag of: `<a href="http://google.com">` - Parameter tagName: This would be `"a"` in the example. - Parameter tagAttributes: This would be `["href": "http://google.com"]` in the example. - Parameter existingStringAttributes: The attributes for the generated attributed string at the given tag start location before applying the given attributes. - Returns: The `NSAttributedString` attributes you wish to be applied for the tag. */ public typealias DynamicAttributes = (_ tagName: String, _ tagAttributes: [String: Any], _ existingStringAttributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] /** Attributes to be applied to an attributed string. - Dynamic: Takes input about the tag to generate values. - Static: Always returns the same attributes. */ public enum Attributes { case dynamic(DynamicAttributes) case `static`([NSAttributedString.Key: Any]) init(wrapper: ZSWTaggedStringAttribute) { if let dictionary = wrapper.staticDictionary { self = .static(dictionary) } else if let block = wrapper.dynamicAttributes { self = .dynamic(block) } else { fatalError("Not static or dynamic") } } var wrapper: ZSWTaggedStringAttribute { let wrapper = ZSWTaggedStringAttribute() switch self { case .dynamic(let attributes): wrapper.dynamicAttributes = attributes case .static(let attributes): wrapper.staticDictionary = attributes } return wrapper } } /** Attributes to be applied for an unknown tag. For example, if you do not specify attributes for the tag `"a"` and your string contains it, these attributes would be invoked for it. */ public var unknownTagAttributes: Attributes? { get { if let wrapper = _private_unknownTagWrapper { return Attributes(wrapper: wrapper) } else { return nil } } set { _private_unknownTagWrapper = newValue?.wrapper } } /** Attributes for a given tag name. For example, use the subscript `"a"` to set the attributes for that tag. */ public subscript (tagName: String) -> Attributes? { get { if let currentValue = _private_tagToAttributesMap[tagName] { return Attributes(wrapper: currentValue) } else { return nil } } set { _private_setWrapper(newValue?.wrapper, forTagName: tagName) } } }
mit
4b2410bb41426ba33272adf80a4e18f4
30.581633
184
0.582553
5.05719
false
false
false
false
koden-km/dialekt-swift
Dialekt/Parser/ListParser.swift
1
2353
import Foundation /// Parses a list of tags. /// /// The expression must be a space-separated list of tags. The result is /// either EmptyExpression, a single Tag node, or a LogicalAnd node /// containing only Tag nodes. public class ListParser: AbstractParser, ParserProtocol { /// Parse a list of tags into an array. /// /// The expression must be a space-separated list of tags. The result is /// an array of strings. public func parseAsArray(expression: String) -> [String]! { return parseAsArray(expression, lexer: Lexer()) } /// Parse a list of tags into an array. /// /// The expression must be a space-separated list of tags. The result is /// an array of strings. public func parseAsArray(expression: String, lexer: LexerProtocol) -> [String]! { let result = parse(expression, lexer: lexer) if result == nil { return nil } var tags = [String]() if let logicalAndResult = result as? LogicalAnd { for child in logicalAndResult.children() { if let childTag = child as? Tag { tags.append(childTag.name()) } } } else if let tagResult = result as? Tag { tags.append(tagResult.name()) } return tags } internal override func parseExpression() -> AbstractExpression! { let expression = LogicalAnd() startExpression() while _currentToken != nil { if !expectToken(TokenType.Text) { return nil } if _currentToken == nil || _currentToken.value.rangeOfString(wildcardString) != nil { // Implement a Result<T>/Failable<T> return type. // throw Exception "Unexpected wildcard string \"" + wildcardString + "\", in tag \"" + _currentToken.value + "\"." // fatalError("Unexpected wildcard string in tag.") return nil } let tag = Tag(_currentToken.value) startExpression() nextToken() endExpression(tag) expression.add(tag) } endExpression(expression) if expression.children().count == 1 { return expression.children()[0] as AbstractExpression } return expression } }
mit
edea48980f42eab0170734c19c3d4405
29.960526
131
0.577136
4.831622
false
false
false
false
changjianfeishui/iOS_Tutorials_Of_Swift
UIKit Dynamics and Motion Effects/DynamicsPlayground/DynamicsPlayground/ViewController.swift
1
3121
// // ViewController.swift // DynamicsPlayground // // Created by XB on 16/5/5. // Copyright © 2016年 XB. All rights reserved. // import UIKit class ViewController: UIViewController ,UICollisionBehaviorDelegate{ var _animator:UIDynamicAnimator! var _gravity:UIGravityBehavior! var _collision:UICollisionBehavior! var _firstContact:Bool = false override func viewDidLoad() { super.viewDidLoad() //添加要执行动画的View let square = UIView(frame: CGRectMake(100,100,100,100)) square.backgroundColor = UIColor.grayColor() self.view.addSubview(square) //动画物理引擎 _animator = UIDynamicAnimator(referenceView: self.view) //重力行为 _gravity = UIGravityBehavior(items: [square]) // gravity.angle = CGFloat(M_PI) // gravity.gravityDirection = CGVector(dx: 1, dy: 1) // gravity.magnitude = 10 _animator.addBehavior(_gravity) //创建障碍物 let barrier = UIView(frame: CGRectMake(0,300,130,20)) barrier.backgroundColor = UIColor.blackColor() self.view .addSubview(barrier) //碰撞行为 _collision = UICollisionBehavior(items: [square]) _collision.translatesReferenceBoundsIntoBoundary = true; _animator.addBehavior(_collision) _collision.action = { // print("\(square.transform),\(square.center)") let traceView = UIView(frame: square.frame) traceView.layer.borderColor = UIColor.orangeColor().CGColor traceView.layer.borderWidth = 1 self.view.addSubview(traceView) } _collision.collisionDelegate = self //添加障碍物为边界 let rightEdge = CGPoint(x: barrier.frame.origin.x + barrier.frame.size.width , y: barrier.frame.origin.y) _collision.addBoundaryWithIdentifier("barrier", fromPoint: barrier.frame.origin, toPoint: rightEdge) //配置仿真属性 let itemBehavior = UIDynamicItemBehavior(items: [square]) itemBehavior.elasticity = 0.6 _animator.addBehavior(itemBehavior) } func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint) { print("Boundary contact occurred \(identifier)") let view = item as! UIView view.backgroundColor = UIColor.yellowColor() UIView.animateWithDuration(0.3) { view.backgroundColor = UIColor.redColor() } if !_firstContact { _firstContact = true let square = UIView(frame: CGRectMake(30, 0, 100, 100)) square.backgroundColor = UIColor.lightGrayColor() self.view.addSubview(square) _collision.addItem(square) _gravity.addItem(square) let attach = UIAttachmentBehavior(item: view, attachedToItem: square) _animator.addBehavior(attach) } } }
mit
0f07e0aa89a54db4368e90b6f699c25e
33.11236
167
0.624506
4.6
false
false
false
false
jonesgithub/DKChainableAnimationKit
iOS Example/ViewController.swift
4
1960
// // ViewController.swift // DKChainableAnimationKit // // Created by Draveness on 15/5/13. // Copyright (c) 2015年 Draveness. All rights reserved. // import UIKit import DKChainableAnimationKit class ViewController: UIViewController { let v: UIView = UIView(frame: CGRect(x: 100, y: 150, width: 50, height: 50)) override func viewDidLoad() { super.viewDidLoad() v.backgroundColor = UIColor.blueColor() self.view.addSubview(v) UIApplication.sharedApplication().statusBarHidden = true let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) button.frame = CGRect(x: 0, y: self.view.bounds.size.height - 50.0, width: self.view.bounds.size.width, height: 50) button.backgroundColor = UIColor.blueColor() button.setTitle("Action!", forState: .Normal) button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.addTarget(self, action: "animateView:", forControlEvents: .TouchUpInside) self.view.addSubview(button) } func animateView(sender: UIButton) { sender.userInteractionEnabled = false let purple = UIColor.purpleColor() let green = UIColor.greenColor() v.animation.moveX(100).thenAfter(1.0).moveWidth(50).bounce.makeBackground(green).easeIn.anchorTopLeft.thenAfter(0.5).rotate(95).easeBack.thenAfter(0.5).moveY(300).easeIn.makeOpacity(0.0).animateWithCompletion(0.4, { self.v.layer.transform = CATransform3DMakeRotation(0, 0, 0, 1) self.v.frame = CGRectMake(100, 150, 50, 50) self.v.animation.makeOpacity(1.0).makeBackground(UIColor.blueColor()).animate(1.0) self.v.layer.cornerRadius = 0 sender.animation.moveY(-50).easeInOutExpo.animate(1.1).animationCompletion = { sender.userInteractionEnabled = true }; }) sender.animation.moveY(50).easeInOutExpo.animate(0.5) } }
mit
1bb236c56a483038357172ad19aed6c1
35.259259
223
0.665986
3.916
false
false
false
false
loudnate/Loop
LoopCore/LoopSettings.swift
1
9556
// // LoopSettings.swift // Loop // // Copyright © 2017 LoopKit Authors. All rights reserved. // import LoopKit import HealthKit public struct LoopSettings: Equatable { public var dosingEnabled = false public let dynamicCarbAbsorptionEnabled = true public static let defaultCarbAbsorptionTimes: CarbStore.DefaultAbsorptionTimes = (fast: .hours(2), medium: .hours(3), slow: .hours(4)) public var glucoseTargetRangeSchedule: GlucoseRangeSchedule? public var preMealTargetRange: DoubleRange? public var legacyWorkoutTargetRange: DoubleRange? public var overridePresets: [TemporaryScheduleOverridePreset] = [] public var scheduleOverride: TemporaryScheduleOverride? public var maximumBasalRatePerHour: Double? public var maximumBolus: Double? public var suspendThreshold: GlucoseThreshold? = nil public let retrospectiveCorrectionEnabled = true /// The interval over which to aggregate changes in glucose for retrospective correction public let retrospectiveCorrectionGroupingInterval = TimeInterval(minutes: 30) /// The amount of time since a given date that input data should be considered valid public let inputDataRecencyInterval = TimeInterval(minutes: 15) /// Loop completion aging category limits public let completionFreshLimit = TimeInterval(minutes: 6) public let completionAgingLimit = TimeInterval(minutes: 16) public let completionStaleLimit = TimeInterval(hours: 12) public let batteryReplacementDetectionThreshold = 0.5 public let defaultWatchCarbPickerValue = 15 // grams public let defaultWatchBolusPickerValue = 1.0 // % // MARK - Display settings public let minimumChartWidthPerHour: CGFloat = 50 public let statusChartMinimumHistoryDisplay: TimeInterval = .hours(1) public var glucoseUnit: HKUnit? { return glucoseTargetRangeSchedule?.unit } // MARK - Push Notifications public var deviceToken: Data? // MARK - Guardrails public func allowedSensitivityValues(for unit: HKUnit) -> [Double] { switch unit { case HKUnit.milligramsPerDeciliter: return (10...500).map { Double($0) } case HKUnit.millimolesPerLiter: return (6...270).map { Double($0) / 10.0 } default: return [] } } public func allowedCorrectionRangeValues(for unit: HKUnit) -> [Double] { switch unit { case HKUnit.milligramsPerDeciliter: return (60...180).map { Double($0) } case HKUnit.millimolesPerLiter: return (33...100).map { Double($0) / 10.0 } default: return [] } } public init( dosingEnabled: Bool = false, glucoseTargetRangeSchedule: GlucoseRangeSchedule? = nil, maximumBasalRatePerHour: Double? = nil, maximumBolus: Double? = nil, suspendThreshold: GlucoseThreshold? = nil ) { self.dosingEnabled = dosingEnabled self.glucoseTargetRangeSchedule = glucoseTargetRangeSchedule self.maximumBasalRatePerHour = maximumBasalRatePerHour self.maximumBolus = maximumBolus self.suspendThreshold = suspendThreshold } } extension LoopSettings { public var glucoseTargetRangeScheduleApplyingOverrideIfActive: GlucoseRangeSchedule? { if let override = scheduleOverride, override.isActive() { return glucoseTargetRangeSchedule?.applyingOverride(override) } else { return glucoseTargetRangeSchedule } } public func scheduleOverrideEnabled(at date: Date = Date()) -> Bool { guard let override = scheduleOverride else { return false } return override.isActive(at: date) } public func nonPreMealOverrideEnabled(at date: Date = Date()) -> Bool { guard let override = scheduleOverride else { return false } return override.context != .preMeal && override.isActive(at: date) } public func preMealTargetEnabled(at date: Date = Date()) -> Bool { guard let override = scheduleOverride else { return false } return override.context == .preMeal && override.isActive(at: date) } public func futureOverrideEnabled(relativeTo date: Date = Date()) -> Bool { guard let override = scheduleOverride else { return false } return override.startDate > date } public mutating func enablePreMealOverride(at date: Date = Date(), for duration: TimeInterval) { scheduleOverride = preMealOverride(beginningAt: date, for: duration) } public func preMealOverride(beginningAt date: Date = Date(), for duration: TimeInterval) -> TemporaryScheduleOverride? { guard let premealTargetRange = preMealTargetRange, let unit = glucoseUnit else { return nil } return TemporaryScheduleOverride( context: .preMeal, settings: TemporaryScheduleOverrideSettings(unit: unit, targetRange: premealTargetRange), startDate: date, duration: .finite(duration), enactTrigger: .local, syncIdentifier: UUID() ) } public mutating func enableLegacyWorkoutOverride(at date: Date = Date(), for duration: TimeInterval) { scheduleOverride = legacyWorkoutOverride(beginningAt: date, for: duration) } public func legacyWorkoutOverride(beginningAt date: Date = Date(), for duration: TimeInterval) -> TemporaryScheduleOverride? { guard let legacyWorkoutTargetRange = legacyWorkoutTargetRange, let unit = glucoseUnit else { return nil } return TemporaryScheduleOverride( context: .legacyWorkout, settings: TemporaryScheduleOverrideSettings(unit: unit, targetRange: legacyWorkoutTargetRange), startDate: date, duration: duration.isInfinite ? .indefinite : .finite(duration), enactTrigger: .local, syncIdentifier: UUID() ) } public mutating func clearOverride(matching context: TemporaryScheduleOverride.Context? = nil) { guard let override = scheduleOverride else { return } if let context = context { if override.context == context { scheduleOverride = nil } } else { scheduleOverride = nil } } } extension LoopSettings: RawRepresentable { public typealias RawValue = [String: Any] private static let version = 1 public init?(rawValue: RawValue) { guard let version = rawValue["version"] as? Int, version == LoopSettings.version else { return nil } if let dosingEnabled = rawValue["dosingEnabled"] as? Bool { self.dosingEnabled = dosingEnabled } if let glucoseRangeScheduleRawValue = rawValue["glucoseTargetRangeSchedule"] as? GlucoseRangeSchedule.RawValue { self.glucoseTargetRangeSchedule = GlucoseRangeSchedule(rawValue: glucoseRangeScheduleRawValue) // Migrate the glucose range schedule override targets if let overrideRangesRawValue = glucoseRangeScheduleRawValue["overrideRanges"] as? [String: DoubleRange.RawValue] { if let preMealTargetRawValue = overrideRangesRawValue["preMeal"] { self.preMealTargetRange = DoubleRange(rawValue: preMealTargetRawValue) } if let legacyWorkoutTargetRawValue = overrideRangesRawValue["workout"] { self.legacyWorkoutTargetRange = DoubleRange(rawValue: legacyWorkoutTargetRawValue) } } } if let rawPreMealTargetRange = rawValue["preMealTargetRange"] as? DoubleRange.RawValue { self.preMealTargetRange = DoubleRange(rawValue: rawPreMealTargetRange) } if let rawLegacyWorkoutTargetRange = rawValue["legacyWorkoutTargetRange"] as? DoubleRange.RawValue { self.legacyWorkoutTargetRange = DoubleRange(rawValue: rawLegacyWorkoutTargetRange) } if let rawPresets = rawValue["overridePresets"] as? [TemporaryScheduleOverridePreset.RawValue] { self.overridePresets = rawPresets.compactMap(TemporaryScheduleOverridePreset.init(rawValue:)) } if let rawOverride = rawValue["scheduleOverride"] as? TemporaryScheduleOverride.RawValue { self.scheduleOverride = TemporaryScheduleOverride(rawValue: rawOverride) } self.maximumBasalRatePerHour = rawValue["maximumBasalRatePerHour"] as? Double self.maximumBolus = rawValue["maximumBolus"] as? Double if let rawThreshold = rawValue["minimumBGGuard"] as? GlucoseThreshold.RawValue { self.suspendThreshold = GlucoseThreshold(rawValue: rawThreshold) } } public var rawValue: RawValue { var raw: RawValue = [ "version": LoopSettings.version, "dosingEnabled": dosingEnabled, "overridePresets": overridePresets.map { $0.rawValue } ] raw["glucoseTargetRangeSchedule"] = glucoseTargetRangeSchedule?.rawValue raw["preMealTargetRange"] = preMealTargetRange?.rawValue raw["legacyWorkoutTargetRange"] = legacyWorkoutTargetRange?.rawValue raw["scheduleOverride"] = scheduleOverride?.rawValue raw["maximumBasalRatePerHour"] = maximumBasalRatePerHour raw["maximumBolus"] = maximumBolus raw["minimumBGGuard"] = suspendThreshold?.rawValue return raw } }
apache-2.0
453e346ef175c933dfbb8c48632165f5
36.324219
138
0.673888
5.09057
false
false
false
false
benlangmuir/swift
benchmark/single-source/SortStrings.swift
10
39372
//===--- SortStrings.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils let t: [BenchmarkCategory] = [.validation, .api, .algorithm, .String] // Sort an array of strings using an explicit sort predicate. public let benchmarks = [ BenchmarkInfo(name: "SortSortedStrings", runFunction: run_SortSortedStrings, tags: t, setUpFunction: { blackHole(sortedWords) }), BenchmarkInfo(name: "SortStrings", runFunction: run_SortStrings, tags: t, setUpFunction: { blackHole(words) }), BenchmarkInfo(name: "SortStringsUnicode", runFunction: run_SortStringsUnicode, tags: t, setUpFunction: { blackHole(unicodeWords) }, legacyFactor: 5), ] let sortedWords = words.sorted() let words: [String] = [ "woodshed", "lakism", "gastroperiodynia", "afetal", "ramsch", "Nickieben", "undutifulness", "birdglue", "ungentlemanize", "menacingly", "heterophile", "leoparde", "Casearia", "decorticate", "neognathic", "mentionable", "tetraphenol", "pseudonymal", "dislegitimate", "Discoidea", "intitule", "ionium", "Lotuko", "timbering", "nonliquidating", "oarialgia", "Saccobranchus", "reconnoiter", "criminative", "disintegratory", "executer", "Cylindrosporium", "complimentation", "Ixiama", "Araceae", "silaginoid", "derencephalus", "Lamiidae", "marrowlike", "ninepin", "dynastid", "lampfly", "feint", "trihemimer", "semibarbarous", "heresy", "tritanope", "indifferentist", "confound", "hyperbolaeon", "planirostral", "philosophunculist", "existence", "fretless", "Leptandra", "Amiranha", "handgravure", "gnash", "unbelievability", "orthotropic", "Susumu", "teleutospore", "sleazy", "shapeliness", "hepatotomy", "exclusivism", "stifler", "cunning", "isocyanuric", "pseudepigraphy", "carpetbagger", "respectiveness", "Jussi", "vasotomy", "proctotomy", "ovatotriangular", "aesthetic", "schizogamy", "disengagement", "foray", "haplocaulescent", "noncoherent", "astrocyte", "unreverberated", "presenile", "lanson", "enkraal", "contemplative", "Syun", "sartage", "unforgot", "wyde", "homeotransplant", "implicational", "forerunnership", "calcaneum", "stomatodeum", "pharmacopedia", "preconcessive", "trypanosomatic", "intracollegiate", "rampacious", "secundipara", "isomeric", "treehair", "pulmonal", "uvate", "dugway", "glucofrangulin", "unglory", "Amandus", "icterogenetic", "quadrireme", "Lagostomus", "brakeroot", "anthracemia", "fluted", "protoelastose", "thro", "pined", "Saxicolinae", "holidaymaking", "strigil", "uncurbed", "starling", "redeemeress", "Liliaceae", "imparsonee", "obtusish", "brushed", "mesally", "probosciformed", "Bourbonesque", "histological", "caroba", "digestion", "Vindemiatrix", "triactinal", "tattling", "arthrobacterium", "unended", "suspectfulness", "movelessness", "chartist", "Corynebacterium", "tercer", "oversaturation", "Congoleum", "antiskeptical", "sacral", "equiradiate", "whiskerage", "panidiomorphic", "unplanned", "anilopyrine", "Queres", "tartronyl", "Ing", "notehead", "finestiller", "weekender", "kittenhood", "competitrix", "premillenarian", "convergescence", "microcoleoptera", "slirt", "asteatosis", "Gruidae", "metastome", "ambuscader", "untugged", "uneducated", "redistill", "rushlight", "freakish", "dosology", "papyrine", "iconologist", "Bidpai", "prophethood", "pneumotropic", "chloroformize", "intemperance", "spongiform", "superindignant", "divider", "starlit", "merchantish", "indexless", "unidentifiably", "coumarone", "nomism", "diaphanous", "salve", "option", "anallantoic", "paint", "thiofurfuran", "baddeleyite", "Donne", "heterogenicity", "decess", "eschynite", "mamma", "unmonarchical", "Archiplata", "widdifow", "apathic", "overline", "chaetophoraceous", "creaky", "trichosporange", "uninterlined", "cometwise", "hermeneut", "unbedraggled", "tagged", "Sminthurus", "somniloquacious", "aphasiac", "Inoperculata", "photoactivity", "mobship", "unblightedly", "lievrite", "Khoja", "Falerian", "milfoil", "protectingly", "householder", "cathedra", "calmingly", "tordrillite", "rearhorse", "Leonard", "maracock", "youngish", "kammererite", "metanephric", "Sageretia", "diplococcoid", "accelerative", "choreal", "metalogical", "recombination", "unimprison", "invocation", "syndetic", "toadback", "vaned", "cupholder", "metropolitanship", "paramandelic", "dermolysis", "Sheriyat", "rhabdus", "seducee", "encrinoid", "unsuppliable", "cololite", "timesaver", "preambulate", "sampling", "roaster", "springald", "densher", "protraditional", "naturalesque", "Hydrodamalis", "cytogenic", "shortly", "cryptogrammatical", "squat", "genual", "backspier", "solubleness", "macroanalytical", "overcovetousness", "Natalie", "cuprobismutite", "phratriac", "Montanize", "hymnologist", "karyomiton", "podger", "unofficiousness", "antisplasher", "supraclavicular", "calidity", "disembellish", "antepredicament", "recurvirostral", "pulmonifer", "coccidial", "botonee", "protoglobulose", "isonym", "myeloid", "premiership", "unmonopolize", "unsesquipedalian", "unfelicitously", "theftbote", "undauntable", "lob", "praenomen", "underriver", "gorfly", "pluckage", "radiovision", "tyrantship", "fraught", "doppelkummel", "rowan", "allosyndetic", "kinesiology", "psychopath", "arrent", "amusively", "preincorporation", "Montargis", "pentacron", "neomedievalism", "sima", "lichenicolous", "Ecclesiastes", "woofed", "cardinalist", "sandaracin", "gymnasial", "lithoglyptics", "centimeter", "quadrupedous", "phraseology", "tumuli", "ankylotomy", "myrtol", "cohibitive", "lepospondylous", "silvendy", "inequipotential", "entangle", "raveling", "Zeugobranchiata", "devastating", "grainage", "amphisbaenian", "blady", "cirrose", "proclericalism", "governmentalist", "carcinomorphic", "nurtureship", "clancular", "unsteamed", "discernibly", "pleurogenic", "impalpability", "Azotobacterieae", "sarcoplasmic", "alternant", "fitly", "acrorrheuma", "shrapnel", "pastorize", "gulflike", "foreglow", "unrelated", "cirriped", "cerviconasal", "sexuale", "pussyfooter", "gadolinic", "duplicature", "codelinquency", "trypanolysis", "pathophobia", "incapsulation", "nonaerating", "feldspar", "diaphonic", "epiglottic", "depopulator", "wisecracker", "gravitational", "kuba", "lactesce", "Toxotes", "periomphalic", "singstress", "fannier", "counterformula", "Acemetae", "repugnatorial", "collimator", "Acinetina", "unpeace", "drum", "tetramorphic", "descendentalism", "cementer", "supraloral", "intercostal", "Nipponize", "negotiator", "vacationless", "synthol", "fissureless", "resoap", "pachycarpous", "reinspiration", "misappropriation", "disdiazo", "unheatable", "streng", "Detroiter", "infandous", "loganiaceous", "desugar", "Matronalia", "myxocystoma", "Gandhiism", "kiddier", "relodge", "counterreprisal", "recentralize", "foliously", "reprinter", "gender", "edaciousness", "chondriomite", "concordant", "stockrider", "pedary", "shikra", "blameworthiness", "vaccina", "Thamnophilinae", "wrongwise", "unsuperannuated", "convalescency", "intransmutable", "dropcloth", "Ceriomyces", "ponderal", "unstentorian", "mem", "deceleration", "ethionic", "untopped", "wetback", "bebar", "undecaying", "shoreside", "energize", "presacral", "undismay", "agricolite", "cowheart", "hemibathybian", "postexilian", "Phacidiaceae", "offing", "redesignation", "skeptically", "physicianless", "bronchopathy", "marabuto", "proprietory", "unobtruded", "funmaker", "plateresque", "preadventure", "beseeching", "cowpath", "pachycephalia", "arthresthesia", "supari", "lengthily", "Nepa", "liberation", "nigrify", "belfry", "entoolitic", "bazoo", "pentachromic", "distinguishable", "slideable", "galvanoscope", "remanage", "cetene", "bocardo", "consummation", "boycottism", "perplexity", "astay", "Gaetuli", "periplastic", "consolidator", "sluggarding", "coracoscapular", "anangioid", "oxygenizer", "Hunanese", "seminary", "periplast", "Corylus", "unoriginativeness", "persecutee", "tweaker", "silliness", "Dabitis", "facetiousness", "thymy", "nonimperial", "mesoblastema", "turbiniform", "churchway", "cooing", "frithbot", "concomitantly", "stalwartize", "clingfish", "hardmouthed", "parallelepipedonal", "coracoacromial", "factuality", "curtilage", "arachnoidean", "semiaridity", "phytobacteriology", "premastery", "hyperpurist", "mobed", "opportunistic", "acclimature", "outdistance", "sophister", "condonement", "oxygenerator", "acetonic", "emanatory", "periphlebitis", "nonsociety", "spectroradiometric", "superaverage", "cleanness", "posteroventral", "unadvised", "unmistakedly", "pimgenet", "auresca", "overimitate", "dipnoan", "chromoxylograph", "triakistetrahedron", "Suessiones", "uncopiable", "oligomenorrhea", "fribbling", "worriable", "flot", "ornithotrophy", "phytoteratology", "setup", "lanneret", "unbraceleted", "gudemother", "Spica", "unconsolatory", "recorruption", "premenstrual", "subretinal", "millennialist", "subjectibility", "rewardproof", "counterflight", "pilomotor", "carpetbaggery", "macrodiagonal", "slim", "indiscernible", "cuckoo", "moted", "controllingly", "gynecopathy", "porrectus", "wanworth", "lutfisk", "semiprivate", "philadelphy", "abdominothoracic", "coxcomb", "dambrod", "Metanemertini", "balminess", "homotypy", "waremaker", "absurdity", "gimcrack", "asquat", "suitable", "perimorphous", "kitchenwards", "pielum", "salloo", "paleontologic", "Olson", "Tellinidae", "ferryman", "peptonoid", "Bopyridae", "fallacy", "ictuate", "aguinaldo", "rhyodacite", "Ligydidae", "galvanometric", "acquisitor", "muscology", "hemikaryon", "ethnobotanic", "postganglionic", "rudimentarily", "replenish", "phyllorhine", "popgunnery", "summar", "quodlibetary", "xanthochromia", "autosymbolically", "preloreal", "extent", "strawberry", "immortalness", "colicwort", "frisca", "electiveness", "heartbroken", "affrightingly", "reconfiscation", "jacchus", "imponderably", "semantics", "beennut", "paleometeorological", "becost", "timberwright", "resuppose", "syncategorematical", "cytolymph", "steinbok", "explantation", "hyperelliptic", "antescript", "blowdown", "antinomical", "caravanserai", "unweariedly", "isonymic", "keratoplasty", "vipery", "parepigastric", "endolymphatic", "Londonese", "necrotomy", "angelship", "Schizogregarinida", "steeplebush", "sparaxis", "connectedness", "tolerance", "impingent", "agglutinin", "reviver", "hieroglyphical", "dialogize", "coestate", "declamatory", "ventilation", "tauromachy", "cotransubstantiate", "pome", "underseas", "triquadrantal", "preconfinemnt", "electroindustrial", "selachostomous", "nongolfer", "mesalike", "hamartiology", "ganglioblast", "unsuccessive", "yallow", "bacchanalianly", "platydactyl", "Bucephala", "ultraurgent", "penalist", "catamenial", "lynnhaven", "unrelevant", "lunkhead", "metropolitan", "hydro", "outsoar", "vernant", "interlanguage", "catarrhal", "Ionicize", "keelless", "myomantic", "booker", "Xanthomonas", "unimpeded", "overfeminize", "speronaro", "diaconia", "overholiness", "liquefacient", "Spartium", "haggly", "albumose", "nonnecessary", "sulcalization", "decapitate", "cellated", "unguirostral", "trichiurid", "loveproof", "amakebe", "screet", "arsenoferratin", "unfrizz", "undiscoverable", "procollectivistic", "tractile", "Winona", "dermostosis", "eliminant", "scomberoid", "tensile", "typesetting", "xylic", "dermatopathology", "cycloplegic", "revocable", "fissate", "afterplay", "screwship", "microerg", "bentonite", "stagecoaching", "beglerbeglic", "overcharitably", "Plotinism", "Veddoid", "disequalize", "cytoproct", "trophophore", "antidote", "allerion", "famous", "convey", "postotic", "rapillo", "cilectomy", "penkeeper", "patronym", "bravely", "ureteropyelitis", "Hildebrandine", "missileproof", "Conularia", "deadening", "Conrad", "pseudochylous", "typologically", "strummer", "luxuriousness", "resublimation", "glossiness", "hydrocauline", "anaglyph", "personifiable", "seniority", "formulator", "datiscaceous", "hydracrylate", "Tyranni", "Crawthumper", "overprove", "masher", "dissonance", "Serpentinian", "malachite", "interestless", "stchi", "ogum", "polyspermic", "archegoniate", "precogitation", "Alkaphrah", "craggily", "delightfulness", "bioplast", "diplocaulescent", "neverland", "interspheral", "chlorhydric", "forsakenly", "scandium", "detubation", "telega", "Valeriana", "centraxonial", "anabolite", "neger", "miscellanea", "whalebacker", "stylidiaceous", "unpropelled", "Kennedya", "Jacksonite", "ghoulish", "Dendrocalamus", "paynimhood", "rappist", "unluffed", "falling", "Lyctus", "uncrown", "warmly", "pneumatism", "Morisonian", "notate", "isoagglutinin", "Pelidnota", "previsit", "contradistinctly", "utter", "porometer", "gie", "germanization", "betwixt", "prenephritic", "underpier", "Eleutheria", "ruthenious", "convertor", "antisepsin", "winterage", "tetramethylammonium", "Rockaway", "Penaea", "prelatehood", "brisket", "unwishful", "Minahassa", "Briareus", "semiaxis", "disintegrant", "peastick", "iatromechanical", "fastus", "thymectomy", "ladyless", "unpreened", "overflutter", "sicker", "apsidally", "thiazine", "guideway", "pausation", "tellinoid", "abrogative", "foraminulate", "omphalos", "Monorhina", "polymyarian", "unhelpful", "newslessness", "oryctognosy", "octoradial", "doxology", "arrhythmy", "gugal", "mesityl", "hexaplaric", "Cabirian", "hordeiform", "eddyroot", "internarial", "deservingness", "jawbation", "orographically", "semiprecious", "seasick", "thermically", "grew", "tamability", "egotistically", "fip", "preabsorbent", "leptochroa", "ethnobotany", "podolite", "egoistic", "semitropical", "cero", "spinelessness", "onshore", "omlah", "tintinnabulist", "machila", "entomotomy", "nubile", "nonscholastic", "burnt", "Alea", "befume", "doctorless", "Napoleonic", "scenting", "apokreos", "cresylene", "paramide", "rattery", "disinterested", "idiopathetic", "negatory", "fervid", "quintato", "untricked", "Metrosideros", "mescaline", "midverse", "Musophagidae", "fictionary", "branchiostegous", "yoker", "residuum", "culmigenous", "fleam", "suffragism", "Anacreon", "sarcodous", "parodistic", "writmaking", "conversationism", "retroposed", "tornillo", "presuspect", "didymous", "Saumur", "spicing", "drawbridge", "cantor", "incumbrancer", "heterospory", "Turkeydom", "anteprandial", "neighborship", "thatchless", "drepanoid", "lusher", "paling", "ecthlipsis", "heredosyphilitic", "although", "garetta", "temporarily", "Monotropa", "proglottic", "calyptro", "persiflage", "degradable", "paraspecific", "undecorative", "Pholas", "myelon", "resteal", "quadrantly", "scrimped", "airer", "deviless", "caliciform", "Sefekhet", "shastaite", "togate", "macrostructure", "bipyramid", "wey", "didynamy", "knacker", "swage", "supermanism", "epitheton", "overpresumptuous" ] @inline(never) func benchSortStrings(_ words: [String]) { // Notice that we _copy_ the array of words before we sort it. // Pass an explicit '<' predicate to benchmark reabstraction thunks. var tempwords = words tempwords.sort(by: <) } public func run_SortStrings(_ n: Int) { for _ in 1...5*n { benchSortStrings(words) } } public func run_SortSortedStrings(_ n: Int) { for _ in 1...5*n { benchSortStrings(sortedWords) } } let unicodeWords: [String] = [ "❄️woodshed", "❄️lakism", "❄️gastroperiodynia", "❄️afetal", "❄️ramsch", "❄️Nickieben", "❄️undutifulness", "❄️birdglue", "❄️ungentlemanize", "❄️menacingly", "❄️heterophile", "❄️leoparde", "❄️Casearia", "❄️decorticate", "❄️neognathic", "❄️mentionable", "❄️tetraphenol", "❄️pseudonymal", "❄️dislegitimate", "❄️Discoidea", "❄️intitule", "❄️ionium", "❄️Lotuko", "❄️timbering", "❄️nonliquidating", "❄️oarialgia", "❄️Saccobranchus", "❄️reconnoiter", "❄️criminative", "❄️disintegratory", "❄️executer", "❄️Cylindrosporium", "❄️complimentation", "❄️Ixiama", "❄️Araceae", "❄️silaginoid", "❄️derencephalus", "❄️Lamiidae", "❄️marrowlike", "❄️ninepin", "❄️dynastid", "❄️lampfly", "❄️feint", "❄️trihemimer", "❄️semibarbarous", "❄️heresy", "❄️tritanope", "❄️indifferentist", "❄️confound", "❄️hyperbolaeon", "❄️planirostral", "❄️philosophunculist", "❄️existence", "❄️fretless", "❄️Leptandra", "❄️Amiranha", "❄️handgravure", "❄️gnash", "❄️unbelievability", "❄️orthotropic", "❄️Susumu", "❄️teleutospore", "❄️sleazy", "❄️shapeliness", "❄️hepatotomy", "❄️exclusivism", "❄️stifler", "❄️cunning", "❄️isocyanuric", "❄️pseudepigraphy", "❄️carpetbagger", "❄️respectiveness", "❄️Jussi", "❄️vasotomy", "❄️proctotomy", "❄️ovatotriangular", "❄️aesthetic", "❄️schizogamy", "❄️disengagement", "❄️foray", "❄️haplocaulescent", "❄️noncoherent", "❄️astrocyte", "❄️unreverberated", "❄️presenile", "❄️lanson", "❄️enkraal", "❄️contemplative", "❄️Syun", "❄️sartage", "❄️unforgot", "❄️wyde", "❄️homeotransplant", "❄️implicational", "❄️forerunnership", "❄️calcaneum", "❄️stomatodeum", "❄️pharmacopedia", "❄️preconcessive", "❄️trypanosomatic", "❄️intracollegiate", "❄️rampacious", "❄️secundipara", "❄️isomeric", "❄️treehair", "❄️pulmonal", "❄️uvate", "❄️dugway", "❄️glucofrangulin", "❄️unglory", "❄️Amandus", "❄️icterogenetic", "❄️quadrireme", "❄️Lagostomus", "❄️brakeroot", "❄️anthracemia", "❄️fluted", "❄️protoelastose", "❄️thro", "❄️pined", "❄️Saxicolinae", "❄️holidaymaking", "❄️strigil", "❄️uncurbed", "❄️starling", "❄️redeemeress", "❄️Liliaceae", "❄️imparsonee", "❄️obtusish", "❄️brushed", "❄️mesally", "❄️probosciformed", "❄️Bourbonesque", "❄️histological", "❄️caroba", "❄️digestion", "❄️Vindemiatrix", "❄️triactinal", "❄️tattling", "❄️arthrobacterium", "❄️unended", "❄️suspectfulness", "❄️movelessness", "❄️chartist", "❄️Corynebacterium", "❄️tercer", "❄️oversaturation", "❄️Congoleum", "❄️antiskeptical", "❄️sacral", "❄️equiradiate", "❄️whiskerage", "❄️panidiomorphic", "❄️unplanned", "❄️anilopyrine", "❄️Queres", "❄️tartronyl", "❄️Ing", "❄️notehead", "❄️finestiller", "❄️weekender", "❄️kittenhood", "❄️competitrix", "❄️premillenarian", "❄️convergescence", "❄️microcoleoptera", "❄️slirt", "❄️asteatosis", "❄️Gruidae", "❄️metastome", "❄️ambuscader", "❄️untugged", "❄️uneducated", "❄️redistill", "❄️rushlight", "❄️freakish", "❄️dosology", "❄️papyrine", "❄️iconologist", "❄️Bidpai", "❄️prophethood", "❄️pneumotropic", "❄️chloroformize", "❄️intemperance", "❄️spongiform", "❄️superindignant", "❄️divider", "❄️starlit", "❄️merchantish", "❄️indexless", "❄️unidentifiably", "❄️coumarone", "❄️nomism", "❄️diaphanous", "❄️salve", "❄️option", "❄️anallantoic", "❄️paint", "❄️thiofurfuran", "❄️baddeleyite", "❄️Donne", "❄️heterogenicity", "❄️decess", "❄️eschynite", "❄️mamma", "❄️unmonarchical", "❄️Archiplata", "❄️widdifow", "❄️apathic", "❄️overline", "❄️chaetophoraceous", "❄️creaky", "❄️trichosporange", "❄️uninterlined", "❄️cometwise", "❄️hermeneut", "❄️unbedraggled", "❄️tagged", "❄️Sminthurus", "❄️somniloquacious", "❄️aphasiac", "❄️Inoperculata", "❄️photoactivity", "❄️mobship", "❄️unblightedly", "❄️lievrite", "❄️Khoja", "❄️Falerian", "❄️milfoil", "❄️protectingly", "❄️householder", "❄️cathedra", "❄️calmingly", "❄️tordrillite", "❄️rearhorse", "❄️Leonard", "❄️maracock", "❄️youngish", "❄️kammererite", "❄️metanephric", "❄️Sageretia", "❄️diplococcoid", "❄️accelerative", "❄️choreal", "❄️metalogical", "❄️recombination", "❄️unimprison", "❄️invocation", "❄️syndetic", "❄️toadback", "❄️vaned", "❄️cupholder", "❄️metropolitanship", "❄️paramandelic", "❄️dermolysis", "❄️Sheriyat", "❄️rhabdus", "❄️seducee", "❄️encrinoid", "❄️unsuppliable", "❄️cololite", "❄️timesaver", "❄️preambulate", "❄️sampling", "❄️roaster", "❄️springald", "❄️densher", "❄️protraditional", "❄️naturalesque", "❄️Hydrodamalis", "❄️cytogenic", "❄️shortly", "❄️cryptogrammatical", "❄️squat", "❄️genual", "❄️backspier", "❄️solubleness", "❄️macroanalytical", "❄️overcovetousness", "❄️Natalie", "❄️cuprobismutite", "❄️phratriac", "❄️Montanize", "❄️hymnologist", "❄️karyomiton", "❄️podger", "❄️unofficiousness", "❄️antisplasher", "❄️supraclavicular", "❄️calidity", "❄️disembellish", "❄️antepredicament", "❄️recurvirostral", "❄️pulmonifer", "❄️coccidial", "❄️botonee", "❄️protoglobulose", "❄️isonym", "❄️myeloid", "❄️premiership", "❄️unmonopolize", "❄️unsesquipedalian", "❄️unfelicitously", "❄️theftbote", "❄️undauntable", "❄️lob", "❄️praenomen", "❄️underriver", "❄️gorfly", "❄️pluckage", "❄️radiovision", "❄️tyrantship", "❄️fraught", "❄️doppelkummel", "❄️rowan", "❄️allosyndetic", "❄️kinesiology", "❄️psychopath", "❄️arrent", "❄️amusively", "❄️preincorporation", "❄️Montargis", "❄️pentacron", "❄️neomedievalism", "❄️sima", "❄️lichenicolous", "❄️Ecclesiastes", "❄️woofed", "❄️cardinalist", "❄️sandaracin", "❄️gymnasial", "❄️lithoglyptics", "❄️centimeter", "❄️quadrupedous", "❄️phraseology", "❄️tumuli", "❄️ankylotomy", "❄️myrtol", "❄️cohibitive", "❄️lepospondylous", "❄️silvendy", "❄️inequipotential", "❄️entangle", "❄️raveling", "❄️Zeugobranchiata", "❄️devastating", "❄️grainage", "❄️amphisbaenian", "❄️blady", "❄️cirrose", "❄️proclericalism", "❄️governmentalist", "❄️carcinomorphic", "❄️nurtureship", "❄️clancular", "❄️unsteamed", "❄️discernibly", "❄️pleurogenic", "❄️impalpability", "❄️Azotobacterieae", "❄️sarcoplasmic", "❄️alternant", "❄️fitly", "❄️acrorrheuma", "❄️shrapnel", "❄️pastorize", "❄️gulflike", "❄️foreglow", "❄️unrelated", "❄️cirriped", "❄️cerviconasal", "❄️sexuale", "❄️pussyfooter", "❄️gadolinic", "❄️duplicature", "❄️codelinquency", "❄️trypanolysis", "❄️pathophobia", "❄️incapsulation", "❄️nonaerating", "❄️feldspar", "❄️diaphonic", "❄️epiglottic", "❄️depopulator", "❄️wisecracker", "❄️gravitational", "❄️kuba", "❄️lactesce", "❄️Toxotes", "❄️periomphalic", "❄️singstress", "❄️fannier", "❄️counterformula", "❄️Acemetae", "❄️repugnatorial", "❄️collimator", "❄️Acinetina", "❄️unpeace", "❄️drum", "❄️tetramorphic", "❄️descendentalism", "❄️cementer", "❄️supraloral", "❄️intercostal", "❄️Nipponize", "❄️negotiator", "❄️vacationless", "❄️synthol", "❄️fissureless", "❄️resoap", "❄️pachycarpous", "❄️reinspiration", "❄️misappropriation", "❄️disdiazo", "❄️unheatable", "❄️streng", "❄️Detroiter", "❄️infandous", "❄️loganiaceous", "❄️desugar", "❄️Matronalia", "❄️myxocystoma", "❄️Gandhiism", "❄️kiddier", "❄️relodge", "❄️counterreprisal", "❄️recentralize", "❄️foliously", "❄️reprinter", "❄️gender", "❄️edaciousness", "❄️chondriomite", "❄️concordant", "❄️stockrider", "❄️pedary", "❄️shikra", "❄️blameworthiness", "❄️vaccina", "❄️Thamnophilinae", "❄️wrongwise", "❄️unsuperannuated", "❄️convalescency", "❄️intransmutable", "❄️dropcloth", "❄️Ceriomyces", "❄️ponderal", "❄️unstentorian", "❄️mem", "❄️deceleration", "❄️ethionic", "❄️untopped", "❄️wetback", "❄️bebar", "❄️undecaying", "❄️shoreside", "❄️energize", "❄️presacral", "❄️undismay", "❄️agricolite", "❄️cowheart", "❄️hemibathybian", "❄️postexilian", "❄️Phacidiaceae", "❄️offing", "❄️redesignation", "❄️skeptically", "❄️physicianless", "❄️bronchopathy", "❄️marabuto", "❄️proprietory", "❄️unobtruded", "❄️funmaker", "❄️plateresque", "❄️preadventure", "❄️beseeching", "❄️cowpath", "❄️pachycephalia", "❄️arthresthesia", "❄️supari", "❄️lengthily", "❄️Nepa", "❄️liberation", "❄️nigrify", "❄️belfry", "❄️entoolitic", "❄️bazoo", "❄️pentachromic", "❄️distinguishable", "❄️slideable", "❄️galvanoscope", "❄️remanage", "❄️cetene", "❄️bocardo", "❄️consummation", "❄️boycottism", "❄️perplexity", "❄️astay", "❄️Gaetuli", "❄️periplastic", "❄️consolidator", "❄️sluggarding", "❄️coracoscapular", "❄️anangioid", "❄️oxygenizer", "❄️Hunanese", "❄️seminary", "❄️periplast", "❄️Corylus", "❄️unoriginativeness", "❄️persecutee", "❄️tweaker", "❄️silliness", "❄️Dabitis", "❄️facetiousness", "❄️thymy", "❄️nonimperial", "❄️mesoblastema", "❄️turbiniform", "❄️churchway", "❄️cooing", "❄️frithbot", "❄️concomitantly", "❄️stalwartize", "❄️clingfish", "❄️hardmouthed", "❄️parallelepipedonal", "❄️coracoacromial", "❄️factuality", "❄️curtilage", "❄️arachnoidean", "❄️semiaridity", "❄️phytobacteriology", "❄️premastery", "❄️hyperpurist", "❄️mobed", "❄️opportunistic", "❄️acclimature", "❄️outdistance", "❄️sophister", "❄️condonement", "❄️oxygenerator", "❄️acetonic", "❄️emanatory", "❄️periphlebitis", "❄️nonsociety", "❄️spectroradiometric", "❄️superaverage", "❄️cleanness", "❄️posteroventral", "❄️unadvised", "❄️unmistakedly", "❄️pimgenet", "❄️auresca", "❄️overimitate", "❄️dipnoan", "❄️chromoxylograph", "❄️triakistetrahedron", "❄️Suessiones", "❄️uncopiable", "❄️oligomenorrhea", "❄️fribbling", "❄️worriable", "❄️flot", "❄️ornithotrophy", "❄️phytoteratology", "❄️setup", "❄️lanneret", "❄️unbraceleted", "❄️gudemother", "❄️Spica", "❄️unconsolatory", "❄️recorruption", "❄️premenstrual", "❄️subretinal", "❄️millennialist", "❄️subjectibility", "❄️rewardproof", "❄️counterflight", "❄️pilomotor", "❄️carpetbaggery", "❄️macrodiagonal", "❄️slim", "❄️indiscernible", "❄️cuckoo", "❄️moted", "❄️controllingly", "❄️gynecopathy", "❄️porrectus", "❄️wanworth", "❄️lutfisk", "❄️semiprivate", "❄️philadelphy", "❄️abdominothoracic", "❄️coxcomb", "❄️dambrod", "❄️Metanemertini", "❄️balminess", "❄️homotypy", "❄️waremaker", "❄️absurdity", "❄️gimcrack", "❄️asquat", "❄️suitable", "❄️perimorphous", "❄️kitchenwards", "❄️pielum", "❄️salloo", "❄️paleontologic", "❄️Olson", "❄️Tellinidae", "❄️ferryman", "❄️peptonoid", "❄️Bopyridae", "❄️fallacy", "❄️ictuate", "❄️aguinaldo", "❄️rhyodacite", "❄️Ligydidae", "❄️galvanometric", "❄️acquisitor", "❄️muscology", "❄️hemikaryon", "❄️ethnobotanic", "❄️postganglionic", "❄️rudimentarily", "❄️replenish", "❄️phyllorhine", "❄️popgunnery", "❄️summar", "❄️quodlibetary", "❄️xanthochromia", "❄️autosymbolically", "❄️preloreal", "❄️extent", "❄️strawberry", "❄️immortalness", "❄️colicwort", "❄️frisca", "❄️electiveness", "❄️heartbroken", "❄️affrightingly", "❄️reconfiscation", "❄️jacchus", "❄️imponderably", "❄️semantics", "❄️beennut", "❄️paleometeorological", "❄️becost", "❄️timberwright", "❄️resuppose", "❄️syncategorematical", "❄️cytolymph", "❄️steinbok", "❄️explantation", "❄️hyperelliptic", "❄️antescript", "❄️blowdown", "❄️antinomical", "❄️caravanserai", "❄️unweariedly", "❄️isonymic", "❄️keratoplasty", "❄️vipery", "❄️parepigastric", "❄️endolymphatic", "❄️Londonese", "❄️necrotomy", "❄️angelship", "❄️Schizogregarinida", "❄️steeplebush", "❄️sparaxis", "❄️connectedness", "❄️tolerance", "❄️impingent", "❄️agglutinin", "❄️reviver", "❄️hieroglyphical", "❄️dialogize", "❄️coestate", "❄️declamatory", "❄️ventilation", "❄️tauromachy", "❄️cotransubstantiate", "❄️pome", "❄️underseas", "❄️triquadrantal", "❄️preconfinemnt", "❄️electroindustrial", "❄️selachostomous", "❄️nongolfer", "❄️mesalike", "❄️hamartiology", "❄️ganglioblast", "❄️unsuccessive", "❄️yallow", "❄️bacchanalianly", "❄️platydactyl", "❄️Bucephala", "❄️ultraurgent", "❄️penalist", "❄️catamenial", "❄️lynnhaven", "❄️unrelevant", "❄️lunkhead", "❄️metropolitan", "❄️hydro", "❄️outsoar", "❄️vernant", "❄️interlanguage", "❄️catarrhal", "❄️Ionicize", "❄️keelless", "❄️myomantic", "❄️booker", "❄️Xanthomonas", "❄️unimpeded", "❄️overfeminize", "❄️speronaro", "❄️diaconia", "❄️overholiness", "❄️liquefacient", "❄️Spartium", "❄️haggly", "❄️albumose", "❄️nonnecessary", "❄️sulcalization", "❄️decapitate", "❄️cellated", "❄️unguirostral", "❄️trichiurid", "❄️loveproof", "❄️amakebe", "❄️screet", "❄️arsenoferratin", "❄️unfrizz", "❄️undiscoverable", "❄️procollectivistic", "❄️tractile", "❄️Winona", "❄️dermostosis", "❄️eliminant", "❄️scomberoid", "❄️tensile", "❄️typesetting", "❄️xylic", "❄️dermatopathology", "❄️cycloplegic", "❄️revocable", "❄️fissate", "❄️afterplay", "❄️screwship", "❄️microerg", "❄️bentonite", "❄️stagecoaching", "❄️beglerbeglic", "❄️overcharitably", "❄️Plotinism", "❄️Veddoid", "❄️disequalize", "❄️cytoproct", "❄️trophophore", "❄️antidote", "❄️allerion", "❄️famous", "❄️convey", "❄️postotic", "❄️rapillo", "❄️cilectomy", "❄️penkeeper", "❄️patronym", "❄️bravely", "❄️ureteropyelitis", "❄️Hildebrandine", "❄️missileproof", "❄️Conularia", "❄️deadening", "❄️Conrad", "❄️pseudochylous", "❄️typologically", "❄️strummer", "❄️luxuriousness", "❄️resublimation", "❄️glossiness", "❄️hydrocauline", "❄️anaglyph", "❄️personifiable", "❄️seniority", "❄️formulator", "❄️datiscaceous", "❄️hydracrylate", "❄️Tyranni", "❄️Crawthumper", "❄️overprove", "❄️masher", "❄️dissonance", "❄️Serpentinian", "❄️malachite", "❄️interestless", "❄️stchi", "❄️ogum", "❄️polyspermic", "❄️archegoniate", "❄️precogitation", "❄️Alkaphrah", "❄️craggily", "❄️delightfulness", "❄️bioplast", "❄️diplocaulescent", "❄️neverland", "❄️interspheral", "❄️chlorhydric", "❄️forsakenly", "❄️scandium", "❄️detubation", "❄️telega", "❄️Valeriana", "❄️centraxonial", "❄️anabolite", "❄️neger", "❄️miscellanea", "❄️whalebacker", "❄️stylidiaceous", "❄️unpropelled", "❄️Kennedya", "❄️Jacksonite", "❄️ghoulish", "❄️Dendrocalamus", "❄️paynimhood", "❄️rappist", "❄️unluffed", "❄️falling", "❄️Lyctus", "❄️uncrown", "❄️warmly", "❄️pneumatism", "❄️Morisonian", "❄️notate", "❄️isoagglutinin", "❄️Pelidnota", "❄️previsit", "❄️contradistinctly", "❄️utter", "❄️porometer", "❄️gie", "❄️germanization", "❄️betwixt", "❄️prenephritic", "❄️underpier", "❄️Eleutheria", "❄️ruthenious", "❄️convertor", "❄️antisepsin", "❄️winterage", "❄️tetramethylammonium", "❄️Rockaway", "❄️Penaea", "❄️prelatehood", "❄️brisket", "❄️unwishful", "❄️Minahassa", "❄️Briareus", "❄️semiaxis", "❄️disintegrant", "❄️peastick", "❄️iatromechanical", "❄️fastus", "❄️thymectomy", "❄️ladyless", "❄️unpreened", "❄️overflutter", "❄️sicker", "❄️apsidally", "❄️thiazine", "❄️guideway", "❄️pausation", "❄️tellinoid", "❄️abrogative", "❄️foraminulate", "❄️omphalos", "❄️Monorhina", "❄️polymyarian", "❄️unhelpful", "❄️newslessness", "❄️oryctognosy", "❄️octoradial", "❄️doxology", "❄️arrhythmy", "❄️gugal", "❄️mesityl", "❄️hexaplaric", "❄️Cabirian", "❄️hordeiform", "❄️eddyroot", "❄️internarial", "❄️deservingness", "❄️jawbation", "❄️orographically", "❄️semiprecious", "❄️seasick", "❄️thermically", "❄️grew", "❄️tamability", "❄️egotistically", "❄️fip", "❄️preabsorbent", "❄️leptochroa", "❄️ethnobotany", "❄️podolite", "❄️egoistic", "❄️semitropical", "❄️cero", "❄️spinelessness", "❄️onshore", "❄️omlah", "❄️tintinnabulist", "❄️machila", "❄️entomotomy", "❄️nubile", "❄️nonscholastic", "❄️burnt", "❄️Alea", "❄️befume", "❄️doctorless", "❄️Napoleonic", "❄️scenting", "❄️apokreos", "❄️cresylene", "❄️paramide", "❄️rattery", "❄️disinterested", "❄️idiopathetic", "❄️negatory", "❄️fervid", "❄️quintato", "❄️untricked", "❄️Metrosideros", "❄️mescaline", "❄️midverse", "❄️Musophagidae", "❄️fictionary", "❄️branchiostegous", "❄️yoker", "❄️residuum", "❄️culmigenous", "❄️fleam", "❄️suffragism", "❄️Anacreon", "❄️sarcodous", "❄️parodistic", "❄️writmaking", "❄️conversationism", "❄️retroposed", "❄️tornillo", "❄️presuspect", "❄️didymous", "❄️Saumur", "❄️spicing", "❄️drawbridge", "❄️cantor", "❄️incumbrancer", "❄️heterospory", "❄️Turkeydom", "❄️anteprandial", "❄️neighborship", "❄️thatchless", "❄️drepanoid", "❄️lusher", "❄️paling", "❄️ecthlipsis", "❄️heredosyphilitic", "❄️although", "❄️garetta", "❄️temporarily", "❄️Monotropa", "❄️proglottic", "❄️calyptro", "❄️persiflage", "❄️degradable", "❄️paraspecific", "❄️undecorative", "❄️Pholas", "❄️myelon", "❄️resteal", "❄️quadrantly", "❄️scrimped", "❄️airer", "❄️deviless", "❄️caliciform", "❄️Sefekhet", "❄️shastaite", "❄️togate", "❄️macrostructure", "❄️bipyramid", "❄️wey", "❄️didynamy", "❄️knacker", "❄️swage", "❄️supermanism", "❄️epitheton", "❄️overpresumptuous" ] public func run_SortStringsUnicode(_ n: Int) { for _ in 1...n { benchSortStrings(unicodeWords) } }
apache-2.0
b067525e40518d94f572e374660ef204
16.170874
80
0.586537
2.55062
false
false
false
false
GuiminChu/HishowZone-iOS
HiShow/Features/TopicDetail/CoreText/CoreTextData.swift
1
2907
// // CoreTextData.swift // HiShow // // Created by Chu Guimin on 17/3/8. // Copyright © 2017年 cgm. All rights reserved. // import UIKit class CoreTextData: NSObject { var ctFrame: CTFrame var height: CGFloat var imageArray: [CoreTextImageData] = [CoreTextImageData]() { willSet { fillImagePosition(imageArray: newValue) } } init(ctFrame: CTFrame, height: CGFloat) { self.ctFrame = ctFrame self.height = height } private func fillImagePosition(imageArray: [CoreTextImageData]) { if imageArray.count == 0 { return } let lines = CTFrameGetLines(ctFrame) as Array var originsArray = [CGPoint](repeating: CGPoint.zero, count:lines.count) // 把 CTFrame 里每一行的初始坐标写到数组里 CTFrameGetLineOrigins(ctFrame, CFRangeMake(0, 0), &originsArray) var imgIndex : Int = 0 var imageData: CoreTextImageData? = imageArray[0] for index in 0..<lines.count { guard imageData != nil else { return } let line = lines[index] as! CTLine let runObjArray = CTLineGetGlyphRuns(line) as Array for runObj in runObjArray { let run = runObj as! CTRun let runAttributes = CTRunGetAttributes(run) as NSDictionary let delegate = runAttributes.value(forKey: kCTRunDelegateAttributeName as String) if delegate == nil { continue } var runBounds = CGRect() var ascent: CGFloat = 0 var descent: CGFloat = 0 runBounds.size.width = CGFloat(CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, nil)) runBounds.size.height = ascent + descent let xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil) runBounds.origin.x = originsArray[index].x + xOffset runBounds.origin.y = originsArray[index].y runBounds.origin.y -= descent let path = CTFrameGetPath(ctFrame) let colRect = path.boundingBox let delegateBounds = runBounds.offsetBy(dx: colRect.origin.x, dy: colRect.origin.y) imageData!.imagePosition = delegateBounds imgIndex += 1 if imgIndex == imageArray.count { imageData = nil break } else { imageData = imageArray[imgIndex] } } } } }
mit
80387df525dfcfeaaf64fd106b20a5da
31.659091
121
0.516354
5.068783
false
false
false
false
Constructor-io/constructorio-client-swift
AutocompleteClient/FW/Logic/Result/CIOSortOption.swift
1
1404
// // SortOption.swift // AutocompleteClient // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation /** Struct encapsulating a sort option */ public struct CIOSortOption { /** Display name of the sort option */ public let displayName: String /** The field to sort by */ public let sortBy: String /** The sort order (i.e. "ascending" or "descending") */ public let sortOrder: CIOSortOrder /** The status of the sort option (i.e. "selected") */ public let status: String } public extension CIOSortOption { /** Create a sort option - parameters - json: JSON data from the server response */ init?(json: JSONObject) { guard let displayName = json["display_name"] as? String else { return nil } guard let sortOrderStr = json["sort_order"] as? String else { return nil } guard let sortOrder = CIOSortOrder(rawValue: sortOrderStr) else { return nil } guard let sortBy = json["sort_by"] as? String else { return nil } guard let status = json["status"] as? String else { return nil } self.displayName = displayName self.sortBy = sortBy self.sortOrder = sortOrder self.status = status } } public enum CIOSortOrder: String { case ascending case descending }
mit
5d6fe5b64f334a59ee1294db65ddbb6f
22.383333
86
0.620813
4.213213
false
false
false
false
tinrobots/Mechanica
Sources/UIKit/UIDevice+Utils.swift
1
824
#if canImport(UIKit) && (os(iOS) || os(tvOS)) import UIKit extension UIDevice { // MARK: - Device Interface Type /// **Mechanica** /// /// Returns `true` if the interface is designed for iPhone or iPod. public var hasPhoneInterface: Bool { return userInterfaceIdiom == .phone } /// **Mechanica** /// /// Returns `true` if the interface is designed for iPad. public var hasPadInterface: Bool { return userInterfaceIdiom == .pad } /// **Mechanica** /// /// Returns `true` if the interface is designed for Apple TV. public var hasTVInterface: Bool { return userInterfaceIdiom == .tv } /// **Mechanica** /// /// Returns `true` if the interface is designed for Apple CarPlay. public var hasCarPlayInterface: Bool { return userInterfaceIdiom == .carPlay } } #endif
mit
fb87e1fbd681d0577388b6e7664e826e
21.27027
69
0.650485
4.161616
false
false
false
false
piwik/piwik-sdk-ios
Example/ios/iOS Example/UserIDViewController.swift
1
1839
import UIKit import MatomoTracker class UserIDViewController: UIViewController { @IBOutlet weak var userIDTextField: UITextField! @IBOutlet weak var signinButton: UIButton! @IBOutlet weak var signoutButton: UIButton! @IBOutlet weak var visitorIdTextField: UITextField! @IBAction func signinAction(_ sender: UIButton) { if (self.userIDTextField.text != nil) && (self.userIDTextField.text?.count)! > 0 { MatomoTracker.shared.userId = self.userIDTextField.text updateUserIdState() } } @IBAction func signOutAction(_ sender: UIButton) { MatomoTracker.shared.userId = nil updateUserIdState() } @IBAction func visitorIdTapped(_ sender: Any) { if (self.visitorIdTextField.text != nil) && (self.visitorIdTextField.text?.count)! > 0 { MatomoTracker.shared.forcedVisitorId = self.visitorIdTextField.text updateVisitorIdState() } } override func viewDidLoad() { super.viewDidLoad() updateUserIdState() updateVisitorIdState() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MatomoTracker.shared.track(view: ["menu","user id"]) } private func updateUserIdState() { self.userIDTextField.text = MatomoTracker.shared.userId self.signinButton.isEnabled = !isVisitorIdValid() self.signoutButton.isEnabled = !self.signinButton.isEnabled } private func updateVisitorIdState() { self.visitorIdTextField.text = MatomoTracker.shared.forcedVisitorId } private func isVisitorIdValid() -> Bool { let currentVisitorId = MatomoTracker.shared.userId return (currentVisitorId != nil) && (currentVisitorId?.count)! > 0 } }
mit
df46aade4fffcf9dc36b8d815c070d68
31.839286
96
0.656879
4.751938
false
false
false
false
exponent/exponent
packages/expo-dev-menu-interface/ios/MenuItems/DevMenuLink.swift
2
567
// Copyright 2015-present 650 Industries. All rights reserved. import Foundation @objc public class DevMenuLink: DevMenuScreenItem { var target: String @objc open var label: () -> String = { "" } @objc open var glyphName: () -> String = { "" } public init(withTarget target: String) { self.target = target super.init(type: .Link) } @objc open override func serialize() -> [String: Any] { var dict = super.serialize() dict["target"] = target dict["label"] = label() dict["glyphName"] = glyphName() return dict } }
bsd-3-clause
c6a20d5e9d4f4b6456d66841394661a8
19.25
62
0.631393
3.754967
false
false
false
false
afaan5556/toolbelt
xcode-toolbelt/ToolBelt/Map.swift
1
1453
// // Map.swift // ToolBelt // // Created by Peter Kang on 5/14/16. // Copyright © 2016 teamToolBelt. All rights reserved. // import MapKit import Alamofire class Map: UIViewController { func getLatandLong() {Alamofire.request(.GET, "http://localhost:3000") .responseJSON { response in if let JSON = response.result.value { print("\(JSON)") } } } @IBOutlet var map: MKMapView! override func viewDidLoad() { super.viewDidLoad() print("hey") getLatandLong() var latitude:CLLocationDegrees = 1.001 var longitude:CLLocationDegrees = 1.001 var latDelta:CLLocationDegrees = 0.05 var longDelta:CLLocationDegrees = 0.05 var span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta) var location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) var region: MKCoordinateRegion = MKCoordinateRegionMake(location, span) map.setRegion(region, animated: false) } // func annotate() { // // var annotation = MKPointAnnotation() // // annotation.coordinate = location // // annotation.title = "Niagra Falls" // // annotation.subtitle = "One day..." // // map.addAnnotation(annotation) // // } }
mit
5fe95800afeee1b304abf299921c080d
19.742857
102
0.572314
4.624204
false
false
false
false
greycats/Greycats.swift
Greycats/Graphics/Animation.swift
1
5488
import UIKit private func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } private func >= <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } private func <= <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } public protocol Animatable: AnyObject { func render(_ elapsedTime: TimeInterval) -> Bool func start() func stop() } class DisplayLink: NSObject { weak var animatable: Animatable? let end: (() -> Void)? var ended = false var lastDrawTime: CFTimeInterval = 0 var displayLink: CADisplayLink? fileprivate var pausedTime: CFTimeInterval? fileprivate var bindAppStatus = false required init(animatable: Animatable, end: (() -> Void)? = nil) { self.animatable = animatable self.end = end super.init() resume() } func invalidate() { displayLink?.invalidate() lastDrawTime = 0 displayLink = nil if !ended { end?() ended = true } } deinit { invalidate() if bindAppStatus { NotificationCenter.default.removeObserver(self) } } @objc func update() { guard let displayLink = displayLink else { return } guard let animatable = animatable else { invalidate() return } if lastDrawTime == 0 { lastDrawTime = displayLink.timestamp } if let time = pausedTime { lastDrawTime += displayLink.timestamp - time pausedTime = nil } let done = animatable.render(displayLink.timestamp - lastDrawTime) if done { invalidate() } } @objc func pause() { displayLink?.isPaused = true pausedTime = displayLink?.timestamp } @objc func resume() { if displayLink == nil { displayLink = CADisplayLink(target: self, selector: #selector(update)) displayLink?.add(to: RunLoop.main, forMode: RunLoop.Mode.common) } if !bindAppStatus { bindAppStatus = true NotificationCenter.default.addObserver(self, selector: #selector(resume), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(pause), name: UIApplication.willResignActiveNotification, object: nil) } displayLink?.isPaused = false } } private var displayLinkKey: Void? extension Animatable { public func start() { let displayLink = DisplayLink(animatable: self) objc_setAssociatedObject(self, &displayLinkKey, displayLink, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } public func stop() { objc_setAssociatedObject(self, &displayLinkKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } open class Animation { public enum Easing { case linear case quad case cubic case sin case cos case circle case exp case elastic(bounciness: Double) } public struct Value { let _value: (_ time: TimeInterval, _ easing: Easing) -> CGFloat public func value(_ time: TimeInterval, easing: Easing = .linear) -> CGFloat { return _value(time, easing) } } var displayLink: DisplayLink? public init() { } open func start(_ animatable: Animatable, end: (() -> Void)? = nil) { displayLink = DisplayLink(animatable: animatable, end: end) } open func stop() { displayLink = nil } } extension Animation.Easing { func calc(_ t: TimeInterval) -> TimeInterval { switch self { case .linear: return t case .quad: return t * t case .cubic: return t * t * t case .sin: return Foundation.sin(t * .pi / 2) case .cos: return Foundation.cos(t * .pi / 2) case .circle: return 1 - sqrt(1 - t * t) case .exp: return pow(2, 10 * (t - 1)) case .elastic(let bounciness): let p = bounciness * .pi return 1 - pow(Foundation.cos(t * .pi / 2), 3) * Foundation.cos(t * p) } } } extension Animation.Value { public static func interpolate(inputRange: [TimeInterval], outputRange: [CGFloat]) -> Animation.Value { return Animation.Value(_value: { time, fn in if time >= inputRange.last { return outputRange.last! } if time <= inputRange.first { return outputRange.first! } var found: Int = 0 for (index, input) in inputRange.enumerated() { if time >= input { found = index } else { break } } let a = inputRange[found], b = inputRange[found + 1], c = outputRange[found], d = outputRange[found + 1] let t = (time - a) / (b - a) let f = fn.calc(t) return CGFloat(f) * (d - c) + c }) } }
mit
7b9f15f6fb9fd21f78938a771696bd66
25.384615
147
0.542456
4.465419
false
false
false
false
zitao0322/ShopCar
Shoping_Car/Pods/RxDataSources/Sources/DataSources/AnimatableSectionModel.swift
3
1071
// // AnimatableSectionModel.swift // RxDataSources // // Created by Krunoslav Zaher on 1/10/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation public struct AnimatableSectionModel<Section: IdentifiableType, ItemType: protocol<IdentifiableType, Equatable>> : AnimatableSectionModelType , CustomStringConvertible { public typealias Item = ItemType public typealias Identity = Section.Identity public var model: Section public var items: [Item] public var identity: Section.Identity { return model.identity } public init(model: Section, items: [ItemType]) { self.model = model self.items = items } public init(original: AnimatableSectionModel, items: [Item]) { self.model = original.model self.items = items } public var description: String { return "HashableSectionModel(model: \"\(self.model)\", items: \(items))" } public var hashValue: Int { return self.model.identity.hashValue } }
mit
25e6c0ef4450d77897c914f1459f3a90
24.47619
112
0.662617
4.776786
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyer/Input/UserTextInputPageOperator.swift
1
2206
import UIKit class UserTextInputPageOperator { weak var delegate: UserTextInputPageDelegate? { didSet { if delegate != nil { registerKeyboardNotifications() } else { unregisterKeyboardNotifications() } } } fileprivate var activeTextField: UITextField? { get { if let delegate = delegate { for textField in delegate.textFields { if textField.isFirstResponder { return textField } } } return nil } } func registerKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(UserTextInputPageOperator.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(UserTextInputPageOperator.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func unregisterKeyboardNotifications() { NotificationCenter.default.removeObserver(self) } @objc func keyboardDidShow(_ notification: Notification) throws { guard let delegate = delegate else { throw BasicError(details: "UserTextInputPageOperator requires a UserTextInputPageDelegate to function") } let userInfo: NSDictionary = notification.userInfo! as NSDictionary let keyboardSize = (userInfo.object(forKey: UIKeyboardFrameBeginUserInfoKey)! as AnyObject).cgRectValue.size let contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0) delegate.pageScrollView.contentInset = contentInsets delegate.pageScrollView.scrollIndicatorInsets = contentInsets } @objc func keyboardWillHide(_ notification: Notification) throws { guard let delegate = delegate else { throw BasicError(details: "UserTextInputPageOperator requires a UserTextInputPageDelegate to function") } delegate.pageScrollView.contentInset = UIEdgeInsets.zero delegate.pageScrollView.scrollIndicatorInsets = UIEdgeInsets.zero } }
apache-2.0
e759dd618bab712c0e22f601293f614c
37.701754
180
0.666818
6.043836
false
false
false
false
ytakzk/Fusuma
Sources/FSCameraView.swift
1
13596
// // FSCameraView.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/14. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit import AVFoundation import CoreMotion import Photos @objc protocol FSCameraViewDelegate: class { func cameraShotFinished(_ image: UIImage) } final class FSCameraView: UIView, UIGestureRecognizerDelegate { @IBOutlet weak var previewViewContainer: UIView! @IBOutlet weak var shotButton: UIButton! @IBOutlet weak var flashButton: UIButton! @IBOutlet weak var flipButton: UIButton! @IBOutlet weak var fullAspectRatioConstraint: NSLayoutConstraint! var croppedAspectRatioConstraint: NSLayoutConstraint? var initialCaptureDevicePosition: AVCaptureDevice.Position = .back weak var delegate: FSCameraViewDelegate? = nil private var session: AVCaptureSession? private var device: AVCaptureDevice? private var videoInput: AVCaptureDeviceInput? private var imageOutput: AVCaptureStillImageOutput? private var videoLayer: AVCaptureVideoPreviewLayer? private var focusView: UIView? private var flashOffImage: UIImage? private var flashOnImage: UIImage? private var motionManager: CMMotionManager? private var currentDeviceOrientation: UIDeviceOrientation? private var zoomFactor: CGFloat = 1.0 static func instance() -> FSCameraView { return UINib(nibName: "FSCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSCameraView } func initialize() { guard session == nil else { return } self.backgroundColor = fusumaBackgroundColor let bundle = Bundle(for: self.classForCoder) flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil) flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil) let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil) let shotImage = fusumaShotImage != nil ? fusumaShotImage : UIImage(named: "ic_shutter", in: bundle, compatibleWith: nil) flashButton.tintColor = fusumaBaseTintColor flipButton.tintColor = fusumaBaseTintColor shotButton.tintColor = fusumaBaseTintColor flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: .normal) flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: .normal) shotButton.setImage(shotImage?.withRenderingMode(.alwaysTemplate), for: .normal) isHidden = false // AVCapture session = AVCaptureSession() guard let session = session else { return } for device in AVCaptureDevice.devices() { if device.position == initialCaptureDevicePosition { self.device = device if !device.hasFlash { flashButton.isHidden = true } } } if let device = device, let _videoInput = try? AVCaptureDeviceInput(device: device) { videoInput = _videoInput session.addInput(videoInput!) imageOutput = AVCaptureStillImageOutput() session.addOutput(imageOutput!) videoLayer = AVCaptureVideoPreviewLayer(session: session) videoLayer?.frame = previewViewContainer.bounds videoLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill previewViewContainer.layer.addSublayer(videoLayer!) session.sessionPreset = AVCaptureSession.Preset.photo session.startRunning() // Focus View focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90)) let tapRecognizer = UITapGestureRecognizer(target: self, action:#selector(FSCameraView.focus(_:))) tapRecognizer.delegate = self previewViewContainer.addGestureRecognizer(tapRecognizer) } flashConfiguration() startCamera() NotificationCenter.default.addObserver(self, selector: #selector(FSCameraView.willEnterForegroundNotification(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchToZoom)) previewViewContainer.addGestureRecognizer(pinchGestureRecognizer) } @objc func willEnterForegroundNotification(_ notification: Notification) { startCamera() } deinit { NotificationCenter.default.removeObserver(self) } func startCamera() { switch AVCaptureDevice.authorizationStatus(for: AVMediaType.video) { case .authorized: session?.startRunning() motionManager = CMMotionManager() motionManager!.accelerometerUpdateInterval = 0.2 motionManager!.startAccelerometerUpdates(to: OperationQueue()) { [unowned self] (data, _) in if let data = data { if abs(data.acceleration.y) < abs(data.acceleration.x) { self.currentDeviceOrientation = data.acceleration.x > 0 ? .landscapeRight : .landscapeLeft } else { self.currentDeviceOrientation = data.acceleration.y > 0 ? .portraitUpsideDown : .portrait } } } case .denied, .restricted: stopCamera() default: break } } func stopCamera() { session?.stopRunning() motionManager?.stopAccelerometerUpdates() currentDeviceOrientation = nil } @IBAction func shotButtonPressed(_ sender: UIButton) { guard let imageOutput = imageOutput else { return } DispatchQueue.global(qos: .default).async(execute: { () -> Void in guard let videoConnection = imageOutput.connection(with: AVMediaType.video) else { return } imageOutput.captureStillImageAsynchronously(from: videoConnection) { (buffer, error) -> Void in self.stopCamera() guard let buffer = buffer, let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer), let image = UIImage(data: data), let cgImage = image.cgImage, let delegate = self.delegate, let videoLayer = self.videoLayer else { return } let rect = videoLayer.metadataOutputRectConverted(fromLayerRect: videoLayer.bounds) let width = CGFloat(cgImage.width) let height = CGFloat(cgImage.height) let cropRect = CGRect(x: rect.origin.x * width, y: rect.origin.y * height, width: rect.size.width * width, height: rect.size.height * height) guard let img = cgImage.cropping(to: cropRect) else { return } let croppedUIImage = UIImage(cgImage: img, scale: 1.0, orientation: image.imageOrientation) DispatchQueue.main.async(execute: { () -> Void in delegate.cameraShotFinished(croppedUIImage) if fusumaSavesImage { self.saveImageToCameraRoll(image: croppedUIImage) } self.session = nil self.videoLayer = nil self.device = nil self.imageOutput = nil self.motionManager = nil }) } }) } @IBAction func flipButtonPressed(_ sender: UIButton) { guard cameraIsAvailable else { return } session?.stopRunning() do { session?.beginConfiguration() if let session = session { for input in session.inputs { session.removeInput(input) } let position = (videoInput?.device.position == AVCaptureDevice.Position.front) ? AVCaptureDevice.Position.back : AVCaptureDevice.Position.front for device in AVCaptureDevice.devices(for: AVMediaType.video) { if device.position == position { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput!) } } } session?.commitConfiguration() } catch { } session?.startRunning() } @IBAction func flashButtonPressed(_ sender: UIButton) { if !cameraIsAvailable { return } do { guard let device = device, device.hasFlash else { return } try device.lockForConfiguration() switch device.flashMode { case .off: device.flashMode = AVCaptureDevice.FlashMode.on flashButton.setImage(flashOnImage?.withRenderingMode(.alwaysTemplate), for: UIControl.State()) case .on: device.flashMode = AVCaptureDevice.FlashMode.off flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControl.State()) default: break } device.unlockForConfiguration() } catch _ { flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControl.State()) return } } @objc private func handlePinchToZoom(_ pinch: UIPinchGestureRecognizer) { guard let device = device else { return } func minMaxZoom(_ factor: CGFloat) -> CGFloat { return min(max(factor, 1.0), device.activeFormat.videoMaxZoomFactor) } func update(scale factor: CGFloat) { do { try device.lockForConfiguration() defer { device.unlockForConfiguration() } device.videoZoomFactor = factor } catch { debugPrint(error) } } let newScaleFactor = minMaxZoom(pinch.scale * zoomFactor) switch pinch.state { case .began: fallthrough case .changed: update(scale: newScaleFactor) case .ended: zoomFactor = minMaxZoom(newScaleFactor) update(scale: zoomFactor) default: break } } } fileprivate extension FSCameraView { func saveImageToCameraRoll(image: UIImage) { PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAsset(from: image) }, completionHandler: nil) } @objc func focus(_ recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: self) let viewsize = self.bounds.size let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width) guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return } do { try device.lockForConfiguration() } catch _ { return } if device.isFocusModeSupported(AVCaptureDevice.FocusMode.autoFocus) == true { device.focusMode = AVCaptureDevice.FocusMode.autoFocus device.focusPointOfInterest = newPoint } if device.isExposureModeSupported(AVCaptureDevice.ExposureMode.continuousAutoExposure) == true { device.exposureMode = AVCaptureDevice.ExposureMode.continuousAutoExposure device.exposurePointOfInterest = newPoint } device.unlockForConfiguration() guard let focusView = self.focusView else { return } focusView.alpha = 0.0 focusView.center = point focusView.backgroundColor = UIColor.clear focusView.layer.borderColor = fusumaBaseTintColor.cgColor focusView.layer.borderWidth = 1.0 focusView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) addSubview(focusView) UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 3.0, options: UIView.AnimationOptions.curveEaseIn, animations:{ focusView.alpha = 1.0 focusView.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) }, completion: {(finished) in focusView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) focusView.removeFromSuperview() }) } func flashConfiguration() { do { if let device = device { guard device.hasFlash else { return } try device.lockForConfiguration() device.flashMode = AVCaptureDevice.FlashMode.off flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControl.State()) device.unlockForConfiguration() } } catch _ { return } } var cameraIsAvailable: Bool { let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) if status == AVAuthorizationStatus.authorized { return true } return false } }
mit
dd65e71b53ff3f29fa103b2afad41cbb
34.677165
189
0.607298
5.774427
false
false
false
false
kimberlyz/Hint-Hint
BLE Test/Extensions.swift
1
5883
// // Extensions.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 10/14/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import Foundation import CoreBluetooth extension NSData { func hexRepresentationWithSpaces(spaces:Bool) ->NSString { var byteArray = [UInt8](count: self.length, repeatedValue: 0x0) // The Test Data is moved into the 8bit Array. self.getBytes(&byteArray, length:self.length) var hexBits = "" as String for value in byteArray { let newHex = NSString(format:"0x%2X", value) as String hexBits += newHex.stringByReplacingOccurrencesOfString(" ", withString: "0", options: NSStringCompareOptions.CaseInsensitiveSearch) if spaces { hexBits += " " } } return hexBits } func hexRepresentation()->String { let dataLength:Int = self.length let string = NSMutableString(capacity: dataLength*2) let dataBytes:UnsafePointer<Void> = self.bytes for idx in 0..<dataLength { string.appendFormat("%02x", [UInt(dataBytes[idx])] ) } return string as String } func stringRepresentation()->String { //Write new received data to the console text view //convert data to string & replace characters we can't display let dataLength:Int = self.length var data = [UInt8](count: dataLength, repeatedValue: 0) self.getBytes(&data, length: dataLength) for index in 0..<dataLength { if (data[index] <= 0x1f) || (data[index] >= 0x80) { //null characters if (data[index] != 0x9) //0x9 == TAB && (data[index] != 0xa) //0xA == NL && (data[index] != 0xd) { //0xD == CR data[index] = 0xA9 } } } let newString = NSString(bytes: &data, length: dataLength, encoding: NSUTF8StringEncoding) return newString! as String } } extension NSString { func toHexSpaceSeparated() ->NSString { let len = UInt(self.length) var charArray = [unichar](count: self.length, repeatedValue: 0x0) // let chars = UnsafeMutablePointer<unichar>(malloc(len * UInt(sizeofValue(unichar)))) self.getCharacters(&charArray) let hexString = NSMutableString() var charString:NSString for i in 0..<len { charString = NSString(format: "0x%02X", charArray[Int(i)]) if (charString.length == 1){ charString = "0".stringByAppendingString(charString as String) } hexString.appendString(charString.stringByAppendingString(" ")) } return hexString } } extension CBUUID { func representativeString() ->NSString{ let data = self.data var byteArray = [UInt8](count: data.length, repeatedValue: 0x0) data.getBytes(&byteArray, length:data.length) let outputString = NSMutableString(capacity: 16) for value in byteArray { switch (value){ case 9: outputString.appendFormat("%02x-", value) break default: outputString.appendFormat("%02x", value) } } return outputString } func equalsString(toString:String, caseSensitive:Bool, omitDashes:Bool)->Bool { var aString = toString var verdict = false var options = NSStringCompareOptions.CaseInsensitiveSearch if omitDashes == true { aString = toString.stringByReplacingOccurrencesOfString("-", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) } if caseSensitive == true { options = NSStringCompareOptions.LiteralSearch } // println("\(self.representativeString()) ?= \(aString)") verdict = aString.compare(self.representativeString() as String, options: options, range: nil, locale: NSLocale.currentLocale()) == NSComparisonResult.OrderedSame return verdict } } func printLog(obj:AnyObject, funcName:String, logString:String) { if LOGGING != true { return } print("\(obj.classForCoder?.description()) \(funcName) : \(logString)") } func binaryforByte(value: UInt8) -> String { var str = String(value, radix: 2) let len = str.characters.count if len < 8 { var addzeroes = 8 - len while addzeroes > 0 { str = "0" + str addzeroes -= 1 } } return str } extension UIImage { func tintWithColor(color:UIColor)->UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0) let context = UIGraphicsGetCurrentContext() // flip the image CGContextScaleCTM(context, 1.0, -1.0) CGContextTranslateCTM(context, 0.0, -self.size.height) // multiply blend mode CGContextSetBlendMode(context, CGBlendMode.Multiply) let rect = CGRectMake(0, 0, self.size.width, self.size.height) CGContextClipToMask(context, rect, self.CGImage) color.setFill() CGContextFillRect(context, rect) // create uiimage let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
bsd-3-clause
0673143fad3fb815f6ff381bf06ea24d
26.619718
170
0.557879
5.067183
false
false
false
false
hilen/TSWeChat
TSWeChat/Classes/Chat/TSChatViewController+Subviews.swift
1
4569
// // TSChatViewController Subviews.swift // TSWeChat // // Created by Hilen on 1/7/16. // Copyright © 2016 Hilen. All rights reserved. // import Foundation private let kCustomKeyboardHeight: CGFloat = 216 // MARK: - @extension TSChatViewController extension TSChatViewController { /** 创建聊天的各种子 view */ func setupSubviews(_ delegate: UITextViewDelegate) { self.setupActionBar(delegate) self.initListTableView() self.setupKeyboardInputView() self.setupVoiceIndicatorView() } fileprivate func initListTableView() { //点击 UITableView 隐藏键盘 let tap = UITapGestureRecognizer() tap.cancelsTouchesInView = false tap.delegate = self self.listTableView.addGestureRecognizer(tap) tap.rx.event.subscribe {[weak self] _ in guard let strongSelf = self else { return } strongSelf.hideAllKeyboard() }.disposed(by: self.disposeBag) self.view.addSubview(self.listTableView) self.listTableView.snp.makeConstraints { (make) -> Void in make.top.left.right.equalTo(self.view) make.bottom.equalTo(self.chatActionBarView.snp.top) } } /** 初始化操作栏 */ fileprivate func setupActionBar(_ delegate: UITextViewDelegate) { self.chatActionBarView = UIView.ts_viewFromNib(TSChatActionBarView.self) self.chatActionBarView.delegate = self self.chatActionBarView.inputTextView.delegate = delegate self.view.addSubview(self.chatActionBarView) self.chatActionBarView.snp.makeConstraints { [weak self] (make) -> Void in guard let strongSelf = self else { return } make.left.equalTo(strongSelf.view.snp.left) make.right.equalTo(strongSelf.view.snp.right) strongSelf.actionBarPaddingBottomConstranit = make.bottom.equalTo(strongSelf.view.snp.bottom).constraint make.height.equalTo(kChatActionBarOriginalHeight) } } /** 初始化表情键盘,分享更多键盘 */ fileprivate func setupKeyboardInputView() { //emotionInputView init self.emotionInputView = UIView.ts_viewFromNib(TSChatEmotionInputView.self) self.emotionInputView.delegate = self self.view.addSubview(self.emotionInputView) self.emotionInputView.snp.makeConstraints {[weak self] (make) -> Void in guard let strongSelf = self else { return } make.left.equalTo(strongSelf.view.snp.left) make.right.equalTo(strongSelf.view.snp.right) make.top.equalTo(strongSelf.chatActionBarView.snp.bottom).offset(0) make.height.equalTo(kCustomKeyboardHeight) } //shareMoreView init self.shareMoreView = UIView.ts_viewFromNib(TSChatShareMoreView.self) self.shareMoreView!.delegate = self self.view.addSubview(self.shareMoreView) self.shareMoreView.snp.makeConstraints {[weak self] (make) -> Void in guard let strongSelf = self else { return } make.left.equalTo(strongSelf.view.snp.left) make.right.equalTo(strongSelf.view.snp.right) make.top.equalTo(strongSelf.chatActionBarView.snp.bottom).offset(0) make.height.equalTo(kCustomKeyboardHeight) } } /** 初始化 VoiceIndicator */ fileprivate func setupVoiceIndicatorView() { //voiceIndicatorView init self.voiceIndicatorView = UIView.ts_viewFromNib(TSChatVoiceIndicatorView.self) self.view.addSubview(self.voiceIndicatorView) self.voiceIndicatorView.snp.makeConstraints {[weak self] (make) -> Void in guard let strongSelf = self else { return } make.top.equalTo(strongSelf.view.snp.top).offset(100) make.left.equalTo(strongSelf.view.snp.left) make.bottom.equalTo(strongSelf.view.snp.bottom).offset(-100) make.right.equalTo(strongSelf.view.snp.right) } self.voiceIndicatorView.isHidden = true } } // MARK: - UIGestureRecognizerDelegate extension TSChatViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { //弹出键盘后,避免按钮的点击事件被listTableView的手势拦截而不执行,例如播放语音 if touch.view is UIButton { return false } return true } }
mit
7712642702c92a2eacad33e29c0d4728
36.226891
116
0.661625
4.54359
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV1/Models/SourceOptionsObject.swift
1
1810
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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 /** Object that defines a Salesforce document object type crawl with this configuration. */ public struct SourceOptionsObject: Codable, Equatable { /** The name of the Salesforce document object to crawl. For example, `case`. */ public var name: String /** The maximum number of documents to crawl for this document object. By default, all documents in the document object are crawled. */ public var limit: Int? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case name = "name" case limit = "limit" } /** Initialize a `SourceOptionsObject` with member variables. - parameter name: The name of the Salesforce document object to crawl. For example, `case`. - parameter limit: The maximum number of documents to crawl for this document object. By default, all documents in the document object are crawled. - returns: An initialized `SourceOptionsObject`. */ public init( name: String, limit: Int? = nil ) { self.name = name self.limit = limit } }
apache-2.0
ca02fdca06d20538b19291099353df57
29.677966
120
0.68011
4.447174
false
false
false
false
ThryvInc/subway-ios
SubwayMap/LineViewModel.swift
2
1600
// // LineViewModel.swift // SubwayMap // // Created by Elliot Schrock on 11/4/15. // Copyright © 2015 Thryv. All rights reserved. // import UIKit import SubwayStations class LineViewModel: NSObject { var routeIds: [String] = [String]() var color: UIColor! func routesString() -> String { var routesString = "" if routeIds.count > 0 { routeIds.sort(by: {$0 < $1}) routesString = routeIds.joined(separator: ", ") } return routesString } override func isEqual(_ object: Any?) -> Bool { if let obj = object { if (obj as AnyObject).isKind(of: LineViewModel.self) { let line = obj as! LineViewModel return line.color.isEqual(self.color) } } return false } } extension StationManager { func linesForStation(_ station: Station) -> [LineViewModel]? { var lineModels = [LineViewModel]() let routeIds = routeIdsForStation(station) for routeId in routeIds { let lineModel = LineViewModel() lineModel.routeIds = [routeId] lineModel.color = AppDelegate.colorManager().colorForRouteId(routeId) let lineIndex = lineModels.index(of: lineModel) if let index = lineIndex { if !lineModels[index].routeIds.contains(routeId) { lineModels[index].routeIds.append(routeId) } }else{ lineModels.append(lineModel) } } return lineModels } }
mit
510d11ec0b81fe9d01eda94c4f14f00d
27.553571
81
0.562226
4.46648
false
false
false
false
blokadaorg/blokada
ios/App/Debug/LogViewModel.swift
1
1821
// // This file is part of Blokada. // // 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 https://mozilla.org/MPL/2.0/. // // Copyright © 2020 Blocka AB. All rights reserved. // // @author Karol Gusak // import Foundation import UIKit import SwiftUI class LogViewModel: ObservableObject { @Published var logs = [String]() @Published var monitoring = false private var timer: Timer? func loadLog() { self.logs = LoggerSaver.loadLog(limit: 500) } func toggleMonitorLog() { Logger.v("Debug", "Toggle log monitoring") onMain { self.loadLog() if self.timer == nil { self.startMonitoringLog() } else { self.stopMonitoringLog() } } } func startMonitoringLog() { self.monitoring = true self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in self.loadLog() } } func stopMonitoringLog() { self.monitoring = false self.timer?.invalidate() self.timer = nil } func colorForLine(_ line: String) -> Color { if line.contains(" E ") { return Color.cError } else if line.contains(" W ") { return Color.cActivePlus } else { return Color.primary } } func share() { onBackground { sleep(1) onMain { guard let file = LoggerSaver.logFile else { return Logger.e("Logger", "Could not share log file: no log file") } Services.dialog.shareFile(file) } } } }
mpl-2.0
c854f4a4b4107120a8baf1bbbe361f3b
23.266667
92
0.545604
4.292453
false
false
false
false
brentvatne/react-native-video
ios/Video/Features/RCTVideoUtils.swift
1
10389
import AVFoundation import Promises /*! * Collection of pure functions */ enum RCTVideoUtils { /*! * Calculates and returns the playable duration of the current player item using its loaded time ranges. * * \returns The playable duration of the current player item in seconds. */ static func calculatePlayableDuration(_ player:AVPlayer?) -> NSNumber { guard let player = player, let video:AVPlayerItem = player.currentItem, video.status == AVPlayerItem.Status.readyToPlay else { return 0 } var effectiveTimeRange:CMTimeRange? for (_, value) in video.loadedTimeRanges.enumerated() { let timeRange:CMTimeRange = value.timeRangeValue if CMTimeRangeContainsTime(timeRange, time: video.currentTime()) { effectiveTimeRange = timeRange break } } if let effectiveTimeRange = effectiveTimeRange { let playableDuration:Float64 = CMTimeGetSeconds(CMTimeRangeGetEnd(effectiveTimeRange)) if playableDuration > 0 { return playableDuration as NSNumber } } return 0 } static func urlFilePath(filepath:NSString!) -> NSURL! { if filepath.contains("file://") { return NSURL(string: filepath as String) } // if no file found, check if the file exists in the Document directory let paths:[String]! = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) var relativeFilePath:String! = filepath.lastPathComponent // the file may be multiple levels below the documents directory let fileComponents:[String]! = filepath.components(separatedBy: "Documents/") if fileComponents.count > 1 { relativeFilePath = fileComponents[1] } let path:String! = (paths.first! as NSString).appendingPathComponent(relativeFilePath) if FileManager.default.fileExists(atPath: path) { return NSURL.fileURL(withPath: path) as NSURL } return nil } static func playerItemSeekableTimeRange(_ player:AVPlayer?) -> CMTimeRange { if let playerItem = player?.currentItem, playerItem.status == .readyToPlay, let firstItem = playerItem.seekableTimeRanges.first { return firstItem.timeRangeValue } return (CMTimeRange.zero) } static func playerItemDuration(_ player:AVPlayer?) -> CMTime { if let playerItem = player?.currentItem, playerItem.status == .readyToPlay { return(playerItem.duration) } return(CMTime.invalid) } static func calculateSeekableDuration(_ player:AVPlayer?) -> NSNumber { let timeRange:CMTimeRange = RCTVideoUtils.playerItemSeekableTimeRange(player) if CMTIME_IS_NUMERIC(timeRange.duration) { return NSNumber(value: CMTimeGetSeconds(timeRange.duration)) } return 0 } static func getAudioTrackInfo(_ player:AVPlayer?) -> [AnyObject]! { guard let player = player else { return [] } let audioTracks:NSMutableArray! = NSMutableArray() let group = player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .audible) for i in 0..<(group?.options.count ?? 0) { let currentOption = group?.options[i] var title = "" let values = currentOption?.commonMetadata.map(\.value) if (values?.count ?? 0) > 0, let value = values?[0] { title = value as! String } let language:String! = currentOption?.extendedLanguageTag ?? "" let audioTrack = [ "index": NSNumber(value: i), "title": title, "language": language ] as [String : Any] audioTracks.add(audioTrack) } return audioTracks as [AnyObject]? } static func getTextTrackInfo(_ player:AVPlayer?) -> [TextTrack]! { guard let player = player else { return [] } // if streaming video, we extract the text tracks var textTracks:[TextTrack] = [] let group = player.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) for i in 0..<(group?.options.count ?? 0) { let currentOption = group?.options[i] var title = "" let values = currentOption?.commonMetadata.map(\.value) if (values?.count ?? 0) > 0, let value = values?[0] { title = value as! String } let language:String! = currentOption?.extendedLanguageTag ?? "" let textTrack = TextTrack([ "index": NSNumber(value: i), "title": title, "language": language ]) textTracks.append(textTrack) } return textTracks } // UNUSED static func getCurrentTime(playerItem:AVPlayerItem?) -> Float { return Float(CMTimeGetSeconds(playerItem?.currentTime() ?? .zero)) } static func base64DataFromBase64String(base64String:String?) -> Data? { if let base64String = base64String { return Data(base64Encoded:base64String) } return nil } static func replaceURLScheme(url: URL, scheme: String?) -> URL? { var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) urlComponents?.scheme = scheme return urlComponents?.url } static func extractDataFromCustomSchemeUrl(from url: URL, scheme: String) -> Data? { guard url.scheme == scheme, let adoptURL = RCTVideoUtils.replaceURLScheme(url:url, scheme: nil) else { return nil } return Data(base64Encoded: adoptURL.absoluteString) } static func generateMixComposition(_ asset:AVAsset) -> AVMutableComposition { let mixComposition:AVMutableComposition = AVMutableComposition() let videoAsset:AVAssetTrack! = asset.tracks(withMediaType: AVMediaType.video).first let videoCompTrack:AVMutableCompositionTrack! = mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID:kCMPersistentTrackID_Invalid) do { try videoCompTrack.insertTimeRange( CMTimeRangeMake(start: .zero, duration: videoAsset.timeRange.duration), of: videoAsset, at: .zero) } catch { } let audioAsset:AVAssetTrack! = asset.tracks(withMediaType: AVMediaType.audio).first let audioCompTrack:AVMutableCompositionTrack! = mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID:kCMPersistentTrackID_Invalid) do { try audioCompTrack.insertTimeRange( CMTimeRangeMake(start: .zero, duration: videoAsset.timeRange.duration), of: audioAsset, at: .zero) } catch { } return mixComposition } static func getValidTextTracks(asset:AVAsset, assetOptions:NSDictionary?, mixComposition:AVMutableComposition, textTracks:[TextTrack]?) -> [TextTrack] { let videoAsset:AVAssetTrack! = asset.tracks(withMediaType: AVMediaType.video).first var validTextTracks:[TextTrack] = [] if let textTracks = textTracks, textTracks.count > 0 { for i in 0..<textTracks.count { var textURLAsset:AVURLAsset! let textUri:String = textTracks[i].uri if textUri.lowercased().hasPrefix("http") { textURLAsset = AVURLAsset(url: NSURL(string: textUri)! as URL, options:(assetOptions as! [String : Any])) } else { textURLAsset = AVURLAsset(url: RCTVideoUtils.urlFilePath(filepath: textUri as NSString?) as URL, options:nil) } let textTrackAsset:AVAssetTrack! = textURLAsset.tracks(withMediaType: AVMediaType.text).first if (textTrackAsset == nil) {continue} // fix when there's no textTrackAsset validTextTracks.append(textTracks[i]) let textCompTrack:AVMutableCompositionTrack! = mixComposition.addMutableTrack(withMediaType: AVMediaType.text, preferredTrackID:kCMPersistentTrackID_Invalid) do { try textCompTrack.insertTimeRange( CMTimeRangeMake(start: .zero, duration: videoAsset.timeRange.duration), of: textTrackAsset, at: .zero) } catch { } } } return validTextTracks } static func delay(seconds: Int = 0) -> Promise<Void> { return Promise<Void>(on: .global()) { fulfill, reject in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(seconds)) / Double(NSEC_PER_SEC), execute: { fulfill(()) }) } } static func prepareAsset(source:VideoSource) -> (asset:AVURLAsset?, assetOptions:NSMutableDictionary?)? { guard source.uri != nil && source.uri != "" else { return nil } var asset:AVURLAsset! let bundlePath = Bundle.main.path(forResource: source.uri, ofType: source.type) ?? "" let url = source.isNetwork || source.isAsset ? URL(string: source.uri ?? "") : URL(fileURLWithPath: bundlePath) let assetOptions:NSMutableDictionary! = NSMutableDictionary() if source.isNetwork { if let headers = source.requestHeaders, headers.count > 0 { assetOptions.setObject(headers, forKey:"AVURLAssetHTTPHeaderFieldsKey" as NSCopying) } let cookies:[AnyObject]! = HTTPCookieStorage.shared.cookies assetOptions.setObject(cookies, forKey:AVURLAssetHTTPCookiesKey as NSCopying) asset = AVURLAsset(url: url!, options:assetOptions as! [String : Any]) } else { asset = AVURLAsset(url: url!) } return (asset, assetOptions) } }
mit
ace794c422086c7edabe6444a809151b
40.556
167
0.602272
5.122781
false
false
false
false
invoy/CoreDataQueryInterface
CoreDataQueryInterface/Comparisons.swift
1
4541
// // Comparisons.swift // CoreDataQueryInterface // // Created by Gregory Higley on 9/25/16. // Copyright © 2016 Prosumma LLC. All rights reserved. // import Foundation public struct Null: ExpressibleByNilLiteral, ExpressionConvertible { public init(nilLiteral: ()) { } public var cdqiExpression: NSExpression { return NSExpression(forConstantValue: nil) } } public func compare(_ lhs: ExpressionConvertible, _ op: NSComparisonPredicate.Operator, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { let (le, re) = (lhs.cdqiExpression, rhs.cdqiExpression) return NSComparisonPredicate(leftExpression: le, rightExpression: re, modifier: .direct, type: op, options: options) } public func compare(_ lhs: ExpressionConvertible, _ op: NSComparisonPredicate.Operator, _ rhs: Null, options: NSComparisonPredicate.Options = []) -> NSPredicate { let (le, re) = (lhs.cdqiExpression, rhs.cdqiExpression) return NSComparisonPredicate(leftExpression: le, rightExpression: re, modifier: .direct, type: op, options: options) } public func equalTo(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .equalTo, rhs, options: options) } public func equalTo(_ lhs: ExpressionConvertible, _ rhs: Null, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .equalTo, rhs, options: options) } public func notEqualTo(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .notEqualTo, rhs, options: options) } public func notEqualTo(_ lhs: ExpressionConvertible, _ rhs: Null, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .notEqualTo, rhs, options: options) } public func lessThan(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .lessThan, rhs, options: options) } public func lessThanOrEqualTo(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .lessThanOrEqualTo, rhs, options: options) } public func greaterThan(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .greaterThan, rhs, options: options) } public func greaterThanOrEqualTo(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .greaterThanOrEqualTo, rhs, options: options) } public func between(_ value: ExpressionConvertible, _ lhs: ExpressionConvertible, and rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { let re = NSExpression(forAggregate: [lhs.cdqiExpression, rhs.cdqiExpression]) return compare(value, .between, re, options: options) } public func among<R: Sequence>(_ lhs: ExpressionConvertible, _ rhs: R, options: NSComparisonPredicate.Options = []) -> NSPredicate where R.Iterator.Element: ExpressionConvertible { let re = NSExpression(forAggregate: rhs.map{ $0.cdqiExpression }) return compare(lhs, .in, re, options: options) } public func contains(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .contains, rhs, options: options) } public func like(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .like, rhs, options: options) } public func beginsWith(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .beginsWith, rhs, options: options) } public func endsWith(_ lhs: ExpressionConvertible, _ rhs: ExpressionConvertible, options: NSComparisonPredicate.Options = []) -> NSPredicate { return compare(lhs, .endsWith, rhs, options: options) } public func matches(_ lhs: ExpressionConvertible, _ rhs: String, options: NSComparisonPredicate.Options = []) -> NSPredicate { let le = lhs.cdqiExpression let re = NSExpression(forConstantValue: rhs) return NSComparisonPredicate(leftExpression: le, rightExpression: re, modifier: .direct, type: .matches, options: options) }
mit
d098edee73b5cc31312dc19a2461cf21
47.297872
180
0.745374
4.680412
false
false
false
false
gssdromen/CedFilterView
FilterTest/ESFFilterItemModel.swift
1
1701
// // ESFFilterModel.swift // JingJiRen_ESF_iOS // // Created by cedricwu on 12/29/16. // Copyright © 2016 Cedric Wu. All rights reserved. // import ObjectMapper extension ESFFilterItemModel { class func getDepth(model: ESFFilterItemModel) -> Int { var max = 0 guard model.subItems != nil else { return max + 1 } for item in model.subItems! { let height = ESFFilterItemModel.getDepth(model: item) if height > max { max = height } } return max + 1 } } extension ESFFilterItemModel { func getDepth() -> Int { var depth = 0 if subItems == nil { return depth } for item in subItems! { let height = item.getDepth() depth = max(height, depth) } return depth + 1 } } class ESFFilterItemModel: NSObject, Mappable { // var maxDepth = -1 var depth: Int? var maxDepth: Int? var displayText: String? var filterKey: String? var fullFilterKey: String? var id: Int? var multiple: Bool? var selected: Bool? var style: Int? var extInfo: String? var subItems: [ESFFilterItemModel]? required init?(map: Map) { } func mapping(map: Map) { depth <- map["depth"] maxDepth <- map["maxDepth"] displayText <- map["displayText"] filterKey <- map["filterKey"] fullFilterKey <- map["fullFilterKey"] id <- map["id"] multiple <- map["multiple"] selected <- map["selected"] style <- map["style"] extInfo <- map["extInfo"] subItems <- map["subItems"] } }
gpl-3.0
9ec4cc334dbae6a96d2ee9bc21543cf4
21.368421
65
0.548824
4.047619
false
false
false
false
nathantannar4/NTComponents
NTComponents/UI Kit/Form/Cells/NTFormAnimatedInputCell.swift
1
3225
// // NTFormAnimatedInputCell.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 6/8/17. // open class NTFormAnimatedInputCell: NTFormCell { open override var datasourceItem: Any? { get { return self } set { guard let cell = newValue as? NTFormAnimatedInputCell else { return } self.textField.removeFromSuperview() self.textField = cell.textField self.setupViews() } } open var text: String? { get { return textField.text } set { textField.text = newValue } } open var placeholder: String? { get { return textField.placeholder } set { textField.placeholder = newValue } } open var textField: NTAnimatedTextField = { let textField = NTAnimatedTextField(style: .body) textField.clearButtonMode = .whileEditing return textField }() // MARK: - Handlers @discardableResult open func onTextFieldUpdate(_ handler: @escaping ((NTTextField) -> Void)) -> Self { textField.onTextFieldUpdate = handler return self } // MARK: - Setup open override func setupViews() { super.setupViews() addSubview(textField) textField.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 12, leftConstant: 16, bottomConstant: 12, rightConstant: 16, widthConstant: 0, heightConstant: 0) let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(dismissKeyboard)) textField.addToolBar(withItems: [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), doneButton]) } @objc open func dismissKeyboard() { textField.resignFirstResponder() } open override class var cellSize: CGSize { get { return CGSize(width: UIScreen.main.bounds.width, height: 60) } } }
mit
1608ad7490bfe7bfd49ed1b7339dae11
32.936842
206
0.650124
4.783383
false
false
false
false
KrishMunot/swift
test/DebugInfo/generic_args.swift
3
2104
// RUN: %target-swift-frontend -primary-file %s -emit-ir -verify -g -o - | FileCheck %s func markUsed<T>(_ t: T) {} protocol AProtocol { func f() -> String } class AClass : AProtocol { func f() -> String { return "A" } } class AnotherClass : AProtocol { func f() -> String { return "B" } } // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq_F12generic_args9aFunction{{.*}}",{{.*}} elements: ![[PROTOS:[0-9]+]] // CHECK-DAG: ![[PROTOS]] = !{![[INHERIT:.*]]} // CHECK-DAG: ![[INHERIT]] = !DIDerivedType(tag: DW_TAG_inheritance,{{.*}} baseType: ![[PROTOCOL:"[^"]+"]] // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtMP12generic_args9AProtocol_",{{.*}} identifier: [[PROTOCOL]] // CHECK-DAG: !DILocalVariable(name: "x", arg: 1,{{.*}} type: ![[T:.*]]) // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq_F12generic_args9aFunction{{.*}}, identifier: [[T]]) // CHECK-DAG: !DILocalVariable(name: "y", arg: 2,{{.*}} type: ![[Q:.*]]) // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq0_F12generic_args9aFunction{{.*}}, identifier: [[Q]]) func aFunction<T : AProtocol, Q : AProtocol>(_ x: T, _ y: Q, _ z: String) { markUsed("I am in \(z): \(x.f()) \(y.f())") } aFunction(AClass(),AnotherClass(),"aFunction") struct Wrapper<T: AProtocol> { init<U: AProtocol>(from : Wrapper<U>) { // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_TtGV12generic_args7WrapperQq_FS0_cuRd__S_9AProtocolrFT4fromGS0_qd____GS0_x__") var wrapped = from wrapped = from _ = wrapped } func passthrough(_ t: T) -> T { // The type of local should have the context Wrapper<T>. // CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]],{{.*}} type: !"_TtQq_V12generic_args7Wrapper" var local = t local = t return local } } // CHECK: !DILocalVariable(name: "f", {{.*}}, line: [[@LINE+1]], type: !"_TtFQq_F12generic_args5applyu0_rFTx1fFxq__q_Qq0_F12generic_args5applyu0_rFTx1fFxq__q_") func apply<T, U> (_ x: T, f: (T) -> (U)) -> U { return f(x) }
apache-2.0
62007b641a40a112e794e77f0124fea1
40.254902
176
0.617395
2.988636
false
false
false
false
phatblat/Nimble
Sources/Nimble/Adapters/NMBExpectation.swift
1
6660
import Foundation import Dispatch #if canImport(Darwin) && !SWIFT_PACKAGE private func from(objcPredicate: NMBPredicate) -> Predicate<NSObject> { return Predicate { actualExpression in let result = objcPredicate.satisfies(({ try actualExpression.evaluate() }), location: actualExpression.location) return result.toSwift() } } internal struct ObjCMatcherWrapper: Matcher { let matcher: NMBMatcher func matches(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { return matcher.matches( // swiftlint:disable:next force_try ({ try! actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) } func doesNotMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { return matcher.doesNotMatch( // swiftlint:disable:next force_try ({ try! actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) } } // Equivalent to Expectation, but for Nimble's Objective-C interface public class NMBExpectation: NSObject { // swiftlint:disable identifier_name internal let _actualBlock: () -> NSObject? internal var _negative: Bool internal let _file: FileString internal let _line: UInt internal var _timeout: DispatchTimeInterval = .seconds(1) // swiftlint:enable identifier_name @objc public init(actualBlock: @escaping () -> NSObject?, negative: Bool, file: FileString, line: UInt) { self._actualBlock = actualBlock self._negative = negative self._file = file self._line = line } private var expectValue: Expectation<NSObject> { return expect(_file, line: _line) { self._actualBlock() as NSObject? } } @objc public var withTimeout: (TimeInterval) -> NMBExpectation { return { timeout in self._timeout = timeout.dispatchInterval return self } } @objc public var to: (NMBMatcher) -> Void { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.to(from(objcPredicate: pred)) } else { self.expectValue.to(ObjCMatcherWrapper(matcher: matcher)) } } } @objc public var toWithDescription: (NMBMatcher, String) -> Void { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.to(from(objcPredicate: pred), description: description) } else { self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description) } } } @objc public var toNot: (NMBMatcher) -> Void { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toNot(from(objcPredicate: pred)) } else { self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher)) } } } @objc public var toNotWithDescription: (NMBMatcher, String) -> Void { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toNot(from(objcPredicate: pred), description: description) } else { self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher), description: description) } } } @objc public var notTo: (NMBMatcher) -> Void { return toNot } @objc public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription } @objc public var toEventually: (NMBMatcher) -> Void { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toEventually( from(objcPredicate: pred), timeout: self._timeout, description: nil ) } else { self.expectValue.toEventually( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: nil ) } } } @objc public var toEventuallyWithDescription: (NMBMatcher, String) -> Void { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toEventually( from(objcPredicate: pred), timeout: self._timeout, description: description ) } else { self.expectValue.toEventually( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: description ) } } } @objc public var toEventuallyNot: (NMBMatcher) -> Void { return { matcher in if let pred = matcher as? NMBPredicate { self.expectValue.toEventuallyNot( from(objcPredicate: pred), timeout: self._timeout, description: nil ) } else { self.expectValue.toEventuallyNot( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: nil ) } } } @objc public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void { return { matcher, description in if let pred = matcher as? NMBPredicate { self.expectValue.toEventuallyNot( from(objcPredicate: pred), timeout: self._timeout, description: description ) } else { self.expectValue.toEventuallyNot( ObjCMatcherWrapper(matcher: matcher), timeout: self._timeout, description: description ) } } } @objc public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot } @objc public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription } @objc public class func failWithMessage(_ message: String, file: FileString, line: UInt) { fail(message, location: SourceLocation(file: file, line: line)) } } #endif
apache-2.0
80c33e055b1a48aaea6f6bf219641ce8
33.6875
109
0.566216
5.531561
false
false
false
false
tkremenek/swift
test/Generics/unify_nested_types_4.swift
1
1452
// RUN: %target-typecheck-verify-swift -requirement-machine=verify -debug-requirement-machine 2>&1 | %FileCheck %s protocol P1 { associatedtype A : P1 associatedtype B : P1 } struct S1 : P1 { typealias A = S1 typealias B = S2 } struct S2 : P1 { typealias A = S2 typealias B = S1 } protocol P2 { associatedtype A where A == S1 associatedtype B where B == S2 } struct G<T : P1 & P2> {} // T.A and T.B become concrete, which produces the following series of // concretized nested types: // // T.A.[concrete: S1] // T.B.[concrete: S2] // T.A.A.[concrete: S1] // T.A.B.[concrete: S2] // T.B.A.[concrete: S2] // T.B.B.[concrete: S1] // ... // // This would normally go on forever, but since S1 and S2 are not generic, // we solve this by merging the repeated types with T.A or T.B: // // T.A.A => T.A // T.A.B => T.B // T.B.A => T.B // T.B.B => T.A // ... // CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> // CHECK-LABEL: Rewrite system: { // CHECK: - τ_0_0.[P1&P2:A].[P1:A] => τ_0_0.[P1&P2:A] // CHECK: - τ_0_0.[P1&P2:A].[P1:B] => τ_0_0.[P1&P2:B] // CHECK: - τ_0_0.[P1&P2:B].[P1:A] => τ_0_0.[P1&P2:B] // CHECK: - τ_0_0.[P1&P2:B].[P1:B] => τ_0_0.[P1&P2:A] // CHECK: } // CHECK-LABEL: Equivalence class map: { // CHECK: τ_0_0.[P1&P2:A] => { conforms_to: [P1] concrete_type: [concrete: S1] } // CHECK: τ_0_0.[P1&P2:B] => { conforms_to: [P1] concrete_type: [concrete: S2] } // CHECK: } // CHECK: }
apache-2.0
5e486b642eef07843568033d6dd64ec1
24.696429
114
0.589298
2.255486
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Components/MarkerImage.swift
4
2628
// // ChartMarkerImage.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif @objc(ChartMarkerImage) open class MarkerImage: NSObject, IMarker { /// The marker image to render @objc open var image: NSUIImage? open var offset: CGPoint = CGPoint() @objc open weak var chartView: ChartViewBase? /// As long as size is 0.0/0.0 - it will default to the image's size @objc open var size: CGSize = CGSize() public override init() { super.init() } open func offsetForDrawing(atPoint point: CGPoint) -> CGPoint { var offset = self.offset let chart = self.chartView var size = self.size if size.width == 0.0 && image != nil { size.width = image?.size.width ?? 0.0 } if size.height == 0.0 && image != nil { size.height = image?.size.height ?? 0.0 } let width = size.width let height = size.height if point.x + offset.x < 0.0 { offset.x = -point.x } else if chart != nil && point.x + width + offset.x > chart!.bounds.size.width { offset.x = chart!.bounds.size.width - point.x - width } if point.y + offset.y < 0 { offset.y = -point.y } else if chart != nil && point.y + height + offset.y > chart!.bounds.size.height { offset.y = chart!.bounds.size.height - point.y - height } return offset } open func refreshContent(entry: ChartDataEntry, highlight: Highlight) { // Do nothing here... } open func draw(context: CGContext, point: CGPoint) { let offset = self.offsetForDrawing(atPoint: point) var size = self.size if size.width == 0.0 && image != nil { size.width = image?.size.width ?? 0.0 } if size.height == 0.0 && image != nil { size.height = image?.size.height ?? 0.0 } let rect = CGRect( x: point.x + offset.x, y: point.y + offset.y, width: size.width, height: size.height) NSUIGraphicsPushContext(context) image!.draw(in: rect) NSUIGraphicsPopContext() } }
apache-2.0
d851a2f74d69c9e16c249412f1c25181
23.333333
87
0.521309
4.158228
false
false
false
false
FirebaseExtended/firestore-codelab-extended-swift
FriendlyEats/Profile/ProfileViewController.swift
1
4911
// // Copyright (c) 2018 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 UIKit import FirebaseAuth import FirebaseUI import FirebaseFirestore import SDWebImage class ProfileViewController: UIViewController { static func fromStoryboard(_ storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)) -> ProfileViewController { return storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController } /// The current user displayed by the controller. Setting this property has side effects. fileprivate var user: User? = nil { didSet { populate(user: user) if let user = user { populateReviews(forUser: user) } else { dataSource?.stopUpdates() dataSource = nil tableView.backgroundView = tableBackgroundLabel tableView.reloadData() } } } lazy private var tableBackgroundLabel: UILabel = { let label = UILabel(frame: tableView.frame) label.textAlignment = .center return label }() private var dataSource: ReviewTableViewDataSource? = nil private var authListener: AuthStateDidChangeListenerHandle? = nil @IBOutlet private var tableView: UITableView! @IBOutlet private var profileImageView: UIImageView! @IBOutlet private var usernameLabel: UILabel! @IBOutlet private var viewRestaurantsButton: UIButton! @IBOutlet private var signInButton: UIButton! // Not weak because we might remove it @IBOutlet private var signOutButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() tableBackgroundLabel.text = "There aren't any reviews here." tableView.backgroundView = tableBackgroundLabel } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setUser(firebaseUser: Auth.auth().currentUser) Auth.auth().addStateDidChangeListener { (auth, newUser) in self.setUser(firebaseUser: newUser) } } @IBAction func signInButtonWasTapped(_ sender: Any) { presentLoginController() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let listener = authListener { Auth.auth().removeStateDidChangeListener(listener) } } fileprivate func setUser(firebaseUser: FirebaseAuth.UserInfo?) { if let firebaseUser = firebaseUser { let user = User(user: firebaseUser) self.user = user } else { user = nil } } fileprivate func populate(user: User?) { if let user = user { profileImageView.sd_setImage(with: user.photoURL) usernameLabel.text = user.name viewRestaurantsButton.isHidden = false signInButton.isHidden = true self.navigationItem.leftBarButtonItem = signOutButton } else { profileImageView.image = nil usernameLabel.text = "Sign in, why don'cha?" viewRestaurantsButton.isHidden = true signInButton.isHidden = false self.navigationItem.leftBarButtonItem = nil } } fileprivate func populateReviews(forUser user: User) { dataSource?.sectionTitle = "My reviews" dataSource?.startUpdates() tableView.dataSource = dataSource } fileprivate func presentLoginController() { guard let authUI = FUIAuth.defaultAuthUI() else { return } guard authUI.auth?.currentUser == nil else { print("Attempted to present auth flow while already logged in") return } let emailAuth = FUIEmailAuth(authAuthUI: authUI, signInMethod: "password", forceSameDevice: false, allowNewEmailAccounts: true, actionCodeSetting: ActionCodeSettings()) authUI.providers = [emailAuth] let controller = authUI.authViewController() self.present(controller, animated: true, completion: nil) } @IBAction private func didTapViewRestaurantsButton(_ sender: Any) { let controller = MyRestaurantsViewController.fromStoryboard() self.navigationController?.pushViewController(controller, animated: true) } @IBAction private func didTapSignOutButton(_ sender: Any) { do { try Auth.auth().signOut() } catch let error { print("Error signing out: \(error)") } } }
apache-2.0
7abf74fe16e11c85aedcb610a118b321
31.098039
98
0.695989
4.862376
false
false
false
false
xwu/swift
test/Constraints/operator.swift
5
7051
// RUN: %target-typecheck-verify-swift // Test constraint simplification of chains of binary operators. // <https://bugs.swift.org/browse/SR-1122> do { let a: String? = "a" let b: String? = "b" let c: String? = "c" let _: String? = a! + b! + c! let x: Double = 1 _ = x + x + x let sr3483: Double? = 1 _ = sr3483! + sr3483! + sr3483! let sr2636: [String: Double] = ["pizza": 10.99, "ice cream": 4.99, "salad": 7.99] _ = sr2636["pizza"]! _ = sr2636["pizza"]! + sr2636["salad"]! _ = sr2636["pizza"]! + sr2636["salad"]! + sr2636["ice cream"]! } // Use operators defined within a type. struct S0 { static func +(lhs: S0, rhs: S0) -> S0 { return lhs } } func useS0(lhs: S0, rhs: S0) { _ = lhs + rhs } // Use operators defined within a generic type. struct S0b<T> { static func + <U>(lhs: S0b<T>, rhs: U) -> S0b<U> { return S0b<U>() } } func useS0b(s1i: S0b<Int>, s: String) { var s1s = s1i + s s1s = S0b<String>() _ = s1s } // Use operators defined within a protocol extension. infix operator %%% infix operator %%%% protocol P1 { static func %%%(lhs: Self, rhs: Self) -> Bool } extension P1 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP1Directly<T : P1>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1 : P1 { static func %%%(lhs: S1, rhs: S1) -> Bool { return false } } func useP1Model(lhs: S1, rhs: S1) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1b<T> : P1 { static func %%%(lhs: S1b<T>, rhs: S1b<T>) -> Bool { return false } } func useP1ModelB(lhs: S1b<Int>, rhs: S1b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP1ModelBGeneric<T>(lhs: S1b<T>, rhs: S1b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Use operators defined within a protocol extension to satisfy a requirement. protocol P2 { static func %%%(lhs: Self, rhs: Self) -> Bool static func %%%%(lhs: Self, rhs: Self) -> Bool } extension P2 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP2Directly<T : P2>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2 : P2 { static func %%%(lhs: S2, rhs: S2) -> Bool { return false } } func useP2Model(lhs: S2, rhs: S2) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2b<T> : P2 { static func %%%(lhs: S2b<T>, rhs: S2b<T>) -> Bool { return false } } func useP2Model2(lhs: S2b<Int>, rhs: S2b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP2Model2Generic<T>(lhs: S2b<T>, rhs: S2b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Using an extension of one protocol to satisfy another conformance. protocol P3 { } extension P3 { static func ==(lhs: Self, rhs: Self) -> Bool { return true } } struct S3 : P3, Equatable { } // rdar://problem/30220565 func shrinkTooFar(_ : Double, closure : ()->()) {} func testShrinkTooFar() { shrinkTooFar(0*0*0) {} } // rdar://problem/33759839 enum E_33759839 { case foo case bar(String) } let foo_33759839 = ["a", "b", "c"] let bar_33759839 = ["A", "B", "C"] let _: [E_33759839] = foo_33759839.map { .bar($0) } + bar_33759839.map { .bar($0) } + [E_33759839.foo] // Ok // rdar://problem/28688585 class B_28688585 { var value: Int init(value: Int) { self.value = value } func add(_ other: B_28688585) -> B_28688585 { return B_28688585(value: value + other.value) } } class D_28688585 : B_28688585 { } func + (lhs: B_28688585, rhs: B_28688585) -> B_28688585 { return lhs.add(rhs) } let var_28688585 = D_28688585(value: 1) _ = var_28688585 + var_28688585 + var_28688585 // Ok // rdar://problem/35740653 - Fix `LinkedExprAnalyzer` greedy operator linking struct S_35740653 { var v: Double = 42 static func value(_ value: Double) -> S_35740653 { return S_35740653(v: value) } static func / (lhs: S_35740653, rhs: S_35740653) -> Double { return lhs.v / rhs.v } } func rdar35740653(val: S_35740653) { let _ = 0...Int(val / .value(1.0 / 42.0)) // Ok } protocol P_37290898 {} struct S_37290898: P_37290898 {} func rdar37290898(_ arr: inout [P_37290898], _ element: S_37290898?) { arr += [element].compactMap { $0 } // Ok } // SR-8221 infix operator ??= func ??= <T>(lhs: inout T?, rhs: T?) {} var c: Int = 0 // expected-note {{change variable type to 'Int?' if it doesn't need to be declared as 'Int'}} c ??= 5 // expected-error{{inout argument could be set to a value with a type other than 'Int'; use a value declared as type 'Int?' instead}} func rdar46459603() { enum E { case foo(value: String) } let e = E.foo(value: "String") var arr = ["key": e] _ = arr.values == [e] // expected-error@-1 {{binary operator '==' cannot be applied to operands of type 'Dictionary<String, E>.Values' and '[E]'}} _ = [arr.values] == [[e]] // expected-error@-1 {{referencing operator function '==' on 'Array' requires that 'E' conform to 'Equatable'}} expected-note@-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // expected-error@-2 {{cannot convert value of type 'Dictionary<String, E>.Values' to expected element type '[E]'}} } // SR-10843 infix operator ^^^ func ^^^ (lhs: String, rhs: String) {} struct SR10843 { static func ^^^ (lhs: SR10843, rhs: SR10843) {} } func sr10843() { let s = SR10843() (^^^)(s, s) _ = (==)(0, 0) } // SR-10970 precedencegroup PowerPrecedence { lowerThan: BitwiseShiftPrecedence higherThan: AdditionPrecedence associativity: right } infix operator ^^ : PowerPrecedence extension Int { static func ^^ (lhs: Int, rhs: Int) -> Int { var result = 1 for _ in 1...rhs { result *= lhs } return result } } _ = 1 ^^ 2 ^^ 3 * 4 // expected-error {{adjacent operators are in unordered precedence groups 'PowerPrecedence' and 'MultiplicationPrecedence'}} // rdar://problem/60185506 - Ambiguity with Float comparison func rdar_60185506() { struct X { var foo: Float } func test(x: X?) { let _ = (x?.foo ?? 0) <= 0.5 // Ok } } // rdar://problem/60727310 func rdar60727310() { func myAssertion<T>(_ a: T, _ op: ((T,T)->Bool), _ b: T) {} var e: Error? = nil myAssertion(e, ==, nil) // expected-error {{binary operator '==' cannot be applied to two 'Error?' operands}} } // FIXME(SR-12438): Bad diagnostic. func sr12438(_ e: Error) { func foo<T>(_ a: T, _ op: ((T, T) -> Bool)) {} foo(e, ==) // expected-error {{type of expression is ambiguous without more context}} } // rdar://problem/62054241 - Swift compiler crashes when passing < as the sort function in sorted(by:) and the type of the array is not comparable func rdar_62054241() { struct Foo { let a: Int } func test(_ arr: [Foo]) -> [Foo] { return arr.sorted(by: <) // expected-error {{no exact matches in reference to operator function '<'}} // expected-note@-1 {{found candidate with type '(Foo, Foo) -> Bool'}} } } // SR-11399 - Operator returning IUO doesn't implicitly unwrap postfix operator ^^^ postfix func ^^^ (lhs: Int) -> Int! { 0 } let x: Int = 1^^^
apache-2.0
bf16a5c358add6212147ef8f271c0b47
22.661074
210
0.599489
3.022289
false
false
false
false
xGoPox/Twelve
Twelve/SpriteNode/ScoreNode.swift
1
637
// // ScoreNode.swift // Twelve // // Created by Clement Yerochewski on 1/31/17. // Copyright © 2017 Clement Yerochewski. All rights reserved. // import SpriteKit class ScoreNode : SKSpriteNode { var label: SKLabelNode? var score: Int = 0 { willSet(number) { if let lbl = label { lbl.text = String(number) } guard let node = childNode(withName: "scoreValue") as? SKLabelNode else { fatalError("scoreValue node not loaded") } label = node label?.text = String(number) } } }
mit
38da9fe5e9b17435a1c1fcafa9d8cfb2
22.555556
62
0.531447
4.184211
false
false
false
false
Allow2CEO/browser-ios
Client/Frontend/Browser/OpenPdfHelper.swift
1
5283
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import SnapKit import Shared import XCGLogger private let log = Logger.browserLogger struct OpenInViewUX { static let ViewHeight: CGFloat = 40.0 static let TextFont = UIFont.systemFont(ofSize: 16) static let TextColor = UIColor(red: 74.0/255.0, green: 144.0/255.0, blue: 226.0/255.0, alpha: 1.0) static let TextOffset = -15 static let OpenInString = Strings.Open_in } enum FileType : String { case PDF = "pdf" } protocol OpenInHelper { var openInView: OpenInView { get } static func canOpen(_ url: URL) -> Bool func open() } struct OpenInHelperFactory { static func helperForURL(_ url: URL) -> OpenInHelper? { if OpenPdfInHelper.canOpen(url) { return OpenPdfInHelper(url: url) } return nil } } class OpenPdfInHelper: NSObject, OpenInHelper, UIDocumentInteractionControllerDelegate { fileprivate var url: URL fileprivate var docController: UIDocumentInteractionController? = nil fileprivate var openInURL: URL? lazy var openInView: OpenInView = getOpenInView(self)() init(url: URL) { self.url = url super.init() } deinit { guard let url = openInURL else { return } let fileManager = FileManager.default do { try fileManager.removeItem(at: url) } catch { log.error("failed to delete file at \(url): \(error)") } } static func canOpen(_ url: URL) -> Bool { // May need to filter empty strings let pathExtension = url.pathExtension return pathExtension == FileType.PDF.rawValue && UIApplication.shared.canOpenURL(URL(string: "itms-books:")!) } func getOpenInView() -> OpenInView { let overlayView = OpenInView() overlayView.openInButton.addTarget(self, action: #selector(OpenPdfInHelper.open), for: .touchUpInside) return overlayView } func createDocumentControllerForURL(_ url: URL) { docController = UIDocumentInteractionController(url: url) docController?.delegate = self self.openInURL = url } func createLocalCopyOfPDF() { let lastPathComponent = url.lastPathComponent if docController == nil{ // if we already have a URL but no document controller, just create the document controller if let url = openInURL { createDocumentControllerForURL(url) return } let contentsOfFile = try? Data(contentsOf: url) let dirPath = URL(string: NSTemporaryDirectory())!.appendingPathComponent("pdfs") let filePath = dirPath.appendingPathComponent(lastPathComponent) let fileManager = FileManager.default do { try fileManager.createDirectory(atPath: dirPath.absoluteString, withIntermediateDirectories: true, attributes: nil) if fileManager.createFile(atPath: filePath.absoluteString, contents: contentsOfFile, attributes: nil) { let openInURL = URL(fileURLWithPath: filePath.absoluteString) createDocumentControllerForURL(openInURL) } else { log.error("Unable to create local version of PDF file at \(filePath)") } } catch { log.error("Error on creating directory at \(dirPath)") } } } func open() { createLocalCopyOfPDF() guard let _parentView = self.openInView.superview, let docController = self.docController else { log.error("view doesn't have a superview so can't open anything"); return } // iBooks should be installed by default on all devices we care about, so regardless of whether or not there are other pdf-capable // apps on this device, if we can open in iBooks we can open this PDF // simulators do not have iBooks so the open in view will not work on the simulator if UIApplication.shared.canOpenURL(URL(string: "itms-books:")!) { log.info("iBooks installed: attempting to open pdf") docController.presentOpenInMenu(from: CGRect.zero, in: _parentView, animated: true) } else { log.info("iBooks is not installed") } } } class OpenInView: UIView { let openInButton = UIButton() init() { super.init(frame: CGRect.zero) openInButton.setTitleColor(OpenInViewUX.TextColor, for: .normal) openInButton.setTitle(OpenInViewUX.OpenInString, for: UIControlState.normal) openInButton.titleLabel?.font = OpenInViewUX.TextFont openInButton.sizeToFit() self.addSubview(openInButton) openInButton.snp.makeConstraints { make in make.centerY.equalTo(self) make.height.equalTo(self) make.trailing.equalTo(self).offset(OpenInViewUX.TextOffset) } self.backgroundColor = UIColor.white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
3e7589329741ce280cedf98405a9c732
35.184932
180
0.647549
4.750899
false
false
false
false
suragch/Chimee-iOS
Chimee/UIMongolSingleLineLabel.swift
1
3516
import UIKit @IBDesignable class UIMongolSingleLineLabel: UIView { fileprivate let textLayer = LabelTextLayer() let mongolFontName = "ChimeeWhiteMirrored" var useMirroredFont = true // MARK: Primary input value @IBInspectable var text: String = "A" { didSet { textLayer.displayString = text updateTextLayerFrame() } } @IBInspectable var fontSize: CGFloat = 17 { didSet { updateTextLayerFrame() } } @IBInspectable var centerText: Bool = true { didSet { updateTextLayerFrame() } } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } func setup() { // Text layer textLayer.useMirroredFont = useMirroredFont //textLayer.backgroundColor = UIColor.clearColor().CGColor textLayer.contentsScale = UIScreen.main.scale //layer.actions = nil layer.addSublayer(textLayer) } override var intrinsicContentSize : CGSize { return textLayer.frame.size } func updateTextLayerFrame() { let myAttribute = [ NSFontAttributeName: UIFont(name: mongolFontName, size: fontSize )! ] let attrString = NSMutableAttributedString(string: textLayer.displayString, attributes: myAttribute ) let size = dimensionsForAttributedString(attrString) // This is the frame for the soon-to-be rotated layer var x: CGFloat = 0 var y: CGFloat = 0 if layer.bounds.width > size.height { x = (layer.bounds.width - size.height) / 2 } if centerText { y = (layer.bounds.height - size.width) / 2 } // FIXME: update layer frame and string without animation textLayer.frame = CGRect(x: x, y: y, width: size.height, height: size.width) textLayer.string = attrString invalidateIntrinsicContentSize() } func dimensionsForAttributedString(_ attrString: NSAttributedString) -> CGSize { var ascent: CGFloat = 0 var descent: CGFloat = 0 var width: CGFloat = 0 let line: CTLine = CTLineCreateWithAttributedString(attrString) width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, nil)) // make width an even integer for better graphics rendering width = ceil(width) if Int(width)%2 == 1 { width += 1.0 } return CGSize(width: width, height: ceil(ascent+descent)) } } // MARK: - Key Text Layer Class class LabelTextLayer: CATextLayer { // set this to false if not using a mirrored font var useMirroredFont = true var displayString = "" override func draw(in ctx: CGContext) { // A frame is passed in, in which the frame size is already rotated at the center but the content is not. ctx.saveGState() if useMirroredFont { ctx.rotate(by: CGFloat(M_PI_2)) ctx.scaleBy(x: 1.0, y: -1.0) } else { ctx.rotate(by: CGFloat(M_PI_2)) ctx.translateBy(x: 0, y: -self.bounds.width) } super.draw(in: ctx) ctx.restoreGState() } }
mit
66c408df584ce742938346ace5eaffe3
26.046154
113
0.574232
4.744939
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobile/AdUnits/Native/NativeMarkupRequestObject.swift
1
5298
/*   Copyright 2018-2021 Prebid.org, 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 @objcMembers public class NativeMarkupRequestObject: NSObject, NSCopying, PBMJsonCodable { /// [Recommended] /// [Integer] /// The context in which the ad appears. /// See NativeContextType public var context: ContextType? /// [Integer] /// A more detailed context in which the ad appears. /// See NativeContextSubtype public var contextsubtype: ContextSubType? /// [Recommended] /// [Integer] /// The design/format/layout of the ad unit being offered. /// See NativePlacementType public var plcmttype: PlacementType? /// [Integer] /// The number of identical placements in this Layout. Refer Section 8.1 Multiplacement Bid Requests for further detail. public var plcmtcnt = 1 /// [Integer] /// 0 for the first ad, 1 for the second ad, and so on. /// Note this would generally NOT be used in combination with plcmtcnt - /// either you are auctioning multiple identical placements (in which case plcmtcnt>1, seq=0) /// or you are holding separate auctions for distinct items in the feed (in which case plcmtcnt=1, seq=>=1) public var seq = 0 /// [Required] /// An array of Asset Objects. Any objects bid response must comply with the array of elements expressed in the bid request. public var assets: [NativeAsset]? /// [Integer] /// Whether the supply source / impression supports returning an assetsurl instead of an asset object. 0 or the absence of the field indicates no such support. public var aurlsupport = 0 /// [Integer] /// Whether the supply source / impression supports returning a dco url instead of an asset object. 0 or the absence of the field indicates no such support. /// Beta feature. public var durlsupport: Int = 0 /// Specifies what type of event objects tracking is supported - see Event Trackers Request Object public var eventtrackers: [NativeEventTracker]? /// [Recommended] /// [Integer] /// Set to 1 when the native ad supports buyer-specific privacy notice. Set to 0 (or field absent) when the native ad doesn’t support custom privacy links or if support is unknown. public var privacy = 0 /// This object is a placeholder that may contain custom JSON agreed to by the parties to support flexibility beyond the standard defined in this specification public var ext: [String : Any]? public override init() { super.init() } // MARK: - NSCopying public func copy(with zone: NSZone? = nil) -> Any { let clone = NativeMarkupRequestObject() clone.context = context clone.contextsubtype = contextsubtype clone.plcmttype = plcmttype clone.plcmtcnt = plcmtcnt clone.seq = seq clone.aurlsupport = aurlsupport clone.durlsupport = durlsupport clone.eventtrackers = eventtrackers clone.assets = assets clone.privacy = privacy clone.ext = ext return clone; } // MARK: - PBMJsonCodable public var jsonDictionary: [String : Any]? { var json = [String : Any]() json["context"] = context?.value json["contextsubtype"] = contextsubtype?.value json["plcmttype"] = plcmttype?.value json["seq"] = seq json["assets"] = jsonAssets() json["plcmtcnt"] = plcmtcnt json["aurlsupport"] = aurlsupport json["durlsupport"] = durlsupport json["eventtrackers"] = jsonTrackers() json["privacy"] = privacy json["ext"] = ext return json } public func toJsonString() throws -> String { try PBMFunctions.toStringJsonDictionary(jsonDictionary ?? [:]) } // MARK: - Private Methods func jsonAssets() -> [[AnyHashable : Any]] { var idCount: Int = 0 var assetsObjects: [[AnyHashable : Any]] = [] if let assets = assets { for asset in assets { if Prebid.shared.shouldAssignNativeAssetID { idCount += 1 } assetsObjects.append(asset.getAssetObject(id: idCount)) } } return assetsObjects } func jsonTrackers() -> [[AnyHashable : Any]]? { var res = [[AnyHashable : Any]]() if let eventtrackers = eventtrackers { for eventtracker in eventtrackers { res.append(eventtracker.getEventTracker()) } } return res.count == 0 ? nil : res } }
apache-2.0
6e8b4c24e508980e0c40dbe9321f0eba
35.19863
184
0.625733
4.587674
false
false
false
false
xivol/MCS-V3-Mobile
examples/graphics/Draw 2.0/Draw 2.0/PaletteCollectionViewController.swift
1
2215
// // PaletteCollectionViewController.swift // Draw 2.0 // // Created by Илья Лошкарёв on 04.10.17. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import UIKit class PaletteCollectionViewController: UICollectionViewController { weak var palette: Palette? var firstLayout: Bool = true var numberOfColorsToDisplay: Int { return self.collectionView?.dataSource?.collectionView(collectionView!, numberOfItemsInSection: 0) ?? 0 } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false palette = (UIApplication.shared.delegate as! AppDelegate).palette collectionView?.dataSource = palette // Select middle item selectColor(at: numberOfColorsToDisplay / 2) } func selectColor(at position: Int) { palette?.stroke = palette?.color(at: position) ?? UIColor.white collectionView?.selectItem(at: IndexPath(indexes: [0, position]), animated: false, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Select middle item if selection cleared if self.clearsSelectionOnViewWillAppear { selectColor(at: numberOfColorsToDisplay / 2) } firstLayout = true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // On first appear scroll to selected item if firstLayout { collectionView?.scrollToItem(at: collectionView?.indexPathsForSelectedItems?[0] ?? IndexPath(), at: .centeredHorizontally, animated: false) firstLayout = false } } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { palette?.stroke = palette?.color(at: indexPath.row) ?? UIColor.white collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally) } }
mit
81cee8b47fa8aeca21b792d51e058c44
34.322581
159
0.684475
5.530303
false
false
false
false
jersonperpetua/ReactiveArray
ReactiveArray/ReactiveArray.swift
1
4136
// // ReactiveArray.swift // ReactiveArray // // Created by Guido Marucci Blas on 6/29/15. // Copyright (c) 2015 Wolox. All rights reserved. // import Foundation // // ReactiveArray.swift // WLXViewModel // // Created by Guido Marucci Blas on 6/15/15. // Copyright (c) 2015 Wolox. All rights reserved. // import Foundation import ReactiveCocoa public final class ReactiveArray<T>: CollectionType, MutableCollectionType, CustomDebugStringConvertible { public typealias OperationProducer = SignalProducer<Operation<T>, NoError> public typealias OperationSignal = Signal<Operation<T>, NoError> private var _elements: Array<T> = [] private let (_signal, _sink) = OperationSignal.pipe() public var signal: OperationSignal { return _signal } public var producer: OperationProducer { let appendCurrentElements = OperationProducer(values:_elements.map { Operation.Append(value: $0) }) let forwardOperations = OperationProducer { (observer, dispoable) in self._signal.observe(observer) } return appendCurrentElements.concat(forwardOperations) } private let _mutableCount: MutableProperty<Int> public let observableCount:AnyProperty<Int> public var isEmpty: Bool { return _elements.isEmpty } public var count: Int { return _elements.count } public var startIndex: Int { return _elements.startIndex } public var endIndex: Int { return _elements.endIndex } public var first: T? { return _elements.first } public var last: T? { let value: T? if _elements.count > 0 { value = _elements[_elements.count - 1] } else { value = Optional.None } return value } public var debugDescription: String { return _elements.debugDescription } public init(elements:[T]) { _elements = elements _mutableCount = MutableProperty(elements.count) observableCount = AnyProperty(_mutableCount) _signal.observe { [unowned self](event) in if case .Next(let operation) = event { self.updateArray(operation) } } } public convenience init(producer: OperationProducer) { self.init() producer.start(_sink) } public convenience init() { self.init(elements: []) } public subscript(index: Int) -> T { get { return _elements[index] } set(newValue) { update(newValue, atIndex: index) } } public func append(element: T) { let operation: Operation<T> = .Append(value: element) _sink.sendNext(operation) } public func insert(newElement: T, atIndex index : Int) { let operation: Operation<T> = .Insert(value: newElement, atIndex: index) _sink.sendNext(operation) } public func update(element: T, atIndex index: Int) { let operation: Operation<T> = .Update(value: element, atIndex: index) _sink.sendNext(operation) } public func removeAtIndex(index:Int) { let operation: Operation<T> = .RemoveElement(atIndex: index) _sink.sendNext(operation) } public func mirror<U>(transformer: T -> U) -> ReactiveArray<U> { return ReactiveArray<U>(producer: producer.map { $0.map(transformer) }) } public func toArray() -> Array<T> { return _elements } private func updateArray(operation: Operation<T>) { switch operation { case .Append(let value): _elements.append(value) _mutableCount.value = _elements.count case .Insert(let value, let index): _elements.insert(value, atIndex: index) case .Update(let value, let index): _elements[index] = value case .RemoveElement(let index): _elements.removeAtIndex(index) _mutableCount.value = _elements.count } } }
mit
8df79d4c2dca6083b9db79767e6a0336
26.03268
109
0.600097
4.515284
false
false
false
false
SwiftKitz/Sandbox
Kitz/Kitz/DetailControllers/AppzViewController.swift
1
1263
// // AppzViewController.swift // Kitz // // Created by Mazyad Alabduljaleel on 12/19/15. // Copyright © 2015 kitz. All rights reserved. // import UIKit import Appz class AppzViewController: UIViewController { init() { super.init(nibName: nil, bundle: nil) title = "Appz" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let settingsButton = UIButton(type: .System) settingsButton.setTitle("Messages", forState: .Normal) settingsButton.addTarget(self, action: "openMessagesPressed", forControlEvents: .TouchUpInside) settingsButton.sizeToFit() settingsButton.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY) settingsButton.autoresizingMask = [ .FlexibleBottomMargin, .FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin, ] view.addSubview(settingsButton) } func openMessagesPressed() { let app = UIApplication.sharedApplication() app.open(Applications.Messages(), action: .SMS(phone: "1234")) } }
mit
b5c9f0088e27cadc10ca41733f9a7dba
25.291667
103
0.622029
4.798479
false
false
false
false
openHPI/xikolo-ios
Common/Data/ObjectsDidChangeNotification.swift
1
2267
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import CoreData public struct ObjectsDidChangeNotification { init(note: Notification) { assert(note.name == .NSManagedObjectContextObjectsDidChange) self.notification = note } public var insertedObjects: Set<NSManagedObject> { return objects(forKey: NSInsertedObjectsKey) } public var updatedObjects: Set<NSManagedObject> { return objects(forKey: NSUpdatedObjectsKey) } public var deletedObjects: Set<NSManagedObject> { return objects(forKey: NSDeletedObjectsKey) } public var refreshedObjects: Set<NSManagedObject> { return objects(forKey: NSRefreshedObjectsKey) } public var invalidatedObjects: Set<NSManagedObject> { return objects(forKey: NSInvalidatedObjectsKey) } public var invalidatedAllObjects: Bool { return (self.notification as Notification).userInfo?[NSInvalidatedAllObjectsKey] != nil } public var managedObjectContext: NSManagedObjectContext { guard let context = self.notification.object as? NSManagedObjectContext else { fatalError("Invalid notification object") } return context } // MARK: Private private let notification: Notification private func objects(forKey key: String) -> Set<NSManagedObject> { return ((self.notification as Notification).userInfo?[key] as? Set<NSManagedObject>) ?? Set() } } extension NSManagedObjectContext { /// Adds the given block to the default `NotificationCenter`'s dispatch table for the given context's objects-did-change notifications. /// - returns: An opaque object to act as the observer. This must be sent to the default `NotificationCenter`'s `removeObserver()`. public func addObjectsDidChangeNotificationObserver(_ handler: @escaping (ObjectsDidChangeNotification) -> Void) -> NSObjectProtocol { let notificationCenter = NotificationCenter.default return notificationCenter.addObserver(forName: .NSManagedObjectContextObjectsDidChange, object: self, queue: nil) { note in let wrappedNote = ObjectsDidChangeNotification(note: note) handler(wrappedNote) } } }
gpl-3.0
c71a94974fd2372835ff90db1c5abc63
33.861538
139
0.717123
5.221198
false
false
false
false
Xiomara7/Twitter-clone
Twitter-client/AppDelegate.swift
1
3119
// // AppDelegate.swift // Twitter-client // // Created by Xiomara on 10/28/16. // Copyright © 2016 Xiomara. All rights reserved. // import UIKit import BDBOAuth1Manager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if User.currentUser != nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "TweetsNC") window?.rootViewController = vc } NotificationCenter.default.addObserver( forName: NSNotification.Name(rawValue: User.userDidLogoutNotification), object: nil, queue: OperationQueue.main) { (notification) in let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateInitialViewController() self.window?.rootViewController = vc } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { TwitterClient.sharedInstance?.handleOpenURL(url: url) return true } }
mit
e07d8ccf4415f2ec386f086850d5dc4d
42.915493
285
0.708467
5.700183
false
false
false
false
hughbe/swift
test/SILGen/errors.swift
3
47827
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -Xllvm -sil-print-debuginfo -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s import Swift class Cat {} enum HomeworkError : Error { case TooHard case TooMuch case CatAteIt(Cat) } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // CHECK: sil hidden @_T06errors10make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[T0:%.*]] = function_ref @_T06errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: return [[T2]] : $Cat func make_a_cat() throws -> Cat { return Cat() } // CHECK: sil hidden @_T06errors15dont_make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[BOX]] func dont_make_a_cat() throws -> Cat { throw HomeworkError.TooHard } // CHECK: sil hidden @_T06errors11dont_return{{.*}}F : $@convention(thin) <T> (@in T) -> (@out T, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: destroy_addr %1 : $*T // CHECK-NEXT: throw [[BOX]] func dont_return<T>(_ argument: T) throws -> T { throw HomeworkError.TooMuch } // CHECK: sil hidden @_T06errors16all_together_nowAA3CatCSbF : $@convention(thin) (Bool) -> @owned Cat { // CHECK: bb0(%0 : $Bool): // CHECK: [[DR_FN:%.*]] = function_ref @_T06errors11dont_return{{.*}} : // CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat // Branch on the flag. // CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]] // In the true case, call make_a_cat(). // CHECK: [[FLAG_TRUE]]: // CHECK: [[MAC_FN:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]] // CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat) // In the false case, call dont_make_a_cat(). // CHECK: [[FLAG_FALSE]]: // CHECK: [[DMAC_FN:%.*]] = function_ref @_T06errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]] // CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat) // Merge point for the ternary operator. Call dont_return with the result. // CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat): // CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]] // CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]] // CHECK: [[DR_NORMAL]]({{%.*}} : $()): // CHECK-NEXT: dealloc_stack [[ARG_TEMP]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat) // Return block. // CHECK: [[RETURN]]([[T0:%.*]] : $Cat): // CHECK-NEXT: return [[T0]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error // CHECK-NEXT: store [[ERROR]] to [init] [[SRC_TEMP]] // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError // CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH]]([[T0:%.*]] : $Cat): // CHECK-NEXT: debug_value // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch all. // CHECK: [[CATCHALL]]: // CHECK: [[T0:%.*]] = function_ref @_T06errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: destroy_value [[ERROR]] : $Error // CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat) // Landing pad. // CHECK: [[MAC_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DR_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: dealloc_stack // CHECK-NEXT: dealloc_stack // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) func all_together_now(_ flag: Bool) -> Cat { do { return try dont_return(flag ? make_a_cat() : dont_make_a_cat()) } catch HomeworkError.CatAteIt(let cat) { return cat } catch _ { return Cat() } } // Catch in non-throwing context. // CHECK-LABEL: sil hidden @_T06errors11catch_a_catAA3CatCyF : $@convention(thin) () -> @owned Cat // CHECK-NEXT: bb0: // CHECK: [[F:%.*]] = function_ref @_T06errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]]) // CHECK-NEXT: return [[V]] : $Cat func catch_a_cat() -> Cat { do { return Cat() } catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} } // Initializers. class HasThrowingInit { var field: Int init(value: Int) throws { field = value } } // CHECK-LABEL: sil hidden @_T06errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error) // CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit // CHECK: [[T0:%.*]] = function_ref @_T06errors15HasThrowingInit{{.*}}c : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2 // CHECK: bb1([[SELF:%.*]] : $HasThrowingInit): // CHECK-NEXT: return [[SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[ERROR]] // CHECK-LABEL: sil hidden @_T06errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) { // CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[BORROWED_T0]] : $HasThrowingInit // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int // CHECK-NEXT: assign %0 to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit enum ColorError : Error { case Red, Green, Blue } //CHECK-LABEL: sil hidden @_T06errors6IThrows5Int32VyKF //CHECK: builtin "willThrow" //CHECK-NEXT: throw func IThrow() throws -> Int32 { throw ColorError.Red return 0 // expected-warning {{will never be executed}} } // Make sure that we are not emitting calls to 'willThrow' on rethrow sites. //CHECK-LABEL: sil hidden @_T06errors12DoesNotThrows5Int32VyKF //CHECK-NOT: builtin "willThrow" //CHECK: return func DoesNotThrow() throws -> Int32 { _ = try IThrow() return 2 } // rdar://20782111 protocol Doomed { func check() throws } // CHECK-LABEL: sil private [transparent] [thunk] @_T06errors12DoomedStructVAA0B0A2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*DoomedStruct // CHECK: [[T0:%.*]] = function_ref @_T06errors12DoomedStructV5checkyyKF : $@convention(method) (DoomedStruct) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: dealloc_stack [[TEMP]] // CHECK: throw [[T0]] : $Error struct DoomedStruct : Doomed { func check() throws {} } // CHECK-LABEL: sil private [transparent] [thunk] @_T06errors11DoomedClassCAA0B0A2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error Error { // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*DoomedClass // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> (), $@convention(method) (@guaranteed DoomedClass) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[BORROWED_SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]] // CHECK: throw [[T0]] : $Error class DoomedClass : Doomed { func check() throws {} } // CHECK-LABEL: sil private [transparent] [thunk] @_T06errors11HappyStructVAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*HappyStruct // CHECK: [[T0:%.*]] = function_ref @_T06errors11HappyStructV5checkyyF : $@convention(method) (HappyStruct) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T1]] : $() struct HappyStruct : Doomed { func check() {} } // CHECK-LABEL: sil private [transparent] [thunk] @_T06errors10HappyClassCAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*HappyClass // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> (), $@convention(method) (@guaranteed HappyClass) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] : $HappyClass // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T1]] : $() class HappyClass : Doomed { func check() {} } func create<T>(_ fn: () throws -> T) throws -> T { return try fn() } func testThunk(_ fn: () throws -> Int) throws -> Int { return try create(fn) } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Sis5Error_pIxdzo_SisAA_pIxrzo_TR : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error) // CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error Error)): // CHECK: try_apply %1() // CHECK: bb1([[T0:%.*]] : $Int): // CHECK: store [[T0]] to [trivial] %0 : $*Int // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: throw [[T0]] : $Error func createInt(_ fn: () -> Int) throws {} func testForceTry(_ fn: () -> Int) { try! createInt(fn) } // CHECK-LABEL: sil hidden @_T06errors12testForceTryySiycF : $@convention(thin) (@owned @callee_owned () -> Int) -> () // CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> Int): // CHECK: [[FUNC:%.*]] = function_ref @_T06errors9createIntySiycKF : $@convention(thin) (@owned @callee_owned () -> Int) -> @error Error // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: try_apply [[FUNC]]([[ARG_COPY]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return // CHECK: builtin "unexpectedError" // CHECK: unreachable func testForceTryMultiple() { _ = try! (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_T06errors20testForceTryMultipleyyF // CHECK-NEXT: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error) // CHECK-NEXT: unreachable // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_T06errors20testForceTryMultipleyyF' // Make sure we balance scopes correctly inside a switch. // <rdar://problem/20923654> enum CatFood { case Canned case Dry } // Something we can switch on that throws. func preferredFood() throws -> CatFood { return CatFood.Canned } func feedCat() throws -> Int { switch try preferredFood() { case .Canned: return 0 case .Dry: return 1 } } // CHECK-LABEL: sil hidden @_T06errors7feedCatSiyKF : $@convention(thin) () -> (Int, @error Error) // CHECK: debug_value undef : $Error, var, name "$error", argno 1 // CHECK: %1 = function_ref @_T06errors13preferredFoodAA03CatC0OyKF : $@convention(thin) () -> (CatFood, @error Error) // CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5 // CHECK: bb1([[VAL:%.*]] : $CatFood): // CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3 // CHECK: bb5([[ERROR:%.*]] : $Error) // CHECK: throw [[ERROR]] : $Error // Throwing statements inside cases. func getHungryCat(_ food: CatFood) throws -> Cat { switch food { case .Canned: return try make_a_cat() case .Dry: return try dont_make_a_cat() } } // errors.getHungryCat throws (errors.CatFood) -> errors.Cat // CHECK-LABEL: sil hidden @_T06errors12getHungryCatAA0D0CAA0D4FoodOKF : $@convention(thin) (CatFood) -> (@owned Cat, @error Error) // CHECK: bb0(%0 : $CatFood): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3 // CHECK: bb1: // CHECK: [[FN:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @_T06errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7 // CHECK: bb6([[ERROR:%.*]] : $Error): // CHECK: br bb8([[ERROR:%.*]] : $Error) // CHECK: bb7([[ERROR:%.*]] : $Error): // CHECK: br bb8([[ERROR]] : $Error) // CHECK: bb8([[ERROR:%.*]] : $Error): // CHECK: throw [[ERROR]] : $Error func take_many_cats(_ cats: Cat...) throws {} func test_variadic(_ cat: Cat) throws { try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_T06errors13test_variadicyAA3CatCKF : $@convention(thin) (@owned Cat) -> @error Error { // CHECK: bb0([[ARG:%.*]] : $Cat): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: [[TAKE_FN:%.*]] = function_ref @_T06errors14take_many_catsySayAA3CatCGd_tKF : $@convention(thin) (@owned Array<Cat>) -> @error Error // CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4 // CHECK: [[T0:%.*]] = function_ref @_T0s27_allocateUninitializedArray{{.*}}F // CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]]) // CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]] // CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 0 // CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]] // CHECK: [[T2:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 1 // CHECK: end_borrow [[BORROWED_T1]] from [[T1]] // CHECK: destroy_value [[T1]] // CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat // Element 0. // CHECK: [[T0:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]] // CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat): // CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]] // Element 1. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1 // CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]] // Element 2. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2 // CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]] // CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat): // CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]] // Element 3. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3 // CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]] // CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat): // CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]] // Complete the call and return. // CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]] // CHECK: [[NORM_CALL]]([[T0:%.*]] : $()): // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] : $Cat // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return // Failure from element 0. // CHECK: [[ERR_0]]([[ERROR:%.*]] : $Error): // CHECK-NOT: end_borrow // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T0s29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error) // Failure from element 2. // CHECK: [[ERR_2]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T0s29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from element 3. // CHECK: [[ERR_3]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[ELT2]] // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T0s29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from call. // CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Rethrow. // CHECK: [[RETHROW]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ARG]] : $Cat // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_T06errors13test_variadicyAA3CatCKF' // rdar://20861374 // Clear out the self box before delegating. class BaseThrowingInit : HasThrowingInit { var subField: Int init(value: Int, subField: Int) throws { self.subField = subField try super.init(value: value) } } // CHECK: sil hidden @_T06errors16BaseThrowingInit{{.*}}c : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error) // CHECK: [[BOX:%.*]] = alloc_box ${ var BaseThrowingInit } // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_BOX]] // Initialize subField. // CHECK: [[T0:%.*]] = load_borrow [[PB]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int // CHECK-NEXT: assign %1 to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[T0]] from [[PB]] // Super delegation. // CHECK-NEXT: [[T0:%.*]] = load [take] [[PB]] // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit // CHECK: [[T3:%[0-9]+]] = function_ref @_T06errors15HasThrowingInitCACSi5value_tKcfc : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: apply [[T3]](%0, [[T2]]) // Cleanups for writebacks. protocol Supportable { mutating func support() throws } protocol Buildable { associatedtype Structure : Supportable var firstStructure: Structure { get set } subscript(name: String) -> Structure { get set } } func supportFirstStructure<B: Buildable>(_ b: inout B) throws { try b.firstStructure.support() } // CHECK-LABEL: sil hidden @_T06errors21supportFirstStructure{{.*}}F : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error { // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: throw [[ERROR]] func supportStructure<B: Buildable>(_ b: inout B, name: String) throws { try b[name].support() } // CHECK-LABEL: sil hidden @_T06errors16supportStructure{{.*}}F // CHECK: bb0({{.*}}, [[INDEX:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[BORROWED_INDEX:%.*]] = begin_borrow [[INDEX]] // CHECK: [[INDEX_COPY:%.*]] = copy_value [[BORROWED_INDEX]] : $String // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[INDEX_COPY]], [[BASE:%[0-9]*]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: end_borrow [[BORROWED_INDEX]] from [[INDEX]] // CHECK: destroy_value [[INDEX]] : $String // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: destroy_value [[INDEX]] : $String // CHECK: throw [[ERROR]] struct Pylon { var name: String mutating func support() throws {} } struct Bridge { var mainPylon : Pylon subscript(name: String) -> Pylon { get { return mainPylon } set {} } } func supportStructure(_ b: inout Bridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_T06errors16supportStructureyAA6BridgeVz_SS4nametKF : $@convention(thin) (@inout Bridge, @owned String) -> @error Error { // CHECK: bb0([[ARG1:%.*]] : $*Bridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_T06errors5PylonV7supportyyKF // CHECK-NEXT: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]] // CHECK-NEXT: [[INDEX_COPY_1:%.*]] = copy_value [[BORROWED_ARG2]] : $String // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*Bridge // CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon // CHECK-NEXT: [[BASE:%.*]] = load_borrow [[WRITE]] : $*Bridge // CHECK-NEXT: // function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_T06errors6BridgeV9subscriptAA5PylonVSScfg : // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]]) // CHECK-NEXT: store [[T0]] to [init] [[TEMP]] // CHECK-NEXT: end_borrow [[BASE]] from [[WRITE]] // CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeV9subscriptAA5PylonVSScfs : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[WRITE]]) // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_INDEX]] from [[INDEX]] // CHECK-NEXT: destroy_value [[INDEX]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // We end up with ugly redundancy here because we don't want to // consume things during cleanup emission. It's questionable. // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeV9subscriptAA5PylonVSScfs : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[WRITE]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: dealloc_stack [[TEMP]] // ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY // CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[BORROWED_INDEX]] from [[INDEX]] // CHECK-NEXT: destroy_value [[INDEX]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_T06errors16supportStructureyAA6BridgeVz_SS4nametKF' struct OwnedBridge { var owner : Builtin.UnknownObject subscript(name: String) -> Pylon { addressWithOwner { return (someValidPointer(), owner) } mutableAddressWithOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout OwnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_T06errors16supportStructureyAA11OwnedBridgeVz_SS4nametKF : // CHECK: bb0([[ARG1:%.*]] : $*OwnedBridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_T06errors5PylonV7supportyyKF // CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]] // CHECK: [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*OwnedBridge // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_T06errors11OwnedBridgeV9subscriptAA5PylonVSScfaO : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[WRITE]]) // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0 // CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1 // CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]] // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]] // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_T06errors16supportStructureyAA11OwnedBridgeVz_SS4nametKF' struct PinnedBridge { var owner : Builtin.NativeObject subscript(name: String) -> Pylon { addressWithPinnedNativeOwner { return (someValidPointer(), owner) } mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout PinnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_T06errors16supportStructureyAA12PinnedBridgeVz_SS4nametKF : // CHECK: bb0([[ARG1:%.*]] : $*PinnedBridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_T06errors5PylonV7supportyyKF // CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]] // CHECK: [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*PinnedBridge // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_T06errors12PinnedBridgeV9subscriptAA5PylonVSScfaP : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[WRITE]]) // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0 // CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1 // CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]] // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]] // CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[OWNER]] // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]] // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_T06errors16supportStructureyAA12PinnedBridgeVz_SS4nametKF' // ! peepholes its argument with getSemanticsProvidingExpr(). // Test that that doesn't look through try!. // rdar://21515402 func testForcePeephole(_ f: () throws -> Int?) -> Int { let x = (try! f())! return x } // CHECK-LABEL: sil hidden @_T06errors15testOptionalTryyyF // CHECK-NEXT: bb0: // CHECK: [[FN:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>) // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_T06errors15testOptionalTryyyF' func testOptionalTry() { _ = try? make_a_cat() } // CHECK-LABEL: sil hidden @_T06errors18testOptionalTryVaryyF // CHECK-NEXT: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<Cat> } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<Cat> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_T06errors18testOptionalTryVaryyF' func testOptionalTryVar() { var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_T06errors26testOptionalTryAddressOnly{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_T06errors11dont_return{{.*}}F // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_T06errors26testOptionalTryAddressOnlyyxlF' func testOptionalTryAddressOnly<T>(_ obj: T) { _ = try? dont_return(obj) } // CHECK-LABEL: sil hidden @_T06errors29testOptionalTryAddressOnlyVar{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_T06errors11dont_return{{.*}}F // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_T06errors29testOptionalTryAddressOnlyVaryxlF' func testOptionalTryAddressOnlyVar<T>(_ obj: T) { var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_T06errors23testOptionalTryMultipleyyF // CHECK: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>) // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_T06errors23testOptionalTryMultipleyyF' func testOptionalTryMultiple() { _ = try? (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_T06errors25testOptionalTryNeverFailsyyF // CHECK: bb0: // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '_T06errors25testOptionalTryNeverFailsyyF' func testOptionalTryNeverFails() { _ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_T06errors28testOptionalTryNeverFailsVaryyF // CHECK: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<()> } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<()> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '_T06errors28testOptionalTryNeverFailsVaryyF' func testOptionalTryNeverFailsVar() { var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}} } // CHECK-LABEL: sil hidden @_T06errors36testOptionalTryNeverFailsAddressOnly{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '_T06errors36testOptionalTryNeverFailsAddressOnlyyxlF' func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) { _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_T06errors39testOptionalTryNeverFailsAddressOnlyVar{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '_T06errors13OtherErrorSubCACycfC' func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) { var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } class SomeErrorClass : Error { } // CHECK-LABEL: sil_vtable SomeErrorClass // CHECK-NEXT: #SomeErrorClass.init!initializer.1: {{.*}} : _T06errors14SomeErrorClassCACycfc // CHECK-NEXT: #SomeErrorClass.deinit!deallocator: _T06errors14SomeErrorClassCfD // CHECK-NEXT: } class OtherErrorSub : OtherError { } // CHECK-LABEL: sil_vtable OtherErrorSub { // CHECK-NEXT: #OtherError.init!initializer.1: {{.*}} : _T06errors13OtherErrorSubCACycfc // OtherErrorSub.init() // CHECK-NEXT: #OtherErrorSub.deinit!deallocator: _T06errors13OtherErrorSubCfD // OtherErrorSub.__deallocating_deinit // CHECK-NEXT:}
apache-2.0
9a09d3eb6cc37133fd56167fc7981948
48.544041
234
0.603618
3.183937
false
false
false
false
venturehacks/ZLSwipeableViewSwift
ZLSwipeableViewSwiftDemo/ZLSwipeableViewSwiftDemo/CustomDirectionDemoViewController.swift
1
919
// // CustomDirectionDemoViewController.swift // ZLSwipeableViewSwiftDemo // // Created by Zhixuan Lai on 5/25/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit class CustomDirectionDemoViewController: ZLSwipeableViewController { override func viewDidLoad() { super.viewDidLoad() let segmentControl = UISegmentedControl(items: [" ", "←", "↑", "→", "↓", "↔︎", "↕︎", "☩"]) segmentControl.selectedSegmentIndex = 5 navigationItem.titleView = segmentControl let directions: [ZLSwipeableViewDirection] = [.None, .Left, .Up, .Right, .Down, .Horizontal, .Vertical, .All] segmentControl.forControlEvents(.ValueChanged) { control in if let control = control as? UISegmentedControl { self.swipeableView.direction = directions[control.selectedSegmentIndex] } } } }
mit
01ca6213c8450080ed7bce13f2f9efcb
31.178571
117
0.648169
4.692708
false
false
false
false
iAladdin/SwiftyFORM
Source/Cells/StaticTextCell.swift
1
756
// // StaticTextCell.swift // SwiftyFORM // // Created by Simon Strandgaard on 08/11/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit public struct StaticTextCellModel { var title: String = "" var value: String = "" } public class StaticTextCell: UITableViewCell { public let model: StaticTextCellModel public init(model: StaticTextCellModel) { self.model = model super.init(style: .Value1, reuseIdentifier: nil) loadWithModel(model) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func loadWithModel(model: StaticTextCellModel) { selectionStyle = .None textLabel?.text = model.title detailTextLabel?.text = model.value } }
mit
823ed2621cd5983cffa86b91292aeee0
20.6
62
0.728836
3.549296
false
false
false
false
exyte/Macaw
MacawTests/Bounds/NodeBoundsTests.swift
1
11235
// // NodeBoundsTests.swift // Macaw // // Created by Daniil Manin on 5/10/17. // Copyright © 2017 Exyte. All rights reserved. // import XCTest #if os(OSX) @testable import MacawOSX #elseif os(iOS) @testable import Macaw #endif class NodeBoundsTests: XCTestCase { var window: MWindow! //TO DO: need to test paths bounds: M 50 50 C 20 20, 40 20, 50 10 and M 50 50 c 20 20, 40 20, 50 10 //currently doesn't work because of http://www.openradar.me/6468254639 or #41355347 on https://bugreport.apple.com/ override func setUp() { super.setUp() window = MWindow() } override func tearDown() { super.tearDown() } func checkBounds(rect1: Rect?, rect2: Rect) { if let rect = rect1 { XCTAssertTrue(rect == rect2, "Test failed. Rects not equal") } } func validate(node: Node, referenceBounds: Rect) { let passingThreshold = 0.2 var testResult = false if let bounds = node.bounds { testResult = (Double(round(100*bounds.x)/100) - referenceBounds.x < passingThreshold) testResult = testResult && (Double(round(100*bounds.y)/100) - referenceBounds.y < passingThreshold) testResult = testResult && (Double(round(100*bounds.w)/100) - referenceBounds.w < passingThreshold) testResult = testResult && (Double(round(100*bounds.h)/100) - referenceBounds.h < passingThreshold) } XCTAssert(testResult) } // MARK: - Shapes func testSimpleShapeZeroBounds() { let shape = Shape(form: Rect.zero()) checkBounds(rect1: shape.bounds, rect2: Rect.zero()) } func testSimpleShapeRect() { // Rect / RoundRect let shape = Shape(form: RoundRect(rect: Rect(x: 20.0, y: 15.0, w: 10.0, h: 10.0), rx: 8.0, ry: 1.0)) let targetRect = Rect(x: 20.0, y: 15.0, w: 10.0, h: 10.0) checkBounds(rect1: shape.bounds, rect2: targetRect) } func testShapePoint() { let shape = Shape(form: Point(x: 10.0, y: 20.0)) let targetRect = Rect(x: 10.0, y: 20.0, w: 0.0, h: 0.0) checkBounds(rect1: shape.bounds, rect2: targetRect) } func testShapeCircle() { let shape = Shape(form: Circle(cx: 10.0, cy: 15.0, r: 3.0)) let targetRect = Rect(x: 7.0, y: 12.0, w: 6.0, h: 6.0) checkBounds(rect1: shape.bounds, rect2: targetRect) } func testShapeEllipse() { // Ellipse / Arc let targetRect = Rect(x: 97.0, y: 43.0, w: 6.0, h: 14.0) let ellipse = Ellipse(cx: 100.0, cy: 50.0, rx: 3.0, ry: 7.0) let shape = Shape(form: ellipse) checkBounds(rect1: shape.bounds, rect2: targetRect) } func testShapePath() { let segment = PathSegment(type: .M, data: [0, 0]) var builder = PathBuilder(segment: segment) builder = builder.lineTo(x: -5.0, y: 0.0) builder = builder.lineTo(x: 7.0, y: 4.0) builder = builder.lineTo(x: 0.0, y: -1.0) builder = builder.lineTo(x: 10.0, y: 0.0) builder = builder.moveTo(x: 20.0, y: 20.0) builder = builder.lineTo(x: 25.0, y: 25.0) let path = builder.build() let shape = Shape(form: path) let targetRect = Rect(x: -5.0, y: -1.0, w: 30.0, h: 26.0) checkBounds(rect1: shape.bounds, rect2: targetRect) } func testShapeLine() { let shape = Shape(form: Line(x1: 10.0, y1: 15.0, x2: 1.0, y2: 1.0)) let targetRect = Rect(x: 1.0, y: 1.0, w: 9.0, h: 14.0) checkBounds(rect1: shape.bounds, rect2: targetRect) } func testShapePoly(points: [Double], targetRect: Rect) { var shape = Shape(form: Polyline(points: points)) checkBounds(rect1: shape.bounds, rect2: targetRect) shape = Shape(form: Polygon(points: points)) checkBounds(rect1: shape.bounds, rect2: targetRect) } func testShapePoly() { let points: [Double] = [ 0, 2, 1, 7, 8, 8, 100, 10, -5, 3] let targetRect = Rect(x: -5.0, y: 2.0, w: 105.0, h: 8.0) testShapePoly(points: points, targetRect: targetRect) } func testShapePolyWithoutPoints() { let targetRect = Rect.zero() testShapePoly(points: [], targetRect: targetRect) } func testShapePolyOnePoint() { let points: [Double] = [7, 4] let targetRect = Rect(x: 7.0, y: 4.0, w: 0.0, h: 0.0) testShapePoly(points: points, targetRect: targetRect) } // MARK: - Image func testSimpleImageZeroBounds() { let image = Image(src: "") XCTAssertNil(image.bounds, "Image bounds not nil") } // MARK: - Text func testSimpleText() { let texts = ["", "Hello, World", "Hello,\nWorld", "\nHello\n,\nWorld"] texts.forEach { text in let text = Text(text: text) let stringAttributes = [NSAttributedString.Key.font: MFont.systemFont(ofSize: MFont.systemFontSize)] let size = text.text.size(withAttributes: stringAttributes) let targetRect = Rect(x: 0.0, y: 0.0, w: size.width.doubleValue, h: size.height.doubleValue) checkBounds(rect1: text.bounds, rect2: targetRect) } } func testTextWithKerning() { let texts = ["", "Hello, World", "Hello,\nWorld", "\nHello\n,\nWorld"] let kernings : [Float] = [-1.0, -0.5, 0.5, 1.0] texts.forEach { (text) in kernings.forEach({ (kerning) in let text = Text(text: text, kerning: kerning) let stringAttributes = [NSAttributedString.Key.font: MFont.systemFont(ofSize: MFont.systemFontSize), NSAttributedString.Key.kern: NSNumber(value: kerning)] let size = text.text.size(withAttributes: stringAttributes) let targetRect = Rect(x: 0.0, y: 0.0, w: size.width.doubleValue, h: size.height.doubleValue) checkBounds(rect1: text.bounds, rect2: targetRect) }) } } // MARK: - Group func testSimpleGroupZeroBounds() { let group = [].group() XCTAssertNil(group.bounds, "Group bounds not nil") } func testGroupZeroBounds() { var shapes: [Node] = [] for _ in 0...10 { let shape = Shape(form: Rect.zero()) shapes.append(shape) } let group = shapes.group() checkBounds(rect1: group.bounds, rect2: Rect.zero()) } func testGroupRectInRect() { // ************* // * * // * ******* * // * * * * // * ******* * // * * // ************* let targetRect = Rect(x: 0.0, y: 0.0, w: 100.0, h: 100.0) let shape = Shape(form: targetRect) let internalShape = Shape(form: Rect(x: 25.0, y: 25.0, w: 50.0, h: 50.0)) let group = [shape, internalShape].group() checkBounds(rect1: group.bounds, rect2: targetRect) } func testGroupRectBetweenRects() { // ************* ************* // * * * * // * * ******* * * // * * * * * * // * * ******* * * // * * * * // ************* * * // * * // ************* let targetRect = Rect(x: 10.0, y: 0.0, w: 290.0, h: 150.0) let leftShape = Shape(form: Rect(x: 10.0, y: 0.0, w: 100.0, h: 100.0)) let midShape = Shape(form: Rect(x: 125.0, y: 25.0, w: 50.0, h: 50.0)) let rightShape = Shape(form: Rect(x: 200.0, y: 0.0, w: 100.0, h: 150.0)) let group = [leftShape, midShape, rightShape].group() checkBounds(rect1: group.bounds, rect2: targetRect) } func testPathBounds1() { let path = MoveTo(x: 101.9, y: 40.5) .c(0, -1.8, 1.5, -3.3, 3.3, -3.3) .s(3.3, 1.5, 3.3, 3.3) .v(27.4) .c(0, 1.8, -1.5, 3.3, -3.3, 3.3) .s(-3.3, -1.5, -3.3, -3.3) .V(40.5).Z().build() let shape = Shape(form: path) let targetRect = Rect(x: 101.9, y: 37.2, w: 6.6, h: 34.0) validate(node: shape, referenceBounds: targetRect) } func testPathBounds2() { let path = MoveTo(x: 68, y: 101.9) .c(1.8, 0, 3.3, 1.5, 3.3, 3.3) .s(-1.5, 3.3, -3.3, 3.3) .H(40.5) .c(-1.8, 0, -3.3, -1.5, -3.3, -3.3) .s(1.5, -3.3, 3.3, -3.3) .H(68).Z().build() let shape = Shape(form: path) let stroke = Stroke(fill: Color.black, width: 1.0, cap: .butt, join: .miter, miterLimit: 4.0, dashes: [], offset: 0.0) shape.stroke = stroke let targetRect = Rect(x: 36.7, y: 101.4, w: 35.1, h: 7.6) validate(node: shape, referenceBounds: targetRect) } func testPathBounds3() { let path = MoveTo(x: 25, y: 49.5) .C(38.5309764, 49.5, 49.5, 38.5309764, 49.5, 25) .C(49.5, 11.4690236, 38.5309764, 0.5, 25, 0.5) .C(11.4690236, 0.5, 0.5, 11.4690236, 0.5, 25) .C(0.5, 38.5309764, 11.4690236, 49.5, 25, 49.5).Z().build() let shape = Shape(form: path) let stroke = Stroke(fill: Color.black, width: 1.0, cap: .butt, join: .miter, miterLimit: 4.0, dashes: [], offset: 0.0) shape.stroke = stroke let targetRect = Rect(x: 0.0, y: 0.0, w: 50, h: 50) validate(node: shape, referenceBounds: targetRect) } func testPathBounds4() { let path = MoveTo(x: 10, y: 80) .C(40, 10, 65, 10, 95, 80) .S(150, 150, 180, 80).build() let shape = Shape(form: path) let targetRect = Rect(x: 10, y: 10, w: 170, h: 140) validate(node: shape, referenceBounds: targetRect) } func testPolyline() { let polyline = Polyline(points: [270, 225, 300, 245, 320, 225, 340, 245, 280, 280, 390, 280, 420, 240, 280, 185]) let stroke = Stroke(fill: Color(val: 30464), width: 8, cap: .butt, join: .miter, miterLimit: 4.0, dashes: [], offset: 0.0) let shape = Shape(form: polyline) shape.stroke = stroke let targetRect = Rect(x: 265.2, y: 181.3, w: 161.2, h: 102.7) validate(node: shape, referenceBounds: targetRect) } }
mit
57902941e780cfe7324e2273298334fa
33.888199
130
0.490386
3.466214
false
true
false
false
simplymadeapps/SMASaveSystem
Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift
4
4457
// // MD5.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 06/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // final class MD5 : HashProtocol { static let size:Int = 16 // 128 / 8 let message: Array<UInt8> init (_ message: Array<UInt8>) { self.message = message } /** specifies the per-round shift amounts */ private let s: Array<UInt32> = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let k: Array<UInt32> = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee, 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be, 0x6b901122,0xfd987193,0xa679438e,0x49b40821, 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa, 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8, 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed, 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c, 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05, 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039, 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1, 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391] private let h:Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> Array<UInt8> { var tmpMessage = prepare(64) tmpMessage.reserveCapacity(tmpMessage.count + 4) // initialize hh with hash values var hh = h // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.count * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage += lengthBytes.reverse() // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M = toUInt32Array(chunk) assert(M.count == 16, "Invalid array") // Initialize hash value for this chunk: var A:UInt32 = hh[0] var B:UInt32 = hh[1] var C:UInt32 = hh[2] var D:UInt32 = hh[3] var dTemp:UInt32 = 0 // Main loop for j in 0..<k.count { var g = 0 var F:UInt32 = 0 switch (j) { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), s[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } var result = Array<UInt8>() result.reserveCapacity(hh.count / 4) hh.forEach { let itemLE = $0.littleEndian result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)] } return result } }
mit
7d128af14522f43b072f71016366f998
36.737288
133
0.465529
3.264663
false
false
false
false
nessBautista/iOSBackup
iOSNotebook/Pods/Outlaw/Sources/Outlaw/Dictionary.swift
1
2539
// // Dictionary.swift // Outlaw // // Created by Brian Mullen on 11/18/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import Foundation public extension Dictionary { public static func value(from object: Any) throws -> [Key: Value] { guard let value = object as? [Key: Value] else { throw OutlawError.typeMismatch(expected: self, actual: type(of: object)) } return value } public static func value(from object: Any) throws -> [Key: Value?] { guard let anyDictionary = object as? [Key: Any?] else { throw OutlawError.typeMismatch(expected: self, actual: type(of: object)) } return anyDictionary.map { (key, anyValue) in return (key, anyValue as? Value) } } } // MARK: - // MARK: Transforms public extension Dictionary { public static func value<T>(from object: Any, with transform:(Value) throws -> T) throws -> [Key: T] { guard let anyDictionary = object as? [Key: Value] else { throw OutlawError.typeMismatch(expected: self, actual: type(of: object)) } return try anyDictionary.map { (key, anyValue) in return (key, try transform(anyValue)) } } public static func value<T>(from object: Any, with transform:(Value?) throws -> T) throws -> [Key: T] { guard let anyDictionary = object as? [Key: Value?] else { throw OutlawError.typeMismatch(expected: self, actual: type(of: object)) } return try anyDictionary.map { (key, anyValue) in return (key, try transform(anyValue)) } } public static func value<T>(from object: Any, with transform:(Value) -> T?) throws -> [Key: T?] { guard let anyDictionary = object as? [Key: Value?] else { throw OutlawError.typeMismatch(expected: self, actual: type(of: object)) } return anyDictionary.map { (key, anyValue) in guard let rawValue = anyValue else { return (key, nil) } return (key, transform(rawValue)) } } public static func value<T>(from object: Any, with transform:(Value?) -> T?) throws -> [Key: T?] { guard let anyDictionary = object as? [Key: Value?] else { throw OutlawError.typeMismatch(expected: self, actual: type(of: object)) } return anyDictionary.map { (key, anyValue) in return (key, transform(anyValue)) } } }
cc0-1.0
41202600f175310047e7126a91358806
32.394737
107
0.5855
4.215947
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift
28
1918
// // AsyncLock.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** In case nobody holds this lock, the work will be queued and executed immediately on thread that is requesting lock. In case there is somebody currently holding that lock, action will be enqueued. When owned of the lock finishes with it's processing, it will also execute and pending work. That means that enqueued work could possibly be executed later on a different thread. */ class AsyncLock : Disposable { typealias Action = () -> Void private var lock = NSRecursiveLock() private var queue: Queue<Action> = Queue(capacity: 2) private var isAcquired: Bool = false private var hasFaulted: Bool = false init() { } func wait(action: Action) { let isOwner = lock.calculateLocked { () -> Bool in if self.hasFaulted { return false } self.queue.enqueue(action) let isOwner = !self.isAcquired self.isAcquired = true return isOwner } if !isOwner { return } while true { let nextAction = lock.calculateLocked { () -> Action? in if self.queue.count > 0 { return self.queue.dequeue() } else { self.isAcquired = false return nil } } if let nextAction = nextAction { nextAction() } else { return } } } func dispose() { lock.performLocked { oldState in self.queue = Queue(capacity: 0) self.hasFaulted = true } } }
gpl-3.0
7c3bbaf4e6ac3531608bc87dc34a3d2f
23.922078
85
0.522941
5.047368
false
false
false
false
shajrawi/swift
stdlib/public/Darwin/Network/NWConnection.swift
2
26709
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Dispatch import Foundation import _SwiftNetworkOverlayShims /// An NWConnection is an object that represents a bi-directional data pipe between /// a local endpoint and a remote endpoint. /// /// A connection handles establishment of any transport, security, or application-level protocols /// required to transmit and receive user data. Multiple protocol instances may be attempted during /// the establishment phase of the connection. // NOTE: older overlays had Network.NWConnection as the ObjC name. // The two must coexist, so it was renamed. The old name must not be // used in the new runtime. _TtC7Network13_NWConnection is the // mangled name for Network._NWConnection. @_objcRuntimeName(_TtC7Network13_NWConnection) @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public final class NWConnection : CustomDebugStringConvertible { public var debugDescription: String { return String("\(self.nw)") } /// States a connection may be in public enum State : Equatable { /// The initial state prior to start case setup /// Waiting connections have not yet been started, or do not have a viable network case waiting(NWError) /// Preparing connections are actively establishing the connection case preparing /// Ready connections can send and receive data case ready /// Failed connections are disconnected and can no longer send or receive data case failed(NWError) /// Cancelled connections have been invalidated by the client and will send no more events case cancelled internal init(_ nw: nw_connection_state_t, _ err: nw_error_t?) { switch nw { case Network.nw_connection_state_invalid: self = .setup case Network.nw_connection_state_waiting: if let error = NWError(err) { self = .waiting(error) } else { self = .waiting(NWError.posix(.ENETDOWN)) } case Network.nw_connection_state_preparing: self = .preparing case Network.nw_connection_state_ready: self = .ready case Network.nw_connection_state_failed: if let error = NWError(err) { self = .failed(error) } else { self = .failed(NWError.posix(.EINVAL)) } case Network.nw_connection_state_cancelled: self = .cancelled default: self = .cancelled } } } internal let nw : nw_connection_t private var _state = NWConnection.State.setup /// Access the current state of the connection public var state: NWConnection.State { return _state } private var _stateUpdateHandler: ((_ state: NWConnection.State) -> Void)? /// Set a block to be called when the connection's state changes, which may be called /// multiple times until the connection is cancelled. public var stateUpdateHandler: ((_ state: NWConnection.State) -> Void)? { set { self._stateUpdateHandler = newValue if let newValue = newValue { nw_connection_set_state_changed_handler(self.nw) { (state, error) in self._state = NWConnection.State(state, error) newValue(self._state) } } else { nw_connection_set_state_changed_handler(self.nw) { (state, error) in self._state = NWConnection.State(state, error) } } } get { return self._stateUpdateHandler } } /// Retrieve the maximum datagram size that can be sent /// on the connection. Any datagrams sent should be less /// than or equal to this size. @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public var maximumDatagramSize: Int { get { return Int(nw_connection_get_maximum_datagram_size(self.nw)) } } private var _currentPath: NWPath? = nil /// Current path for the connection, which can be used to extract interface and effective endpoint information public var currentPath: NWPath? { get { if let path = nw_connection_copy_current_path(self.nw) { return NWPath(path) } return nil } } private var _pathUpdateHandler: ((_ newPath: NWPath) -> Void)? /// Set a block to be called when the connection's path has changed, which may be called /// multiple times until the connection is cancelled. public var pathUpdateHandler: ((_ newPath: NWPath) -> Void)? { set { self._pathUpdateHandler = newValue if let newValue = newValue { nw_connection_set_path_changed_handler(self.nw) { (nwPath) in let newPath = NWPath(nwPath) self._currentPath = newPath newValue(newPath) } } else { nw_connection_set_path_changed_handler(self.nw, nil) } } get { return self._pathUpdateHandler } } private var _viabilityUpdateHandler: ((_ isViable: Bool) -> Void)? /// Set a block to be called when the connection's viability changes, which may be called /// multiple times until the connection is cancelled. /// /// Connections that are not currently viable do not have a route, and packets will not be /// sent or received. There is a possibility that the connection will become viable /// again when network connectivity changes. public var viabilityUpdateHandler: ((_ isViable: Bool) -> Void)? { set { self._viabilityUpdateHandler = newValue if let newValue = newValue { nw_connection_set_viability_changed_handler(self.nw) { (isViable) in newValue(isViable) } } else { nw_connection_set_viability_changed_handler(self.nw, nil) } } get { return self._viabilityUpdateHandler } } private var _betterPathUpdateHandler: ((_ betterPathAvailable: Bool) -> Void)? /// A better path being available indicates that the system thinks there is a preferred path or /// interface to use, compared to the one this connection is actively using. As an example, the /// connection is established over an expensive cellular interface and an unmetered Wi-Fi interface /// is now available. /// /// Set a block to be called when a better path becomes available or unavailable, which may be called /// multiple times until the connection is cancelled. /// /// When a better path is available, if it is possible to migrate work from this connection to a new connection, /// create a new connection to the endpoint. Continue doing work on this connection until the new connection is /// ready. Once ready, transition work to the new connection and cancel this one. public var betterPathUpdateHandler: ((_ betterPathAvailable: Bool) -> Void)? { set { self._betterPathUpdateHandler = newValue if let newValue = newValue { nw_connection_set_better_path_available_handler(self.nw) { (betterPathAvailable) in newValue(betterPathAvailable) } } else { nw_connection_set_better_path_available_handler(self.nw, nil) } } get { return self._betterPathUpdateHandler } } /// The remote endpoint of the connection public let endpoint: NWEndpoint /// The set of parameters with which the connection was created public let parameters: NWParameters private init(to: NWEndpoint, using: NWParameters, connection: nw_connection_t) { self.endpoint = to self.parameters = using self.nw = connection nw_connection_set_state_changed_handler(self.nw) { (state, error) in self._state = NWConnection.State(state, error) } } convenience internal init?(using: NWParameters, inbound: nw_connection_t) { guard let peer = NWEndpoint(nw_connection_copy_endpoint(inbound)) else { return nil } self.init(to: peer, using: using, connection: inbound) } /// Create a new outbound connection to an endpoint, with parameters. /// The parameters determine the protocols to be used for the connection, and their options. /// /// - Parameter to: The remote endpoint to which to connect. /// - Parameter using: The parameters define which protocols and path to use. public init(to: NWEndpoint, using: NWParameters) { self.endpoint = to self.parameters = using self.nw = nw_connection_create(to.nw!, using.nw) nw_connection_set_state_changed_handler(self.nw) { (state, error) in self._state = NWConnection.State(state, error) } } /// Create a new outbound connection to a hostname and port, with parameters. /// The parameters determine the protocols to be used for the connection, and their options. /// /// - Parameter host: The remote hostname to which to connect. /// - Parameter port: The remote port to which to connect. /// - Parameter using: The parameters define which protocols and path to use. public convenience init(host: NWEndpoint.Host, port: NWEndpoint.Port, using: NWParameters) { self.init(to: .hostPort(host: host, port: port), using: using) } /// Start the connection and provide a dispatch queue for callback blocks. /// /// Starts the connection, which will cause the connection to evaluate its path, do resolution and try to become /// ready (connected). NWConnection establishment is asynchronous. A stateUpdateHandler may be used to determine /// when the state changes. If the connection can not be established, the state will transition to waiting with /// an associated error describing the reason. If an unrecoverable error is encountered, the state will /// transition to failed with an associated NWError value. If the connection is established, the state will /// transition to ready. /// /// Start should only be called once on a connection, and multiple calls to start will /// be ignored. public func start(queue: DispatchQueue) { self._queue = queue nw_connection_set_queue(self.nw, queue) nw_connection_start(self.nw) } private var _queue: DispatchQueue? /// Get queue used for delivering block handlers, such as stateUpdateHandler, pathUpdateHandler, /// viabilityUpdateHandler, betterPathUpdateHandler, and completions for send and receive. /// If the connection has not yet been started, the queue will be nil. Once the connection has been /// started, the queue will be valid. public var queue: DispatchQueue? { get { return self._queue } } /// Cancel the connection, and cause all update handlers to be cancelled. /// /// Cancel is asynchronous. The last callback will be to the stateUpdateHandler with the cancelled state. After /// the stateUpdateHandlers are called with the cancelled state, all blocks are released to break retain cycles. /// /// Calls to cancel after the first one are ignored. public func cancel() { nw_connection_cancel(self.nw) } /// A variant of cancel that performs non-graceful closure of the transport. public func forceCancel() { nw_connection_force_cancel(self.nw) } /// Cancel the currently connected endpoint, causing the connection to fall through to the next endpoint if /// available, or to go to the waiting state if no more endpoints are available. public func cancelCurrentEndpoint() { nw_connection_cancel_current_endpoint(self.nw) } /// NWConnections will normally re-attempt on network changes. This function causes a connection that is in /// the waiting state to re-attempt even without a network change. public func restart() { nw_connection_restart(self.nw) } /// Content Context controls options for how data is sent, and access for metadata to send or receive. /// All properties of Content Context are valid for sending. For received Content Context, only the protocolMetadata /// values will be set. // Set the ObjC name of this class to be nested in the customized ObjC name of NWConnection. @_objcRuntimeName(_TtCC7Network13_NWConnection14ContentContext) public class ContentContext { internal let nw: nw_content_context_t /// A string description of the content, used for logging and debugging. public let identifier: String /// An expiration in milliseconds after scheduling a send, after which the content may be dropped. /// Defaults to 0, which implies no expiration. Used only when sending. public let expirationMilliseconds: UInt64 /// A numeric value between 0.0 and 1.0 to specify priority of this data/message. Defaults to 0.5. /// Used only when sending. public let relativePriority: Double /// Any content marked as an antecedent must be sent prior to this content being sent. Defaults to nil. /// Used only when sending. public let antecedent: NWConnection.ContentContext? /// A boolean indicating if this context is the final context in a given direction on this connection. Defaults to false. public let isFinal: Bool /// An array of protocol metadata to send (to inform the protocols of per-data options) or receive (to receive per-data options or statistics). public var protocolMetadata: [NWProtocolMetadata] { get { var metadataArray: [NWProtocolMetadata] = [] nw_content_context_foreach_protocol_metadata(self.nw) { (definition, metadata) in if nw_protocol_metadata_is_tcp(metadata) { metadataArray.append(NWProtocolTCP.Metadata(metadata)) } else if nw_protocol_metadata_is_udp(metadata) { metadataArray.append(NWProtocolUDP.Metadata(metadata)) } else if nw_protocol_metadata_is_ip(metadata) { metadataArray.append(NWProtocolIP.Metadata(metadata)) } else if nw_protocol_metadata_is_tls(metadata) { metadataArray.append(NWProtocolTLS.Metadata(metadata)) } } return metadataArray } } /// Access the metadata for a specific protocol from a context. The metadata may be nil. public func protocolMetadata(definition: NWProtocolDefinition) -> NWProtocolMetadata? { if let metadata = nw_content_context_copy_protocol_metadata(self.nw, definition.nw) { if nw_protocol_metadata_is_tcp(metadata) { return NWProtocolTCP.Metadata(metadata) } else if nw_protocol_metadata_is_udp(metadata) { return NWProtocolUDP.Metadata(metadata) } else if nw_protocol_metadata_is_ip(metadata) { return NWProtocolIP.Metadata(metadata) } else if nw_protocol_metadata_is_tls(metadata) { return NWProtocolTLS.Metadata(metadata) } } return nil } /// Create a context for sending, that optionally can set expiration (default 0), /// priority (default 0.5), antecedent (default nil), and protocol metadata (default []]). public init(identifier: String, expiration: UInt64 = 0, priority: Double = 0.5, isFinal: Bool = false, antecedent: NWConnection.ContentContext? = nil, metadata: [NWProtocolMetadata]? = []) { self.nw = nw_content_context_create(identifier) self.identifier = identifier self.expirationMilliseconds = expiration nw_content_context_set_expiration_milliseconds(self.nw, expiration) self.relativePriority = priority nw_content_context_set_relative_priority(self.nw, priority) self.isFinal = isFinal nw_content_context_set_is_final(self.nw, isFinal) self.antecedent = antecedent if let otherContext = antecedent { nw_content_context_set_antecedent(self.nw, otherContext.nw) } if let metadataArray = metadata { for singleMetadata in metadataArray { nw_content_context_set_metadata_for_protocol(self.nw, singleMetadata.nw) } } } /// Use the default message context to send content with all default properties: /// default priority, no expiration, and not the final message. Marking this context /// as complete with a send indicates that the message content is now complete and any /// other messages that were blocked may be scheduled, but will not close the underlying /// connection. Use this context for any lightweight sends of datagrams or messages on /// top of a stream that do not require special properties. /// This context does not support overriding any properties. public static let defaultMessage : NWConnection.ContentContext = NWConnection.ContentContext(_swift_nw_content_context_default_message())! /// Use the final message context to indicate that no more sends are expected /// once this context is complete. Like .defaultMessage, all properties are default. /// Marking a send as complete when using this context will close the sending side of the /// underlying connection. This is the equivalent of sending a FIN on a TCP stream. /// This context does not support overriding any properties. public static let finalMessage : NWConnection.ContentContext = NWConnection.ContentContext(_swift_nw_content_context_final_message())! /// Use the default stream context to indicate that this sending context is /// the one that represents the entire connection. All context properties are default. /// This context behaves in the same way as .finalMessage, such that marking the /// context complete by sending isComplete will close the sending side of the /// underlying connection (a FIN for a TCP stream). /// Note that this context is a convenience for sending a single, final context. /// If the protocol used by the connection is a stream (such as TCP), the caller /// may still use .defaultMessage, .finalMessage, or a custom context with priorities /// and metadata to set properties of a particular chunk of stream data relative /// to other data on the stream. /// This context does not support overriding any properties. public static let defaultStream : NWConnection.ContentContext = NWConnection.ContentContext(_swift_nw_content_context_default_stream())! internal init?(_ nw: nw_content_context_t?) { guard let nw = nw else { return nil } self.nw = nw // Received content context doesn't have expiration, priority, or antecedents self.expirationMilliseconds = 0 self.relativePriority = 0 self.antecedent = nil self.isFinal = nw_content_context_get_is_final(nw) self.identifier = String(cString: nw_content_context_get_identifier(nw)) } } /// Receive data from a connection. This may be called before the connection /// is ready, in which case the receive request will be queued until the /// connection is ready. The completion handler will be invoked exactly /// once for each call, so the client must call this function multiple /// times to receive multiple chunks of data. For protocols that /// support flow control, such as TCP, calling receive opens the receive /// window. If the client stops calling receive, the receive window will /// fill up and the remote peer will stop sending. /// - Parameter minimumIncompleteLength: The minimum length to receive from the connection, /// until the content is complete. /// - Parameter maximumLength: The maximum length to receive from the connection in a single completion. /// - Parameter completion: A receive completion is invoked exactly once for a call to receive(...). /// The completion indicates that the requested content has been received (in which case /// the content is delivered), or else an error has occurred. Parameters to the completion are: /// /// - content: The received content, as constrained by the minimum and maximum length. This may /// be nil if the message or stream is complete (without any more data to deliver), or if /// an error was encountered. /// /// - contentContext: Content context describing the received content. This includes protocol metadata /// that lets the caller introspect information about the received content (such as flags on a packet). /// /// - isComplete: An indication that this context (a message or stream, for example) is now complete. For /// protocols such as TCP, this will be marked when the entire stream has be closed in the /// reading direction. For protocols such as UDP, this will be marked when the end of a /// datagram has been reached. /// /// - error: An error will be sent if the receive was terminated before completing. There may still /// be content delivered along with the error, but this content may be shorter than the requested /// ranges. An error will be sent for any outstanding receives when the connection is cancelled. public func receive(minimumIncompleteLength: Int, maximumLength: Int, completion: @escaping (_ content: Data?, _ contentContext: NWConnection.ContentContext?, _ isComplete: Bool, _ error: NWError?) -> Void) { nw_connection_receive(self.nw, UInt32(minimumIncompleteLength), UInt32(maximumLength)) { (content, context, complete, nwError) in completion(NWCreateNSDataFromDispatchData(content) as Data?, ContentContext(context), complete, NWError(nwError)); } } /// Receive complete message content from the connection, waiting for the content to be marked complete /// (or encounter an error) before delivering the callback. This is useful for datagram or message-based /// protocols like UDP. See receive(minimumIncompleteLength:, maximumLength:, completion:) for a description /// of the completion handler. public func receiveMessage(completion: @escaping (_ completeContent: Data?, _ contentContext: NWConnection.ContentContext?, _ isComplete: Bool, _ error: NWError?) -> Void) { nw_connection_receive_message(self.nw) { (content, context, complete, nwError) in completion(NWCreateNSDataFromDispatchData(content) as Data?, ContentContext(context), complete, NWError(nwError)) } } /// A type representing a wrapped completion handler invoked when send content has been consumed by the protocol stack, or the lack of a completion handler because the content is idempotent. public enum SendCompletion { /// Completion handler to be invoked when send content has been successfully processed, or failed to send due to an error. /// Note that this does not guarantee that the data was sent out over the network, or acknowledge, but only that /// it has been consumed by the protocol stack. case contentProcessed((_ error: NWError?) -> Void) /// Idempotent content may be sent multiple times when opening up a 0-RTT connection, so there is no completion block case idempotent } /// Send data on a connection. This may be called before the connection is ready, /// in which case the send will be enqueued until the connection is ready to send. /// This is an asynchronous send and the completion block can be used to /// determine when the send is complete. There is nothing preventing a client /// from issuing an excessive number of outstanding sends. To minimize memory /// footprint and excessive latency as a consequence of buffer bloat, it is /// advisable to keep a low number of outstanding sends. The completion block /// can be used to pace subsequent sends. /// - Parameter content: The data to send on the connection. May be nil if this send marks its context as complete, such /// as by sending .finalMessage as the context and marking isComplete to send a write-close. /// - Parameter contentContext: The context associated with the content, which represents a logical message /// to be sent on the connection. All content sent within a single context will /// be sent as an in-order unit, up until the point that the context is marked /// complete (see isComplete). Once a context is marked complete, it may be re-used /// as a new logical message. Protocols like TCP that cannot send multiple /// independent messages at once (serial streams) will only start processing a new /// context once the prior context has been marked complete. Defaults to .defaultMessage. /// - Parameter isComplete: A flag indicating if the caller's sending context (logical message) is now complete. /// Until a context is marked complete, content sent for other contexts may not /// be sent immediately (if the protocol requires sending bytes serially, like TCP). /// For datagram protocols, like UDP, isComplete indicates that the content represents /// a complete datagram. /// When sending using streaming protocols like TCP, isComplete can be used to mark the end /// of a single message on the stream, of which there may be many. However, it can also /// indicate that the connection should send a "write close" (a TCP FIN) if the sending /// context is the final context on the connection. Specifically, to send a "write close", /// pass .finalMessage or .defaultStream for the context (or create a custom context and /// set .isFinal), and pass true for isComplete. /// - Parameter completion: A completion handler (.contentProcessed) to notify the caller when content has been processed by /// the connection, or a marker that this data is idempotent (.idempotent) and may be sent multiple times as fast open data. public func send(content: Data?, contentContext: NWConnection.ContentContext = .defaultMessage, isComplete: Bool = true, completion: SendCompletion) { switch completion { case .idempotent: _swift_nw_connection_send_idempotent(self.nw, NWCreateDispatchDataFromNSData(content), contentContext.nw, isComplete) case .contentProcessed(let handler): _swift_nw_connection_send(self.nw, NWCreateDispatchDataFromNSData(content), contentContext.nw, isComplete) { (error) in handler(NWError(error)) } } } /// Batching allows multiple send or receive calls provides a hint to the connection that the operations /// should be coalesced to improve efficiency. Calls other than send and receive will not be affected. public func batch(_ block: () -> Void) { nw_connection_batch(self.nw, block) } /// Access connection-wide protocol metadata on the connection. This allows access to state for protocols /// like TCP and TLS that have long-term state. public func metadata(definition: NWProtocolDefinition) -> NWProtocolMetadata? { if let metadata = nw_connection_copy_protocol_metadata(self.nw, definition.nw) { if nw_protocol_metadata_is_tcp(metadata) { return NWProtocolTCP.Metadata(metadata) } else if nw_protocol_metadata_is_udp(metadata) { return NWProtocolUDP.Metadata(metadata) } else if nw_protocol_metadata_is_ip(metadata) { return NWProtocolIP.Metadata(metadata) } else if nw_protocol_metadata_is_tls(metadata) { return NWProtocolTLS.Metadata(metadata) } return NWProtocolMetadata(metadata) } else { return nil } } }
apache-2.0
7c9aa649c0b6e309d74e082afab1a9e4
45.612565
192
0.720207
4.107813
false
false
false
false
Intercambio/CloudUI
CloudUI/CloudUI/AccountListViewController.swift
1
2050
// // AccountListViewController.swift // CloudUI // // Created by Tobias Kraentzer on 24.01.17. // Copyright © 2017 Tobias Kräntzer. All rights reserved. // import UIKit import Fountain class AccountListViewController: UITableViewController, AccountListView { let presenter: AccountListPresenter init(presenter: AccountListPresenter) { self.presenter = presenter super.init(style: .plain) self.presenter.view = self } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } var dataSource: FTDataSource? private var tableViewAdapter: FTTableViewAdapter? public override func viewDidLoad() { super.viewDidLoad() tableViewAdapter = FTTableViewAdapter(tableView: tableView) tableView.register(AccountListCell.self, forCellReuseIdentifier: "AccountListCell") tableViewAdapter?.forRowsMatching(nil, useCellWithReuseIdentifier: "AccountListCell") { view, item, _, _ in if let cell = view as? AccountListCell, let account = item as? AccountListViewModel { cell.textLabel?.text = account.title cell.detailTextLabel?.text = account.subtitle cell.accessoryType = .detailDisclosureButton } } tableViewAdapter?.delegate = self tableViewAdapter?.dataSource = dataSource navigationItem.title = "Accounts" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAccount)) } override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) { presenter.didSelect(itemAt: indexPath) } override func tableView(_: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { presenter.didTapAccessoryButton(forItemAt: indexPath) } @objc private func addAccount() { presenter.addAccount() } }
gpl-3.0
86810840820c433adc9ff6197b10bcfc
32.032258
131
0.661621
5.319481
false
false
false
false
HarrisLee/SwiftBook
SmartHomeI/Pods/FillableLoaders/Source/FillableLoader.swift
3
11793
// // FillableLoader.swift // PQFFillableLoaders // // Created by Pol Quintana on 25/7/15. // Copyright (c) 2015 Pol Quintana. All rights reserved. // import UIKit open class FillableLoader: UIView, CAAnimationDelegate { internal var shapeLayer = CAShapeLayer() internal var strokeLayer = CAShapeLayer() internal var path: CGPath! internal var loaderView = UIView() internal var animate: Bool = false internal var extraHeight: CGFloat = 0 internal var oldYPoint: CGFloat = 0 internal let mainBgColor = UIColor(white: 0.2, alpha: 0.6) internal weak var loaderSuperview: UIView? // MARK: Public Variables /// Duration of the animation (Default: 10.0) open var duration: TimeInterval = 10.0 /// Loader background height (Default: ScreenHeight/6 + 30) open var rectSize: CGFloat = UIScreen.main.bounds.height/6 + 30 /// A Boolean value that determines whether the loader should have a swing effect while going up (Default: true) open var swing: Bool = true /// A Boolean value that determines whether the loader movement is progress based or not (Default: false) open var progressBased: Bool = false // MARK: Custom Getters and Setters internal var _backgroundColor: UIColor? internal var _loaderColor: UIColor? internal var _loaderBackgroundColor: UIColor? internal var _loaderStrokeColor: UIColor? internal var _loaderStrokeWidth: CGFloat = 0.5 internal var _loaderAlpha: CGFloat = 1.0 internal var _cornerRadius: CGFloat = 0.0 internal var _progress: CGFloat = 0.0 /// Loader view background color (Default: Clear) override open var backgroundColor: UIColor? { get { return _backgroundColor } set { super.backgroundColor = mainBgColor _backgroundColor = newValue loaderView.backgroundColor = newValue loaderView.layer.backgroundColor = newValue?.cgColor } } /// Filled loader color (Default: Blue) open var loaderColor: UIColor? { get { return _loaderColor } set { _loaderColor = newValue shapeLayer.fillColor = newValue?.cgColor } } /// Unfilled loader color (Default: White) open var loaderBackgroundColor: UIColor? { get { return _loaderBackgroundColor } set { _loaderBackgroundColor = newValue strokeLayer.fillColor = newValue?.cgColor } } /// Loader outline line color (Default: Black) open var loaderStrokeColor: UIColor? { get { return _loaderStrokeColor } set { _loaderStrokeColor = newValue strokeLayer.strokeColor = newValue?.cgColor } } /// Loader outline line width (Default: 0.5) open var loaderStrokeWidth: CGFloat { get { return _loaderStrokeWidth } set { _loaderStrokeWidth = newValue strokeLayer.lineWidth = newValue } } /// Loader view alpha (Default: 1.0) open var loaderAlpha: CGFloat { get { return _loaderAlpha } set { _loaderAlpha = newValue loaderView.alpha = newValue } } /// Loader view corner radius (Default: 0.0) open var cornerRadius: CGFloat { get { return _cornerRadius } set { _cornerRadius = newValue loaderView.layer.cornerRadius = newValue } } /// Loader fill progress from 0.0 to 1.0 . It will automatically fire an animation to update the loader fill progress (Default: 0.0) open var progress: CGFloat { get { return _progress } set { if (!progressBased || newValue > 1.0 || newValue < 0.0) { return } _progress = newValue applyProgress() } } // MARK: Initializers Methods /** Creates and SHOWS a loader with the given path :param: path Loader CGPath :returns: The loader that's already being showed */ open static func showLoader(with path: CGPath, on view: UIView? = nil) -> Self { let loader = createLoader(with: path, on: view) loader.showLoader() return loader } /** Creates and SHOWS a progress based loader with the given path :param: path Loader CGPath :returns: The loader that's already being showed */ open static func showProgressBasedLoader(with path: CGPath, on view: UIView? = nil) -> Self { let loader = createProgressBasedLoader(with: path, on: view) loader.showLoader() return loader } /** Creates a loader with the given path :param: path Loader CGPath :returns: The created loader */ open static func createLoader(with path: CGPath, on view: UIView? = nil) -> Self { let loader = self.init() loader.initialSetup(on: view) loader.add(path) return loader } /** Creates a progress based loader with the given path :param: path Loader CGPath :returns: The created loader */ open static func createProgressBasedLoader(with path: CGPath, on view: UIView? = nil) -> Self { let loader = self.init() loader.progressBased = true loader.initialSetup(on: view) loader.add(path) return loader } internal func initialSetup(on view: UIView? = nil) { //Setting up frame var window = view if view == nil, let mainWindow = UIApplication.shared.delegate?.window { window = mainWindow } guard let w = window else { return } self.frame = w.frame self.center = CGPoint(x: w.bounds.midX, y: w.bounds.midY) w.addSubview(self) loaderSuperview = w //Initial Values defaultValues() //Setting up loaderView loaderView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: rectSize) loaderView.center = CGPoint(x: frame.width/2, y: frame.height/2) loaderView.layer.cornerRadius = cornerRadius //Add loader to its superview self.addSubview(loaderView) //Initially hidden isHidden = true } internal func add(_ path: CGPath) { let bounds = path.boundingBox let center = bounds.origin let height = bounds.height let width = bounds.width assert(height <= loaderView.frame.height, "The height(\(height)) of the path has to fit the dimensions (Height: \(loaderView.frame.height) Width: \(frame.width))") assert(width <= loaderView.frame.width, "The width(\(width)) of the path has to fit the dimensions (Height: \(loaderView.frame.width) Width: \(frame.width))") var transformation = CGAffineTransform(translationX: -center.x - width/2 + loaderView.frame.width/2, y: -center.y - height/2 + loaderView.frame.height/2) self.path = path.copy(using: &transformation)! } // MARK: Prepare Loader /** Shows the loader. Atention: do not use this method after creating a loader with `showLoaderWithPath(path:)` */ open func showLoader() { alpha = 1.0 isHidden = false animate = true generateLoader() startAnimating() if superview == nil { loaderSuperview?.addSubview(self) } } /** Stops loader animations and removes it from its superview */ open func removeLoader(_ animated: Bool = true) { let completion: () -> () = { self.isHidden = false self.animate = false self.removeFromSuperview() self.layer.removeAllAnimations() self.shapeLayer.removeAllAnimations() } guard animated else { completion() return } UIView.animateKeyframes(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { self.alpha = 0.0 }) { _ in completion() } } internal func layoutPath() { let maskingLayer = CAShapeLayer() maskingLayer.frame = loaderView.bounds maskingLayer.path = path strokeLayer = CAShapeLayer() strokeLayer.frame = loaderView.bounds strokeLayer.path = path strokeLayer.strokeColor = loaderStrokeColor?.cgColor strokeLayer.lineWidth = loaderStrokeWidth strokeLayer.fillColor = loaderBackgroundColor?.cgColor loaderView.layer.addSublayer(strokeLayer) let baseLayer = CAShapeLayer() baseLayer.frame = loaderView.bounds baseLayer.mask = maskingLayer shapeLayer.fillColor = loaderColor?.cgColor shapeLayer.lineWidth = 0.2 shapeLayer.strokeColor = UIColor.black.cgColor shapeLayer.frame = loaderView.bounds oldYPoint = rectSize + extraHeight shapeLayer.position = CGPoint(x: shapeLayer.position.x, y: oldYPoint) loaderView.layer.addSublayer(baseLayer) baseLayer.addSublayer(shapeLayer) } internal func defaultValues() { duration = 10.0 backgroundColor = UIColor.clear loaderColor = UIColor(red: 0.41, green: 0.728, blue: 0.892, alpha: 1.0) loaderBackgroundColor = UIColor.white loaderStrokeColor = UIColor.black loaderStrokeWidth = 0.5 loaderAlpha = 1.0 cornerRadius = 0.0 } //MARK: Animations internal func startMoving(up: Bool) { if (progressBased) { return } let key = up ? "up" : "down" let moveAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position.y") moveAnimation.values = up ? [loaderView.frame.height/2 + rectSize/2, loaderView.frame.height/2 - rectSize/2 - extraHeight] : [loaderView.frame.height/2 - rectSize/2 - extraHeight, loaderView.frame.height/2 + rectSize/2] moveAnimation.duration = duration moveAnimation.isRemovedOnCompletion = false moveAnimation.fillMode = kCAFillModeForwards moveAnimation.delegate = self moveAnimation.setValue(key, forKey: "animation") shapeLayer.add(moveAnimation, forKey: key) } internal func applyProgress() { let yPoint = (rectSize + extraHeight)*(1-progress) let progressAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position.y") progressAnimation.values = [oldYPoint, yPoint] progressAnimation.duration = 0.2 progressAnimation.isRemovedOnCompletion = false progressAnimation.fillMode = kCAFillModeForwards shapeLayer.add(progressAnimation, forKey: "progress") oldYPoint = yPoint } internal func startswinging() { let swingAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") swingAnimation.values = [0, randomAngle(), -randomAngle(), randomAngle(), -randomAngle(), randomAngle(), 0] swingAnimation.duration = 12.0 swingAnimation.isRemovedOnCompletion = false swingAnimation.fillMode = kCAFillModeForwards swingAnimation.delegate = self swingAnimation.setValue("rotation", forKey: "animation") shapeLayer.add(swingAnimation, forKey: "rotation") } internal func randomAngle() -> Double { return M_PI_4/(Double(arc4random_uniform(16)) + 8) } //MARK: Abstract methods internal func generateLoader() { preconditionFailure("Call this method from the desired FillableLoader type class") } internal func startAnimating() { preconditionFailure("Call this method from the desired FillableLoader type class") } }
mit
c0bec850a8e9c9a6b636ad74825c043d
32.126404
227
0.62978
4.823313
false
false
false
false
apple/swift-format
Sources/SwiftFormat/Parsing.swift
1
2443
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation import SwiftDiagnostics import SwiftFormatCore import SwiftOperators import SwiftParser import SwiftParserDiagnostics import SwiftSyntax /// Parses the given source code and returns a valid `SourceFileSyntax` node. /// /// This helper function automatically folds sequence expressions using the given operator table, /// ignoring errors so that formatting can do something reasonable in the presence of unrecognized /// operators. /// /// - Parameters: /// - source: The Swift source code to be formatted. /// - url: A file URL denoting the filename/path that should be assumed for this syntax tree, /// which is associated with any diagnostics emitted during formatting. If this is nil, a /// dummy value will be used. /// - operatorTable: The operator table to use for sequence folding. /// - parsingDiagnosticHandler: An optional callback that will be notified if there are any /// errors when parsing the source code. /// - Throws: If an unrecoverable error occurs when formatting the code. func parseAndEmitDiagnostics( source: String, operatorTable: OperatorTable, assumingFileURL url: URL?, parsingDiagnosticHandler: ((Diagnostic, SourceLocation) -> Void)? = nil ) throws -> SourceFileSyntax { let sourceFile = operatorTable.foldAll(Parser.parse(source: source)) { _ in }.as(SourceFileSyntax.self)! let diagnostics = ParseDiagnosticsGenerator.diagnostics(for: sourceFile) if let parsingDiagnosticHandler = parsingDiagnosticHandler { let expectedConverter = SourceLocationConverter(file: url?.path ?? "<unknown>", tree: sourceFile) for diagnostic in diagnostics { let location = diagnostic.location(converter: expectedConverter) parsingDiagnosticHandler(diagnostic, location) } } guard diagnostics.isEmpty else { throw SwiftFormatError.fileContainsInvalidSyntax } return restoringLegacyTriviaBehavior(sourceFile) }
apache-2.0
29518e51bd373b0441d1c3cf863da7be
39.716667
98
0.708146
4.97556
false
false
false
false
kolyvan/kybookfmt
KyBookFmtKit/fb2kybook/fb2utils.swift
1
3488
// // fb2utils.swift // https://github.com/kolyvan/kybookfmt // // Created by Konstantin Bukreev on 09.02.16. // Copyright © 2016 Konstantin Bukreev. All rights reserved. // /* Copyright (c) 2016 Konstantin Bukreev 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. 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 Foundation struct FB2Utils { static let whitespacesCharacterSet : NSCharacterSet = { let charset = NSMutableCharacterSet.whitespaceAndNewlineCharacterSet() charset.removeCharactersInRange(NSRange(location:0xa0, length:1)) // No-Break Space return charset.copy() as! NSCharacterSet }() static func trimWhitespaces(text: String) -> String { if text.isEmpty { return text } let newlines = NSCharacterSet.newlineCharacterSet() let whites = self.whitespacesCharacterSet var needTrim = false let scanner = NSScanner(string: text) scanner.charactersToBeSkipped = nil scanner.scanUpToCharactersFromSet(newlines, intoString:nil) if scanner.scanCharactersFromSet(newlines, intoString:nil) { needTrim = true; } else { scanner.scanLocation = 0 var scanLocation = 0 while !scanner.atEnd { if scanner.scanCharactersFromSet(whites, intoString:nil) { if (scanner.scanLocation - scanLocation) > 1 { needTrim = true break } } if scanner.scanUpToCharactersFromSet(whites, intoString:nil) { scanLocation = scanner.scanLocation } } } if !needTrim { return text; } var buffer = "" scanner.scanLocation = 0 while !scanner.atEnd { if scanner.scanCharactersFromSet(whites, intoString:nil) { buffer += " " } if let s = scanner.scanUpToCharactersFromSet(whites) { buffer += s } } return buffer } }
bsd-2-clause
e844b939277d25a47c80361128fee9a9
32.528846
91
0.62604
5.406202
false
false
false
false
huonw/swift
validation-test/compiler_crashers_fixed/00183-swift-inflightdiagnostic-fixitreplacechars.swift
65
1903
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck import Foundation class m<j>: NSObject { var h: j g -> k = l $n } b f: _ = j() { } } func k<g { enum k { func l var _ = l func i(c: () -> ()) { } class a { var _ = i() { } } func C<D, E: A where D.C == E> { } func prefix(with: String) -> <T>(() -> T) -> String { { g in "\(withing } clasnintln(some(xs)) func a<T>() -> (T, T -> T) -> T { var b: ((T, T -> T) -> T)! return b } } class p { u _ = q() { } } u l = r u s: k -> k = { n $h: m.j) { } } o l() { ({}) } struct m<t> { let p: [(t, () -> ())] = [] } protocol p : p { } protocol m { o u() -> String } class j { o m() -> String { n "" } } class h: j, m { q o m() -> String { n "" } o u() -> S, q> ) -> d) import Foundation class k<f>: NSObject { d e: f g(e: f) { j h.g() } } d protocol i : d { func d i var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) } class i { func d((h: (Any, AnyObject)) { d(h) } } d h) func d<i>() -> (i, i -> i) -> i { i j i.f = { } protocol d { class func f() } class i: d{ class func f {} func f() { ({}) } func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c k) func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protocol c { class func i() } class k: c{ class func i { class c { func b((Any, c))( typealias g = a<d<i>i) { } let d = a d() a=d g a=d protocol a : a { } class a { typealias b = b
apache-2.0
f2e848c42e22cdfc365d1282d55ee6e0
14.346774
79
0.468734
2.557796
false
false
false
false
ScottRobbins/RxCocoaTouch
Pod/Classes/UITextField+Rx.swift
1
5775
import RxSwift extension UITextField { // MARK: - Accessing the Text Attributes public var rx_attributedText: ObserverOf<NSAttributedString?> { return observerOfWithPropertySetter { [weak self] (attributedText: NSAttributedString?) in self?.attributedText = attributedText } } public var rx_placeholder: ObserverOf<String?> { return observerOfWithPropertySetter { [weak self] (placeholder: String?) in self?.placeholder = placeholder } } public var rx_attributedPlaceholder: ObserverOf<NSAttributedString?> { return observerOfWithPropertySetter { [weak self] (attributedPlaceholder: NSAttributedString?) in self?.attributedPlaceholder = attributedPlaceholder } } public var rx_defaultTextAttributes: ObserverOf<[String : AnyObject]> { return observerOfWithPropertySetter { [weak self] (defaultTextAttributes: [String : AnyObject]) in self?.defaultTextAttributes = defaultTextAttributes } } public var rx_font: ObserverOf<UIFont?> { return observerOfWithPropertySetter { [weak self] (font: UIFont?) in self?.font = font } } public var rx_textColor: ObserverOf<UIColor> { return observerOfWithPropertySetter { [weak self] (textColor: UIColor) in self?.textColor = textColor } } public var rx_textAlignment: ObserverOf<NSTextAlignment> { return observerOfWithPropertySetter { [weak self] (textAlignment: NSTextAlignment) in self?.textAlignment = textAlignment } } public var rx_typingAttributes: ObserverOf<[String : AnyObject]?> { return observerOfWithPropertySetter { [weak self] (typingAttributes: [String : AnyObject]?) in self?.typingAttributes = typingAttributes } } // MARK: - Sizing the Text Field's Text public var rx_adjustsFontSizeToFitWidth: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (adjustsFontSizeToFitWidth: Bool) in self?.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth } } public var rx_minimumFontSize: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (minimumFontSize: CGFloat) in self?.minimumFontSize = minimumFontSize } } // MARK: - Managing the Editing Behavior public var rx_clearsOnBeginEditing: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (clearsOnBeginEditing: Bool) in self?.clearsOnBeginEditing = clearsOnBeginEditing } } public var rx_clearsOnInsertion: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (clearsOnInsertion: Bool) in self?.clearsOnInsertion = clearsOnInsertion } } public var rx_allowsEditingTextAttributes: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (allowsEditingTextAttributes: Bool) in self?.allowsEditingTextAttributes = allowsEditingTextAttributes } } // MARK: - Setting the View's Background Appearance public var rx_borderStyle: ObserverOf<UITextBorderStyle> { return observerOfWithPropertySetter { [weak self] (borderStyle: UITextBorderStyle) in self?.borderStyle = borderStyle } } public var rx_background: ObserverOf<UIImage?> { return observerOfWithPropertySetter { [weak self] (background: UIImage?) in self?.background = background } } public var rx_disabledBackground: ObserverOf<UIImage?> { return observerOfWithPropertySetter { [weak self] (disabledBackground: UIImage?) in self?.disabledBackground = disabledBackground } } // MARK: - Managing Overlay Views public var rx_clearButtonMode: ObserverOf<UITextFieldViewMode> { return observerOfWithPropertySetter { [weak self] (clearButtonMode: UITextFieldViewMode) in self?.clearButtonMode = clearButtonMode } } public var rx_leftView: ObserverOf<UIView?> { return observerOfWithPropertySetter { [weak self] (leftView: UIView?) in self?.leftView = leftView } } public var rx_leftViewMode: ObserverOf<UITextFieldViewMode> { return observerOfWithPropertySetter { [weak self] (leftViewMode: UITextFieldViewMode) in self?.leftViewMode = leftViewMode } } public var rx_rightView: ObserverOf<UIView?> { return observerOfWithPropertySetter { [weak self] (rightView: UIView?) in self?.rightView = rightView } } public var rx_rightViewMode: ObserverOf<UITextFieldViewMode> { return observerOfWithPropertySetter { [weak self] (rightViewMode: UITextFieldViewMode) in self?.rightViewMode = rightViewMode } } // MARK: - Accessing the Delegate public var rx_delegate: ObserverOf<UITextFieldDelegate?> { return observerOfWithPropertySetter { [weak self] (delegate: UITextFieldDelegate?) in self?.delegate = delegate } } // MARK: - Replacing the System Input Views public var rx_inputView: ObserverOf<UIView?> { return observerOfWithPropertySetter { [weak self] (inputView: UIView?) in self?.inputView = inputView } } public var rx_inputAccessoryView: ObserverOf<UIView?> { return observerOfWithPropertySetter { [weak self] (inputAccessoryView: UIView?) in self?.inputAccessoryView = inputAccessoryView } } }
mit
639596d49e4beeb19ea0a0fd0ee3c251
34.654321
106
0.654372
5.510496
false
false
false
false
VirgilSecurity/virgil-sdk-pfs-x
Source/Client/EphemeralCardValidator.swift
1
1509
// // EphemeralCardValidator.swift // VirgilSDKPFS // // Created by Oleksandr Deundiak on 6/15/17. // Copyright © 2017 VirgilSecurity. All rights reserved. // import Foundation import VirgilSDK class EphemeralCardValidator { let crypto: VSSCryptoProtocol private var verifiers: [String: VSSPublicKey] = [:] init(crypto: VSSCryptoProtocol) { self.crypto = crypto } func addVerifier(withId verifierId: String, publicKeyData: Data) throws { guard let publicKey = self.crypto.importPublicKey(from: publicKeyData) else { throw SecureChat.makeError(withCode: .importingVerifier, description: "Error importing verifier public key.") } self.verifiers[verifierId] = publicKey } func validate(cardResponse: VSSCardResponse) -> Bool { let fingerprint = self.crypto.calculateFingerprint(for: cardResponse.snapshot) let cardId = fingerprint.hexValue guard cardId == cardResponse.identifier else { return false } for verifier in self.verifiers { guard let signature = cardResponse.signatures[verifier.key], signature.count > 0 else { return false } do { try self.crypto.verify(fingerprint.value, withSignature: signature, using: verifier.value) } catch { return false } } return true } }
bsd-3-clause
9d2b2b6377025115f9fc65aa2688c90a
28.568627
121
0.610743
4.864516
false
false
false
false
Alloc-Studio/Hypnos
Hypnos/Hypnos/Service/HttpTool.swift
1
1037
// // HttpTool.swift // Hypnos // // Created by Fay on 16/5/19. // Copyright © 2016年 DMT312. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class HttpTool: NSObject { class func getDataList(url:String,parameters:[String:AnyObject]?=nil,failCallback:(NSError)->Void,successCallback:(JSON)->Void) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true Alamofire.request(.GET, url, parameters: parameters).responseData { (response) in if let returnStr = response.result.value { let range = NSRange(location: 27, length: (response.result.value?.length)! - 29) let data = returnStr.subdataWithRange(range) let json = JSON(data: data) successCallback(json) }else if let error = response.result.error { failCallback(error) } UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } }
mit
ac245859313377d8cbee752d11ecea20
29.411765
133
0.630561
4.7
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Models/TypeSpec.swift
1
10455
import Quick import Nimble @testable import Sourcery @testable import SourceryRuntime class TypeSpec: QuickSpec { override func spec() { describe ("Type") { var sut: Type? let staticVariable = Variable(name: "staticVar", typeName: TypeName("Int"), isStatic: true) let computedVariable = Variable(name: "variable", typeName: TypeName("Int"), isComputed: true) let storedVariable = Variable(name: "otherVariable", typeName: TypeName("Int"), isComputed: false) let supertypeVariable = Variable(name: "supertypeVariable", typeName: TypeName("Int"), isComputed: true) let superTypeMethod = Method(name: "doSomething()", definedInTypeName: TypeName("Protocol")) let overrideMethod = superTypeMethod let overrideVariable = supertypeVariable let initializer = Method(name: "init()", definedInTypeName: TypeName("Foo")) let parentType = Type(name: "Parent") let protocolType = Type(name: "Protocol", variables: [Variable(name: "supertypeVariable", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none))], methods: [superTypeMethod]) let superType = Type(name: "Supertype", variables: [supertypeVariable], methods: [superTypeMethod], inheritedTypes: ["Protocol"]) superType.implements["Protocol"] = protocolType beforeEach { sut = Type(name: "Foo", parent: parentType, variables: [storedVariable, computedVariable, staticVariable, overrideVariable], methods: [initializer, overrideMethod], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]) sut?.supertype = superType } afterEach { sut = nil } it("being not an extension reports kind as unknown") { expect(sut?.kind).to(equal("unknown")) } it("being an extension reports kind as extension") { expect((Type(name: "Foo", isExtension: true)).kind).to(equal("extension")) } it("resolves name") { expect(sut?.name).to(equal("Parent.Foo")) } it("has local name") { expect(sut?.localName).to(equal("Foo")) } it("filters static variables") { expect(sut?.staticVariables).to(equal([staticVariable])) } it("filters computed variables") { expect(sut?.computedVariables).to(equal([computedVariable, overrideVariable])) } it("filters stored variables") { expect(sut?.storedVariables).to(equal([storedVariable])) } it("filters instance variables") { expect(sut?.instanceVariables).to(equal([storedVariable, computedVariable, overrideVariable])) } it("filters initializers") { expect(sut?.initializers).to(equal([initializer])) } it("flattens methods from supertype") { expect(sut?.allMethods).to(equal([initializer, overrideMethod])) } it("flattens variables from supertype") { expect(sut?.allVariables).to(equal([storedVariable, computedVariable, staticVariable, overrideVariable])) expect(superType.allVariables).to(equal([supertypeVariable])) } describe("isGeneric") { context("given generic type") { it("recognizes correctly for simple generic") { let sut = Type(name: "Foo", isGeneric: true) expect(sut.isGeneric).to(beTrue()) } } context("given non-generic type") { it("recognizes correctly for simple type") { let sut = Type(name: "Foo") expect(sut.isGeneric).to(beFalse()) } } } describe("when setting containedTypes") { it("sets their parent to self") { let type = Type(name: "Bar", isExtension: false) sut?.containedTypes = [type] expect(type.parent).to(beIdenticalTo(sut)) } } describe("when extending with Type extension") { it("adds variables") { let extraVariable = Variable(name: "variable", typeName: TypeName("Int")) let type = Type(name: "Foo", isExtension: true, variables: [extraVariable]) sut?.extend(type) expect(sut?.variables).to(equal([storedVariable, computedVariable, staticVariable, overrideVariable, extraVariable])) } it("does not duplicate variables with protocol extension") { let aExtension = Type(name: "Foo", isExtension: true, variables: [Variable(name: "variable", typeName: TypeName("Int"), isComputed: true)]) let aProtocol = Protocol(name: "Foo", variables: [Variable(name: "variable", typeName: TypeName("Int"))]) aProtocol.extend(aExtension) expect(aProtocol.variables).to(equal([Variable(name: "variable", typeName: TypeName("Int"))])) } it("adds methods") { let extraMethod = Method(name: "foo()", definedInTypeName: TypeName("Foo")) let type = Type(name: "Foo", isExtension: true, methods: [extraMethod]) sut?.extend(type) expect(sut?.methods).to(equal([initializer, overrideMethod, extraMethod])) } it("does not duplicate methods with protocol extension") { let aExtension = Type(name: "Foo", isExtension: true, methods: [Method(name: "foo()", definedInTypeName: TypeName("Foo"))]) let aProtocol = Protocol(name: "Foo", methods: [Method(name: "foo()", definedInTypeName: TypeName("Foo"))]) aProtocol.extend(aExtension) expect(aProtocol.methods).to(equal([Method(name: "foo()", definedInTypeName: TypeName("Foo"))])) } it("adds annotations") { let expected: [String: NSObject] = ["something": NSNumber(value: 161), "ExtraAnnotation": "ExtraValue" as NSString] let type = Type(name: "Foo", isExtension: true, annotations: ["ExtraAnnotation": "ExtraValue" as NSString]) sut?.extend(type) guard let annotations = sut?.annotations else { return fail() } expect(annotations == expected).to(beTrue()) } it("adds inherited types") { let type = Type(name: "Foo", isExtension: true, inheritedTypes: ["Something", "New"]) sut?.extend(type) expect(sut?.inheritedTypes).to(equal(["NSObject", "Something", "New"])) expect(sut?.based).to(equal(["NSObject": "NSObject", "Something": "Something", "New": "New"])) } it("adds implemented types") { let type = Type(name: "Foo", isExtension: true) type.implements = ["New": Protocol(name: "New")] sut?.extend(type) expect(sut?.implements).to(equal(["New": Protocol(name: "New")])) } } describe("When testing equality") { context("given same items") { it("is equal") { expect(sut).to(equal(Type(name: "Foo", parent: parentType, accessLevel: .internal, isExtension: false, variables: [storedVariable, computedVariable, staticVariable, overrideVariable], methods: [initializer, overrideMethod], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]))) } } context("given different items") { it("is not equal") { expect(sut).toNot(equal(Type(name: "Bar", parent: parentType, accessLevel: .internal, isExtension: false, variables: [storedVariable, computedVariable], methods: [initializer], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]))) expect(sut).toNot(equal(Type(name: "Foo", parent: parentType, accessLevel: .public, isExtension: false, variables: [storedVariable, computedVariable], methods: [initializer], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]))) expect(sut).toNot(equal(Type(name: "Foo", parent: parentType, accessLevel: .internal, isExtension: true, variables: [storedVariable, computedVariable], methods: [initializer], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]))) expect(sut).toNot(equal(Type(name: "Foo", parent: parentType, accessLevel: .internal, isExtension: false, variables: [computedVariable], methods: [initializer], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]))) expect(sut).toNot(equal(Type(name: "Foo", parent: parentType, accessLevel: .internal, isExtension: false, variables: [storedVariable, computedVariable], methods: [initializer], inheritedTypes: [], annotations: ["something": NSNumber(value: 161)]))) expect(sut).toNot(equal(Type(name: "Foo", parent: nil, accessLevel: .internal, isExtension: false, variables: [storedVariable, computedVariable], methods: [initializer], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]))) expect(sut).toNot(equal(Type(name: "Foo", parent: parentType, accessLevel: .internal, isExtension: false, variables: [storedVariable, computedVariable], methods: [initializer], inheritedTypes: ["NSObject"], annotations: [:]))) expect(sut).toNot(equal(Type(name: "Foo", parent: parentType, accessLevel: .internal, isExtension: false, variables: [storedVariable, computedVariable], methods: [], inheritedTypes: ["NSObject"], annotations: ["something": NSNumber(value: 161)]))) } } } } } }
mit
e93a74ab90c1b1dd01dd959e8365a013
53.170984
329
0.572358
4.971469
false
false
false
false
MartinOSix/DemoKit
dSwift/SwiftSyntaxDemo/SwiftSyntaxDemo/ViewController_controlFlow.swift
1
3856
// // ViewController_controlFlow.swift // SwiftSyntaxDemo // // Created by runo on 16/12/26. // Copyright © 2016年 com.runo. All rights reserved. // import UIKit class ViewController_controlFlow: UIViewController { override func viewDidLoad() { super.viewDidLoad() //self.funType_For() self.funcType_While() self.funcType_if() self.funcType_Switch() // Do any additional setup after loading the view. var name : String? = nil; name = "name" guard name != nil else { print("name is nil") return; } print("\(name) is not nil") if let name1 = name{ print("\(name1) is not nil") } } func funType_For() { for index in 1...5 { print("index = \(index)") } for _ in 1...5 { print("lalal ") } let names = ["alex","alen","haha"] for name in names { print(name) } let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] for (animalName, legCount) in numberOfLegs { print("\(animalName)s have \(legCount) legs") } //直接遍历字符串 for character in "Hello".characters { print(character) } let charArr = Array("Hello".characters) print(charArr) // swift 3 完全移除了这种语法 // for var indexx = 0; indexx < 5; indexx++ { // print(indexx) // } } func funcType_While() { var condition = 10 while condition > 0 { print(condition) condition -= 1 } repeat{ print(condition) condition += 1 } while condition < 10 } func funcType_if() { var temperature = 30 if temperature > 32 { print("temperature High") }else{ print("temperature low") } temperature += 20 if temperature > 30 { print("Hight") }else if temperature > 20{ print("Middle") }else{ print("Low") } } func funcType_Switch() { //匹配字符 let char = "e" switch char { case "a","b","c","d","e" : print("5") default: print("NO") } //匹配范围 let i = 5 switch 1 { case 1...5: print("1...5") default: print("other") } //元祖匹配 let tup = (1,1) switch tup { case (0,0): print("nothing") case (1,_): print("1,x") fallthrough case (_,1): print("x,1") default: print("hhhh") } //值绑定 let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): print("on the x-axis with an x value of \(x)") case (0, let y): print("on the y-axis with a y value of \(y)") case let (x, y): print("somewhere else at (\(x), \(y))") } //进一步判断 let point = (1,4) switch point { case (1,let y) where y > 5: print("x = 1 , y > 5") case (1, let y) where y < 5: print("x = 1 , y < 5") default: print("other") } //continue 终止当次循环 //break 跳出当前循环 //return 跳出方法 } }
apache-2.0
53c8de38e8e81522b7765d495cdcc80e
19.712707
60
0.404374
4.38993
false
false
false
false
RobotsAndPencils/Scythe
Dependencies/HarvestKit-Swift/HarvestKit-Shared/ContactsController.swift
1
10049
// // ContactsController.swift // HarvestKit // // Created by Matthew Cheetham on 16/01/2016. // Copyright © 2016 Matt Cheetham. All rights reserved. // import Foundation #if os(iOS) import ThunderRequest #elseif os(tvOS) import ThunderRequestTV #elseif os (OSX) import ThunderRequestMac #endif /** The contacts controller is responsible for managing contacts in the Harvest API. Contacts can be assosciated with clients */ public final class ContactsController { /** The request controller used to load contact information. This is shared with other controllers */ let requestController: TSCRequestController /** Initialises a new controller. - parameter requestController: The request controller to use when loading contact information. This must be passed down from HarvestController so that authentication may be shared */ internal init(requestController: TSCRequestController) { self.requestController = requestController } //MARK: - Creating Contacts /** Creates a new contact entry in the Harvest system. You may configure any of the parameters on the contact object you are creating and they will be saved. - parameter contact: The new contact object to send to the API - parameter completionHandler: The completion handler to return any errors to - requires: `clientIdentifier`, `firstName` and `lastName` on the contact object as a minimum */ public func create(_ contact: Contact, completionHandler: @escaping (_ requestError: Error?) -> ()) { guard let _ = contact.clientIdentifier else { let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 400, userInfo: [NSLocalizedDescriptionKey: "Contact does not have a client identifier"]) completionHandler(error) return } guard let _ = contact.firstName else { let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 400, userInfo: [NSLocalizedDescriptionKey: "Contact does not have a first name"]) completionHandler(error) return } guard let _ = contact.lastName else { let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 400, userInfo: [NSLocalizedDescriptionKey: "Contact does not have a last name"]) completionHandler(error) return } requestController.post("contacts", bodyParams: contact.serialisedObject) { (response: TSCRequestResponse?, requestError: Error?) -> Void in if let error = requestError { completionHandler(error) return } completionHandler(nil) } } //MARK: - Retrieving Contacts /** Gets all contacts for the account of the authenticated user. - parameter completionHandler: The completion handler to return contacts and errors to - Note: The user must have access to the contacts on this account */ public func getContacts(_ completionHandler: @escaping (_ contacts: [Contact]?, _ requestError: Error?) -> ()) { requestController.get("contacts") { (response: TSCRequestResponse?, requestError: Error?) -> Void in if let error = requestError { completionHandler(nil, error) return; } if let contactsArray = response?.array as? [[String: AnyObject]] { let contacts = contactsArray.map({Contact(dictionary: $0)}).filter { $0 != nil }.map { $0! } completionHandler(contacts, nil) return } let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 500, userInfo: [NSLocalizedDescriptionKey: "The server did not return a valid response"]) completionHandler(nil, error) } } /** Gets all contacts assosciated with a client by their identifier - parameter clientIdentifier: The unique identifier of the client to search for contacts for - parameter completionHandler: The completion handler to return contacts and errors to - Note: The user must have access to the contacts on this account */ public func getContacts(_ clientIdentifier: Int, completionHandler: @escaping (_ contacts: [Contact]?, _ requestError: Error?) -> ()) { requestController.get("clients/\(clientIdentifier)/contacts") { (response: TSCRequestResponse?, requestError: Error?) -> Void in if let error = requestError { completionHandler(nil, error) return; } if let contactsArray = response?.array as? [[String: AnyObject]] { let contacts = contactsArray.map({Contact(dictionary: $0)}).filter { $0 != nil }.map { $0! } completionHandler(contacts, nil) return } let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 500, userInfo: [NSLocalizedDescriptionKey: "The server did not return a valid response"]) completionHandler(nil, error) } } /** Gets all contacts assosciated with a client - parameter clientIdentifier: The unique identifier of the client to search for contacts for - parameter completionHandler: The completion handler to return contacts and errors to - Note: The user must have access to the contacts on this account */ public func getContacts(_ client: Client, completionHandler: @escaping (_ contacts: [Contact]?, _ requestError: Error?) -> ()) { guard let clientIdentifier = client.identifier else { let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 400, userInfo: [NSLocalizedDescriptionKey: "The client specified does not have an identifier"]) completionHandler(nil, error) return } getContacts(clientIdentifier, completionHandler: completionHandler) } /** Gets a contact for a specific ID - parameter identifier: The identifier for a contact - parameter completionHandler: The completion handler to return the contact and errors to */ public func getContact(_ identifier: Int, completionHandler: @escaping (_ contact: Contact?, _ requestError: Error?) -> ()) { requestController.get("contacts/\(identifier)") { (response: TSCRequestResponse?, requestError: Error?) -> Void in if let error = requestError { completionHandler(nil, error) return } if let contactResponse = response { if let contactResponseDictionary = contactResponse.dictionary as? [String: AnyObject] { let foundContact = Contact(dictionary: contactResponseDictionary) completionHandler(foundContact, nil) return } } let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 500, userInfo: [NSLocalizedDescriptionKey: "The server did not return a valid contact object"]) completionHandler(nil, error) } } //MARK: - Modifying Contacts /** Updates a contact. The contact must have an identifier to be updated. All other properties will be updated in the system except for creation and update date which are fixed. - parameter contact: The contact to update. You may modify a contact returned from another request or create a new one that has a valid identifier - parameter completionHandler: The completion handler to return request errors to */ public func update(_ contact: Contact, completionHandler: @escaping (_ requestError: Error?) -> ()) { guard let contactIdentifier = contact.identifier else { let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 400, userInfo: [NSLocalizedDescriptionKey: "Supplied contact does not have an identifier"]) completionHandler(error) return; } requestController.put("contacts/\(contactIdentifier)", bodyParams: contact.serialisedObject) { (response: TSCRequestResponse?, requestError: Error?) -> Void in if let error = requestError { completionHandler(error) return } completionHandler(nil) } } /** Deletes the given contact. Will return an error of 404 if the timer has already been deleted or is not valid - parameter contact: The contact to delete - parameter completionHandler: The completion handler to return request errors to */ public func delete(_ contact: Contact, completionHandler: @escaping (_ requestError: Error?) -> ()) { guard let contactIdentifier = contact.identifier else { let error = NSError(domain: "co.uk.mattcheetham.harvestkit", code: 400, userInfo: [NSLocalizedDescriptionKey: "Contact does not have an identifier"]) completionHandler(error) return; } requestController.delete("contacts/\(contactIdentifier)") { (resposne: TSCRequestResponse?, requestError: Error?) -> Void in if let error = requestError { completionHandler(error) return; } completionHandler(nil) } } }
mit
82d3412d6367edb7958b8760efe2f638
37.795367
183
0.605892
5.572934
false
false
false
false
jaksatomovic/Snapgram
Snapgram/guestVC.swift
1
12880
// // guestVC.swift // Snapgram // // Created by Jaksa Tomovic on 28/11/16. // Copyright © 2016 Jaksa Tomovic. All rights reserved. // import UIKit import Parse var guestname = [String]() class guestVC: UICollectionViewController { // UI objects var refresher : UIRefreshControl! var page : Int = 12 // arrays to hold data from server var uuidArray = [String]() var picArray = [PFFile]() // default func override func viewDidLoad() { super.viewDidLoad() // allow vertical scroll self.collectionView!.alwaysBounceVertical = true // backgroung color self.collectionView?.backgroundColor = .white // top title self.navigationItem.title = guestname.last?.uppercased() // new back button self.navigationItem.hidesBackButton = true let backBtn = UIBarButtonItem(image: UIImage(named: "back.png"), style: .plain, target: self, action: #selector(guestVC.back(_:))) self.navigationItem.leftBarButtonItem = backBtn // swipe to go back let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(guestVC.back(_:))) backSwipe.direction = UISwipeGestureRecognizerDirection.right self.view.addGestureRecognizer(backSwipe) // pull to refresh refresher = UIRefreshControl() refresher.addTarget(self, action: #selector(guestVC.refresh), for: UIControlEvents.valueChanged) collectionView?.addSubview(refresher) // call load posts function loadPosts() } // back function func back(_ sender : UIBarButtonItem) { // push back self.navigationController?.popViewController(animated: true) // clean guest username or deduct the last guest userame from guestname = Array if !guestname.isEmpty { guestname.removeLast() } } // refresh function func refresh() { refresher.endRefreshing() loadPosts() } // posts loading function func loadPosts() { // load posts let query = PFQuery(className: "posts") query.whereKey("username", equalTo: guestname.last!) query.limit = page query.findObjectsInBackground (block: { (objects, error) -> Void in if error == nil { // clean up self.uuidArray.removeAll(keepingCapacity: false) self.picArray.removeAll(keepingCapacity: false) // find related objects for object in objects! { // hold found information in arrays self.uuidArray.append(object.value(forKey: "uuid") as! String) self.picArray.append(object.value(forKey: "pic") as! PFFile) } self.collectionView?.reloadData() } else { print(error!.localizedDescription) } }) } // load more while scrolling down override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.y >= scrollView.contentSize.height - self.view.frame.size.height { self.loadMore() } } // paging func loadMore() { // if there is more objects if page <= picArray.count { // increase page size page = page + 12 // load more posts let query = PFQuery(className: "posts") query.whereKey("username", equalTo: guestname.last!) query.limit = page query.findObjectsInBackground(block: { (objects, error) -> Void in if error == nil { // clean up self.uuidArray.removeAll(keepingCapacity: false) self.picArray.removeAll(keepingCapacity: false) // find related objects for object in objects! { self.uuidArray.append(object.value(forKey: "uuid") as! String) self.picArray.append(object.value(forKey: "pic") as! PFFile) } print("loaded +\(self.page)") self.collectionView?.reloadData() } else { print(error?.localizedDescription) } }) } } // cell numb override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return picArray.count } // cell size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let size = CGSize(width: self.view.frame.size.width / 3, height: self.view.frame.size.width / 3) return size } // cell config override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // define cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! pictureCell // connect data from array to picImg object from pictureCell class picArray[(indexPath as NSIndexPath).row].getDataInBackground (block: { (data, error) -> Void in if error == nil { cell.picImg.image = UIImage(data: data!) } else { print(error!.localizedDescription) } }) return cell } // header config override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // define header let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! headerView // STEP 1. Load data of guest let infoQuery = PFQuery(className: "_User") infoQuery.whereKey("username", equalTo: guestname.last!) infoQuery.findObjectsInBackground (block: { (objects, error) -> Void in if error == nil { // shown wrong user if objects!.isEmpty { // call alert let alert = UIAlertController(title: "\(guestname.last!.uppercased())", message: "is not existing", preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in self.navigationController?.popViewController(animated: true) }) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } // find related to user information for object in objects! { header.fullnameLbl.text = (object.object(forKey: "fullname") as? String)?.uppercased() header.bioLbl.text = object.object(forKey: "bio") as? String header.bioLbl.sizeToFit() header.webTxt.text = object.object(forKey: "web") as? String header.webTxt.sizeToFit() let avaFile : PFFile = (object.object(forKey: "ava") as? PFFile)! avaFile.getDataInBackground(block: { (data, error) -> Void in header.avaImg.image = UIImage(data: data!) }) } } else { print(error?.localizedDescription) } }) // STEP 2. Show do current user follow guest or do not let followQuery = PFQuery(className: "follow") followQuery.whereKey("follower", equalTo: PFUser.current()!.username!) followQuery.whereKey("following", equalTo: guestname.last!) followQuery.countObjectsInBackground (block: { (count, error) -> Void in if error == nil { if count == 0 { header.button.setTitle("FOLLOW", for: UIControlState()) header.button.backgroundColor = .lightGray } else { header.button.setTitle("FOLLOWING", for: UIControlState()) header.button.backgroundColor = .green } } else { print(error?.localizedDescription) } }) // STEP 3. Count statistics // count posts let posts = PFQuery(className: "posts") posts.whereKey("username", equalTo: guestname.last!) posts.countObjectsInBackground (block: { (count, error) -> Void in if error == nil { header.posts.text = "\(count)" } else { print(error?.localizedDescription) } }) // count followers let followers = PFQuery(className: "follow") followers.whereKey("following", equalTo: guestname.last!) followers.countObjectsInBackground (block: { (count, error) -> Void in if error == nil { header.followers.text = "\(count)" } else { print(error?.localizedDescription) } }) // count followings let followings = PFQuery(className: "follow") followings.whereKey("follower", equalTo: guestname.last!) followings.countObjectsInBackground (block: { (count, error) -> Void in if error == nil { header.followings.text = "\(count)" } else { print(error?.localizedDescription) } }) // STEP 4. Implement tap gestures // tap to posts label let postsTap = UITapGestureRecognizer(target: self, action: #selector(guestVC.postsTap)) postsTap.numberOfTapsRequired = 1 header.posts.isUserInteractionEnabled = true header.posts.addGestureRecognizer(postsTap) // tap to followers label let followersTap = UITapGestureRecognizer(target: self, action: #selector(guestVC.followersTap)) followersTap.numberOfTapsRequired = 1 header.followers.isUserInteractionEnabled = true header.followers.addGestureRecognizer(followersTap) // tap to followings label let followingsTap = UITapGestureRecognizer(target: self, action: #selector(guestVC.followingsTap)) followingsTap.numberOfTapsRequired = 1 header.followings.isUserInteractionEnabled = true header.followings.addGestureRecognizer(followingsTap) return header } // tapped posts label func postsTap() { if !picArray.isEmpty { let index = IndexPath(item: 0, section: 0) self.collectionView?.scrollToItem(at: index, at: UICollectionViewScrollPosition.top, animated: true) } } // tapped followers label func followersTap() { user = guestname.last! showDetails = "followers" // defind followersVC let followers = self.storyboard?.instantiateViewController(withIdentifier: "followersVC") as! followersVC // navigate to it self.navigationController?.pushViewController(followers, animated: true) } // tapped followings label func followingsTap() { user = guestname.last! showDetails = "followings" // define followersVC let followings = self.storyboard?.instantiateViewController(withIdentifier: "followersVC") as! followersVC // navigate to it self.navigationController?.pushViewController(followings, animated: true) } // go post override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // send post uuid to "postuuid" variable postuuid.append(uuidArray[(indexPath as NSIndexPath).row]) // navigate to post view controller let post = self.storyboard?.instantiateViewController(withIdentifier: "postVC") as! postVC self.navigationController?.pushViewController(post, animated: true) } }
mit
68825b09d17baea41c5e9ec54477f672
35.07563
176
0.565494
5.546512
false
false
false
false
everald/JetPack
Sources/Extensions/UIKit/UIBezierPath.swift
1
4251
import UIKit public extension UIBezierPath { @nonobjc public convenience init(animatableRoundedRect rect: CGRect, cornerRadii: CornerRadii = .zero) { self.init() move(to: CGPoint(left: rect.left + cornerRadii.topLeft, top: rect.top)) addLine(to: CGPoint(left: rect.right - cornerRadii.topRight, top: rect.top)) addRoundedCorner(direction: .rightDown, radius: cornerRadii.topRight) addLine(to: CGPoint(left: rect.right, top: rect.bottom - cornerRadii.bottomRight)) addRoundedCorner(direction: .downLeft, radius: cornerRadii.bottomRight) addLine(to: CGPoint(left: rect.left + cornerRadii.bottomLeft, top: rect.bottom)) addRoundedCorner(direction: .leftUp, radius: cornerRadii.bottomLeft) addLine(to: CGPoint(left: rect.left, top: rect.top + cornerRadii.topLeft)) addRoundedCorner(direction: .upRight, radius: cornerRadii.topLeft) } @nonobjc public func addRoundedCorner(direction: RoundedCornerDirection, radius requestedRadius: CGFloat) { let radius = max(requestedRadius, 0) var center: CGPoint var clockwise: Bool var endAngle: CGFloat var startAngle: CGFloat switch direction { case .downLeft: center = currentPoint.offsetBy(dx: -radius) clockwise = true endAngle = CGMath.radiansBottom startAngle = CGMath.radiansRight case .downRight: center = currentPoint.offsetBy(dx: radius) clockwise = false endAngle = CGMath.radiansBottom startAngle = CGMath.radiansLeft case .leftDown: center = currentPoint.offsetBy(dy: radius) clockwise = false endAngle = CGMath.radiansLeft startAngle = CGMath.radiansTop case .leftUp: center = currentPoint.offsetBy(dy: -radius) clockwise = true endAngle = CGMath.radiansLeft startAngle = CGMath.radiansBottom case .rightDown: center = currentPoint.offsetBy(dy: radius) clockwise = true endAngle = CGMath.radiansRight startAngle = CGMath.radiansTop case .rightUp: center = currentPoint.offsetBy(dy: -radius) clockwise = false endAngle = CGMath.radiansRight startAngle = CGMath.radiansBottom case .upLeft: center = currentPoint.offsetBy(dx: -radius) clockwise = false endAngle = CGMath.radiansTop startAngle = CGMath.radiansRight case .upRight: center = currentPoint.offsetBy(dx: radius) clockwise = true endAngle = CGMath.radiansTop startAngle = CGMath.radiansLeft } addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise) } fileprivate func centerForRoundedCorner(direction: RoundedCornerDirection, radius: CGFloat) -> CGPoint { switch direction { case .leftDown, .rightDown: return currentPoint.offsetBy(dy: radius) case .leftUp, .rightUp: return currentPoint.offsetBy(dy: -radius) case .downLeft, .upLeft: return currentPoint.offsetBy(dx: -radius) case .downRight, .upRight: return currentPoint.offsetBy(dx: radius) } } fileprivate class func endAngleForRoundedCorner(direction: RoundedCornerDirection) -> CGFloat { switch direction { case .downLeft, .downRight: return CGMath.radiansBottom case .leftDown, .leftUp: return CGMath.radiansLeft case .rightDown, .rightUp: return CGMath.radiansRight case .upLeft, .upRight: return CGMath.radiansTop } } @nonobjc public func invertedBezierPathInRect(_ rect: CGRect) -> UIBezierPath { let path = UIBezierPath(rect: rect) path.usesEvenOddFillRule = true path.append(self) return path } fileprivate class func roundedCornerIsClockwise(direction: RoundedCornerDirection) -> Bool { switch direction { case .upRight, .rightDown, .downLeft, .leftUp: return true case .leftDown, .downRight, .rightUp, .upLeft: return false } } fileprivate class func startAngleForRoundedCorner(direction: RoundedCornerDirection) -> CGFloat { switch direction { case .downLeft, .upLeft: return CGMath.radiansRight case .downRight, .upRight: return CGMath.radiansLeft case .leftDown, .rightDown: return CGMath.radiansTop case .leftUp, .rightUp: return CGMath.radiansBottom } } public enum RoundedCornerDirection { case downLeft case downRight case leftDown case leftUp case rightDown case rightUp case upLeft case upRight } }
mit
b902ca2524b90ca9fccdabd4de9f3a44
24.153846
110
0.740061
3.661499
false
false
false
false
bzmario/SwiftyBeaver
SwiftyBeaverTests/BaseDestinationTests.swift
1
6730
// // BaseDestinationTests.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import XCTest @testable import SwiftyBeaver class BaseDestinationTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testInit() { let obj = BaseDestination() XCTAssertNotNil(obj.queue) } func testFormattedDate() { // empty format var str = BaseDestination().formattedDate("") XCTAssertEqual(str, "") // no time format str = BaseDestination().formattedDate("--") XCTAssertGreaterThanOrEqual(str, "--") // HH:mm:ss let formatter = NSDateFormatter() formatter.dateFormat = "HH:mm:ss" let dateStr = formatter.stringFromDate(NSDate()) str = BaseDestination().formattedDate(formatter.dateFormat) XCTAssertEqual(str, dateStr) } func testFormattedLevel() { let obj = BaseDestination() var str = "" str = obj.formattedLevel(SwiftyBeaver.Level.Verbose) XCTAssertNotNil(str, "VERBOSE") str = obj.formattedLevel(SwiftyBeaver.Level.Debug) XCTAssertNotNil(str, "DEBUG") str = obj.formattedLevel(SwiftyBeaver.Level.Info) XCTAssertNotNil(str, "INFO") str = obj.formattedLevel(SwiftyBeaver.Level.Warning) XCTAssertNotNil(str, "WARNING") str = obj.formattedLevel(SwiftyBeaver.Level.Error) XCTAssertNotNil(str, "ERROR") // custom level strings obj.levelString.Verbose = "Who cares" obj.levelString.Debug = "Look" obj.levelString.Info = "Interesting" obj.levelString.Warning = "Oh oh" obj.levelString.Error = "OMG!!!" str = obj.formattedLevel(SwiftyBeaver.Level.Verbose) XCTAssertNotNil(str, "Who cares") str = obj.formattedLevel(SwiftyBeaver.Level.Debug) XCTAssertNotNil(str, "Look") str = obj.formattedLevel(SwiftyBeaver.Level.Info) XCTAssertNotNil(str, "Interesting") str = obj.formattedLevel(SwiftyBeaver.Level.Warning) XCTAssertNotNil(str, "Oh oh") str = obj.formattedLevel(SwiftyBeaver.Level.Error) XCTAssertNotNil(str, "OMG!!!") } func testFormattedMessage() { let obj = BaseDestination() var str = "" let formatter = NSDateFormatter() formatter.dateFormat = "HH:mm:ss" let dateStr = formatter.stringFromDate(NSDate()) str = obj.formattedMessage(dateStr, levelString: "DEBUG", msg: "Hello", path: "/path/to/ViewController.swift", function: "testFunction()", line: 50, detailOutput: false) XCTAssertNotNil(str.rangeOfString("[\(dateStr)] DEBUG: Hello")) str = obj.formattedMessage(dateStr, levelString: "DEBUG", msg: "Hello", path: "/path/to/ViewController.swift", function: "testFunction()", line: 50, detailOutput: true) print(str) XCTAssertNotNil(str.rangeOfString("[\(dateStr)] ViewController.testFunction():50 DEBUG: Hello")) } func testFormattedMessageEmptyDate() { let obj = BaseDestination() var str = "" let dateStr = obj.formattedDate("") XCTAssertEqual(dateStr, "") str = obj.formattedMessage(dateStr, levelString: "DEBUG", msg: "Hello", path: "/path/to/ViewController.swift", function: "testFunction()", line: 50, detailOutput: false) XCTAssertEqual(str, "DEBUG: Hello") } func testShouldLevelBeLogged() { let obj = BaseDestination() obj.minLevel = SwiftyBeaver.Level.Info // filters to set minLevel to Verbose for certain files / folders obj.addMinLevelFilter(.Verbose, path: "foo.swift") obj.addMinLevelFilter(.Verbose, path: "/bar/") obj.addMinLevelFilter(.Verbose, path: "/app") obj.addMinLevelFilter(.Verbose, path: "/world/beaver.swift", function: "AppDelegate") obj.addMinLevelFilter(.Verbose, path: "", function: "MyFunction") // check instance minLevel property XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "", function: "")) XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Debug, path: "", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Info, path: "", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Warning, path: "", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Error, path: "", function: "")) // check if filters overrule instance property XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "foo2.swift", function: "")) XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "Foo.swift", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "foo.swift", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/hello/foo.swift", function: "")) // check filter 2 XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "bar", function: "")) XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/Bar/", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/bar/", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/hello/bar/beaver", function: "")) // check filter 3 XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/lol/App2/", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/lol/app2/", function: "")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/lol/app", function: "")) // check filter 4 (file & function) XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/world/beaver/", function: "")) XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "world/beaver.swift", function: "")) XCTAssertFalse(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/world/beaver.swift", function: "appDelegate")) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "/world/beaver.swift", function: "AppDelegate")) // check filter 5 (function) XCTAssertTrue(obj.shouldLevelBeLogged(SwiftyBeaver.Level.Verbose, path: "", function: "MyFunction")) } }
mit
559f72b4f4d361980ffb8264658170e5
46.723404
177
0.663694
4.386571
false
true
false
false
YauheniYarotski/APOD
APOD/ApodManager.swift
1
7362
// // ApodManager.swift // APOD // // Created by Yauheni Yarotski on 6/27/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // protocol ApodManagerDelegate { func apodLikesAmountDidChangeForDate(_ apodManager: ApodManager, date: Date, likesAmount: Int) func apodIsSelfLikedDidChangeForDate(_ apodManager: ApodManager, date: Date, isSelfLiked: Bool) } class ApodManager: NSObject { let notificaitonCenter = NotificationCenter.default let networkManager = NetworkManager.sharedInstance let calendarManager = CalendarManager.sharedInstance let cacheManager = CacheManager.sharedInstance let fireBaseManager = FirebaseManager.sharedInstance static let sharedInstance = ApodManager() var delegate: ApodManagerDelegate? var isFreeVersion: Bool { didSet { if isFreeVersion != oldValue { IOManager.saveIsAppPurchaed(!isFreeVersion) } } } //MARK: - ApodManager override init() { let isAppPurchased = IOManager.loadIsAppPurchased() if isAppPurchased { self.isFreeVersion = !isAppPurchased } else if let path = Bundle.main.path(forResource: "Info", ofType: "plist"), let infoDict = NSDictionary(contentsOfFile: path), let fromPlistIsFreeVersion = infoDict["isFreeVersion"] as? Bool { isFreeVersion = fromPlistIsFreeVersion } else { self.isFreeVersion = true } super.init() removeSavedImagesInBrokerVersion() configAppNotifications() fireBaseManager.delegate = self } fileprivate func currentVersion() -> String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } //MARK: - Save fileprivate func saveApod(_ apod: Apod) { cacheManager.cacheApod(apod) cacheManager.saveCacheToDisk()//TODO: save one apod by onw } fileprivate func saveImage(_ image: UIImage, name: String) { IOManager.saveImageToDisk(image, name: name) } fileprivate func removeSavedImagesInBrokerVersion() { let previosVersion = IOManager.loadSavedCurrentVersion() ?? "0.0.1" let fixedVersion = "0.0.4" if previosVersion != currentVersion() { if previosVersion.compare(fixedVersion) == .orderedAscending { // previosVersion is lower than the fixedVersion IOManager.removeAllImages() } IOManager.saveCurrentVersion() } } //MARK: - Apods func apodForDate(_ date: Date, completion:@escaping (_ apod: Apod?, _ error: Error?) -> Void) { if let apod = cacheManager.getCachedApodForDate(date) { completion(apod, nil) } else { networkManager.getApodForDate(date) { (networkApod, error) in if let networkApod = networkApod { let mediaType = MediaType(rawValue: networkApod.mediaType) ?? MediaType.na let apod = Apod(date: date, title: networkApod.title, explanation: networkApod.explanation, mediaType: mediaType, url: networkApod.url, hdUrl: networkApod.hdUrl, copyright: networkApod.copyright) self.saveApod(apod) completion(apod, nil) } else if let error = error { completion(nil, error) } } } } func mediaForDate(_ date: Date, completion:((_ image: UIImage?, _ videoIdentifier: String?, _ url: URL?, _ error: Error?) -> Void)?) { apodForDate(date) { (apod, error) in if let apod = apod { switch apod.mediaType { case .image: if let image = self.cacheManager.getCachedImageForUrl(apod.url) { completion?(image, nil, nil, nil) } else if let image = IOManager.loadImageFromDiskWithName(URL(fileURLWithPath: apod.url).lastPathComponent) { self.cacheManager.cacheImage(image, url: apod.url) completion?(image, nil, nil, nil) } else { self.networkManager.getImageForUrl(apod.url, completion: { (image, error) in if let image = image { self.cacheManager.cacheImage(image, url: apod.url) self.saveImage(image, name: URL(fileURLWithPath: apod.url).lastPathComponent) completion?(image, nil, nil, nil) } else { completion?(nil, nil, nil, error) } }) } case .video: if let videoIdentifier = apod.url.videoIdentifier() { completion?(nil, videoIdentifier, nil, nil) } else { completion?(nil, nil, URL(string: apod.url), nil) } default: completion?(nil, nil, nil, NSError(domain: "Unknown mediaType: \(apod.mediaType.rawValue)", code: -99, userInfo: nil)) } } else { completion?(nil, nil, nil, error) } } } func updateApodLikesForDate(_ date: Date) { FirebaseManager.sharedInstance.startRecivingApodLikesForDate(date) } func likeApodForDate(_ date: Date) { fireBaseManager.likeApodForDate(date) } func firstApodDate() -> Date { var components = DateComponents() components.day = 16 components.month = 06 components.year = 1996 let date = calendarManager.nasaCalendar.date(from: components)! return date } func lastApodDate() -> Date { //TODO: maka synchromizes with data source, because thit date is fkexible, and data source is counted only at the begining return calendarManager.nasaCalendar.startOfDay(for: Date()) } func totalAmountOfApods() -> Int { return calendarManager.nasaCalendar.dateComponents([.day], from: firstApodDate(), to: lastApodDate()).day! + 1 } func cancelOperationForDate(_ date: Date) { networkManager.cancelOperationForDate(date) } //MARK: - Notifications func configAppNotifications() { notificaitonCenter.addObserver(self, selector: #selector(ApodManager.appWasPuchased), name: Notification.Name(rawValue: IAPHelper.kIAPHelperPurchaseNotification), object: nil) } func appWasPuchased() { isFreeVersion = false } } //MARK: - FirebaseManagerDelegate extension ApodManager: FirebaseManagerDelegate { func apodLikesAmountDidChange(_ firebaseManager: FirebaseManager, apodDate: Date, likesAmount: Int) { delegate?.apodLikesAmountDidChangeForDate(self, date: apodDate, likesAmount: likesAmount) } func apodIsSelfLikedDidChange(_ firebaseManager: FirebaseManager, apodDate: Date, isSelfLiked: Bool) { delegate?.apodIsSelfLikedDidChangeForDate(self, date: apodDate, isSelfLiked: isSelfLiked) } }
mit
6f6cb4a2fa7c97b8879a9a1729d39b79
36.943299
215
0.591496
4.661811
false
false
false
false
microeditionbiz/reddit-client
reddit-client/reddit-client/Helpers/Fle System/FileSystemHelper.swift
1
911
// // FileSystemHelper.swift // reddit-client // // Created by Pablo Romero on 1/20/17. // Copyright © 2017 Pablo Romero. All rights reserved. // import UIKit class FileSystemHelper: NSObject { static let sharedInstance: FileSystemHelper = FileSystemHelper() let fileManager = FileManager.default func existFile(atUrl url: URL) -> Bool { let path = url.path return self.fileManager.fileExists(atPath: path) } func copyFile(atUrl: URL, toUrl: URL) { if self.existFile(atUrl: toUrl) { try! self.fileManager.removeItem(at: toUrl) } try! self.fileManager.copyItem(at: atUrl, to: toUrl) } static func cachesUrl() -> URL { let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String] let path = paths.first! return URL(fileURLWithPath: path) } }
mit
63b2ccabc70b01fb9e6eb01164a6d90a
26.575758
108
0.648352
4.212963
false
false
false
false
xuech/OMS-WH
OMS-WH/Utilities/AutoAlertView/XCHAlertController.swift
1
11502
// // XCHAlertController.swift // OMSAutoAlertView // // Created by xuech on 2017/11/22. // Copyright © 2017年 xuech. All rights reserved. // import UIKit enum Dimension { static var width: CGFloat { return (UIScreen.main.bounds.width <= 414.0) ? (UIScreen.main.bounds.width - 60) : 280 } static let padding: CGFloat = 15.0 static let buttonHeight: CGFloat = 50.0 static let iconHeight: CGFloat = 100.0 } class XCHAlertController: UIView { fileprivate var alertViewHeight: NSLayoutConstraint? fileprivate var buttonStackViewHeightConstraint: NSLayoutConstraint? fileprivate var buttonStackViewWidthConstraint: NSLayoutConstraint? fileprivate var scrollViewHeightConstraint: NSLayoutConstraint? fileprivate var imageViewHeight: CGFloat = Dimension.iconHeight fileprivate var messageLabelHeight: CGFloat = 20 fileprivate var iconHeightConstraint: NSLayoutConstraint? //MARK:外界设置 public var cornerRadius: CGFloat? { willSet { alertView.layer.cornerRadius = newValue! } } public var iconImage: UIImage? { get { return imageView.image } set { imageView.image = newValue guard let image = newValue else { imageViewHeight = 0 iconHeightConstraint?.constant = imageViewHeight return } (image.size.height > CGFloat(0.0)) ? (imageViewHeight = Dimension.iconHeight) : (imageViewHeight = 0) iconHeightConstraint?.constant = imageViewHeight } } public var titleText: String? { get { return titleLabel.text } set { titleLabel.text = newValue } } public var messageText: String? { get { return messageTextView.text } set { messageTextView.text = newValue } } public var titleColor: UIColor? { willSet { titleLabel.textColor = newValue } } public var messageColor: UIColor? { willSet { messageTextView.textColor = newValue } } // public var backgroundColor: UIColor? { // willSet { // alertView.backgroundColor = newValue // } // } // public var backgroundViewColor: UIColor? { // willSet { // backgroundView.backgroundColor = newValue // } // } // // public var backgroundViewAlpha: CGFloat? { // willSet { // backgroundView.alpha = newValue! // } // } // public var buttonSpacing: CGFloat = 15 { // willSet { // buttonStackView.spacing = newValue // } // } //MARK:懒加载控件 ///背景视图 fileprivate lazy var backgroundView: UIView = { let bgView = UIView() bgView.translatesAutoresizingMaskIntoConstraints = false bgView.backgroundColor = .darkGray bgView.alpha = 0.3 return bgView }() ///内容视图 fileprivate var alertView: UIView = { let alertView = UIView() alertView.translatesAutoresizingMaskIntoConstraints = false alertView.backgroundColor = UIColor.xchAlertviewColor alertView.layer.cornerRadius = 5 alertView.layer.shadowColor = UIColor.black.cgColor alertView.layer.shadowOpacity = 0.2 alertView.layer.shadowOffset = CGSize(width: 0, height: 0) alertView.layer.shadowRadius = 5 alertView.clipsToBounds = false return alertView }() ///背景图 fileprivate var imageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit return imageView }() fileprivate var titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.boldSystemFont(ofSize: 17) label.textAlignment = .center label.textColor = .black label.numberOfLines = 2 return label }() fileprivate var messageTextView: UITextView = { let textview = UITextView() textview.translatesAutoresizingMaskIntoConstraints = false textview.font = UIFont.systemFont(ofSize: 14) textview.textAlignment = .center textview.isEditable = false textview.showsHorizontalScrollIndicator = false textview.textColor = UIColor.black textview.backgroundColor = UIColor.clear textview.isScrollEnabled = false textview.isSelectable = false textview.bounces = false return textview }() fileprivate let buttonStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.alignment = .fill stackView.distribution = .fillEqually stackView.axis = .horizontal return stackView }() // MARK: - 初始化 required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public convenience init (frame: CGRect,title: String, message: String?) { self.init(frame: frame,icon: nil, title: title, message: message) } public init(frame: CGRect,icon: UIImage?, title: String, message: String?) { super.init(frame: frame) self.titleText = title self.messageText = message (icon != nil) ? (iconImage = icon) : (imageViewHeight = 0.0) (message != nil) ? (messageLabelHeight = 20) : (messageLabelHeight = 0.0) setUp() } open func showViews() { if alertView.frame.height >= UIScreen.main.bounds.height - 80 { messageTextView.isScrollEnabled = true } UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.5, options: .curveLinear, animations: { let transform = CGAffineTransform(translationX: 0, y: -100) self.alertView.transform = transform }, completion: nil) } open func disappear() { // UIView.animate(withDuration: 0.1, delay: 0.0, usingSpringWithDamping: 0, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: { // let transform = CGAffineTransform(translationX: 0, y: 500) // self.alertView.transform = transform // }, completion: { (true) in self.removeFromSuperview() // }) } // open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // alertViewHeight?.constant = size.height - 80 // alertView.layoutIfNeeded() // } } extension XCHAlertController { fileprivate func setUp() { // self.modalPresentationStyle = .custom // self.modalTransitionStyle = .crossDissolve self.addSubview(alertView) self.insertSubview(backgroundView, at: 0) alertView.addSubview(imageView) alertView.addSubview(titleLabel) alertView.addSubview(messageTextView) alertView.addSubview(buttonStackView) // backgroundView Constraints backgroundView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true backgroundView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true backgroundView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true backgroundView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true // alertView Constraints alertView.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor).isActive = true alertView.centerXAnchor.constraint(equalTo: backgroundView.centerXAnchor).isActive = true alertView.widthAnchor.constraint(equalToConstant: Dimension.width).isActive = true alertViewHeight = alertView.heightAnchor.constraint(lessThanOrEqualToConstant: self.bounds.height - 80) alertViewHeight!.isActive = true // imageView Constraints imageView.topAnchor.constraint(equalTo: alertView.topAnchor, constant: 5).isActive = true imageView.leadingAnchor.constraint(equalTo: alertView.leadingAnchor, constant: Dimension.padding).isActive = true imageView.trailingAnchor.constraint(equalTo: alertView.trailingAnchor, constant: -Dimension.padding).isActive = true iconHeightConstraint = imageView.heightAnchor.constraint(equalToConstant: imageViewHeight) iconHeightConstraint?.isActive = true // titleLabel Constraints titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 8).isActive = true titleLabel.leadingAnchor.constraint(equalTo: alertView.leadingAnchor, constant: Dimension.padding).isActive = true titleLabel.trailingAnchor.constraint(equalTo: alertView.trailingAnchor, constant: -Dimension.padding).isActive = true titleLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 20).isActive = true titleLabel.sizeToFit() // messageLabel Constraints messageTextView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 0).isActive = true messageTextView.leadingAnchor.constraint(equalTo: alertView.leadingAnchor, constant: Dimension.padding).isActive = true messageTextView.trailingAnchor.constraint(equalTo: alertView.trailingAnchor, constant: -Dimension.padding).isActive = true messageTextView.heightAnchor.constraint(greaterThanOrEqualToConstant: messageLabelHeight).isActive = true messageTextView.sizeToFit() // actionStackView Constraints buttonStackView.topAnchor.constraint(equalTo: messageTextView.bottomAnchor, constant: 8).isActive = true buttonStackView.leadingAnchor.constraint(equalTo: alertView.leadingAnchor, constant: 0).isActive = true buttonStackView.trailingAnchor.constraint(equalTo: alertView.trailingAnchor, constant: 0).isActive = true buttonStackView.bottomAnchor.constraint(equalTo: alertView.bottomAnchor, constant: 0).isActive = true buttonStackViewHeightConstraint = buttonStackView.heightAnchor.constraint(equalToConstant: (Dimension.buttonHeight * CGFloat(buttonStackView.arrangedSubviews.count))) buttonStackViewHeightConstraint!.isActive = true } } extension XCHAlertController { open func addAction(action: XCHAlertAction) { buttonStackView.addArrangedSubview(action) if buttonStackView.arrangedSubviews.count > 2 { buttonStackView.axis = .vertical buttonStackViewHeightConstraint?.constant = Dimension.buttonHeight * CGFloat(buttonStackView.arrangedSubviews.count) buttonStackView.spacing = 0 } else { buttonStackViewHeightConstraint?.constant = Dimension.buttonHeight buttonStackView.axis = .horizontal buttonStackView.spacing = 15 } action.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) } @objc func buttonAction(sender: XCHAlertAction) { // dismiss(animated: true, completion: nil) disappear() } }
mit
881f3cb4f5490db49fc72d7af385da68
38.357388
174
0.657382
5.47205
false
false
false
false
lieonCX/Live
Live/Model/Transform.swift
1
5807
// // Transform.swift // Live // // Created by lieon on 2017/6/21. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit import ObjectMapper open class IntStringTransform: TransformType { public typealias Object = Int public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> Int? { if let time = value as? String { return Int(time) } return nil } public func transformToJSON(_ value: Int?) -> String? { if let date = value { return String(date) } return nil } } open class ArrayOfURLTransform: TransformType { public typealias Object = [URL?] public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> [URL?]? { if let time = value as? [String] { return time.map { return URL(string: $0)} } return nil } public func transformToJSON(_ value: [URL?]?) -> String? { if let date = value { let array = date.flatMap { return $0?.absoluteString } return array.joined(separator: ",") } return nil } } open class FloatStringTransform: TransformType { public typealias Object = Float public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> Float? { if let time = value as? String { return Float(time) } return nil } public func transformToJSON(_ value: Float?) -> String? { if let date = value { return String(date) } return nil } } open class BoolNumberTransform: TransformType { public typealias Object = Bool public typealias JSON = Int public init() {} public func transformFromJSON(_ value: Any?) -> Bool? { if let time = value as? Int { if time == 1 { return true } else { return false } } return nil } public func transformToJSON(_ value: Bool?) -> Int? { if let date = value { if date == true { return 1 } else { return 0 } } return nil } } open class BoolStringTransform: TransformType { public typealias Object = Bool public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> Bool? { if let time = value as? String { if time == "1" { return true } else { return false } } return nil } public func transformToJSON(_ value: Bool?) -> String? { if let date = value { if date == true { return "1" } else { return "0" } } return nil } } open class DoubleStringTransform: TransformType { public typealias Object = Double public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> Double? { if let time = value as? String { return Double(time) } return nil } public func transformToJSON(_ value: Double?) -> String? { if let date = value { return String(date) } return nil } } open class HtmlStringTransform: TransformType { public typealias Object = String public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> String? { if let time = value as? String { let string = time.stringByRemovingCharactersInSet(CharacterSet(charactersIn: "\"")) return string } return nil } public func transformToJSON(_ value: String?) -> String? { if let date = value { return String(date) } return nil } } open class DataStringTransform: TransformType { public typealias Object = Data public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> Data? { if let time = value as? String { return Data(base64Encoded: time, options: .ignoreUnknownCharacters) } return nil } public func transformToJSON(_ value: Data?) -> String? { if let date = value { return date.base64EncodedString(options: .lineLength64Characters) } return nil } } open class RegionPathsTransform: TransformType { public typealias Object = [String] public typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> [String]? { if let string = value as? String { return string.components(separatedBy: ",") } return nil } public func transformToJSON(_ value: [String]?) -> String? { if let strings = value { // FIXME: need test return strings.reduce("", { $0 ?? $1 + "," + $1 }) } return nil } } open class DateTransform: TransformType { public typealias Object = Date public typealias JSON = Double public init() {} public func transformFromJSON(_ value: Any?) -> Date? { if let interval = value as? Double { return Date(timeIntervalSince1970: interval / 1000.0) } return nil } public func transformToJSON(_ value: Date?) -> Double? { if let date = value { return date.timeIntervalSince1970 * 1000.0 } return nil } }
mit
cab2d62f7bcb4f71c252d27122555d3f
23.082988
95
0.540145
4.943782
false
false
false
false
haitran2011/Rocket.Chat.iOS
Rocket.Chat/Views/Cells/Chat/ChatMessageImageView.swift
1
1738
// // ChatMessageImageView.swift // Rocket.Chat // // Created by Rafael K. Streit on 03/10/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import UIKit import SDWebImage protocol ChatMessageImageViewProtocol: class { func openImageFromCell(attachment: Attachment, thumbnail: UIImageView) } final class ChatMessageImageView: UIView { static let defaultHeight = CGFloat(250) weak var delegate: ChatMessageImageViewProtocol? var attachment: Attachment! { didSet { updateMessageInformation() } } @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var activityIndicatorImageView: UIActivityIndicatorView! @IBOutlet weak var imageView: UIImageView! { didSet { imageView.layer.cornerRadius = 3 imageView.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.1).cgColor imageView.layer.borderWidth = 1 } } private lazy var tapGesture: UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(didTapView)) }() fileprivate func updateMessageInformation() { let containsGesture = gestureRecognizers?.contains(tapGesture) ?? false if !containsGesture { addGestureRecognizer(tapGesture) } labelTitle.text = attachment.title let imageURL = attachment.fullImageURL() activityIndicatorImageView.startAnimating() imageView.sd_setImage(with: imageURL, completed: { [weak self] _, _, _, _ in self?.activityIndicatorImageView.stopAnimating() }) } func didTapView() { delegate?.openImageFromCell(attachment: attachment, thumbnail: imageView) } }
mit
3074f5e6ca6d220f45afb91c4f341496
28.948276
91
0.679908
5.093842
false
false
false
false
GabrielYeah/ToolBox
Tip Calculator/TodayViewController.swift
1
4789
// // TodayViewController.swift // Tip Calculator // // Created by Gabriel Yeah on 12/24/14. // Copyright (c) 2014 Haishan Ye. All rights reserved. // import UIKit import NotificationCenter enum TipLevel { case Satisfied case Standard case Unsatisfied mutating func changeLevel(level : NSInteger) { switch level { case 1: self = .Unsatisfied case 2: self = .Standard case 3: self = .Satisfied default: self = .Standard } } func color(alpha : CGFloat) -> UIColor { var color = UIColor.whiteColor() switch self { case .Satisfied: color = UIColor.UIColorFromRGB(0x09BB44, alpha: alpha) case .Unsatisfied: color = UIColor.UIColorFromRGB(0xEA5251, alpha: alpha) case .Standard: color = UIColor.UIColorFromRGB(0x0096DA, alpha: alpha) } return color } func factor() -> Double { var factor = 1.0 switch self { case .Satisfied: factor = 0.2 case .Unsatisfied: factor = 0.1 case .Standard: factor = 0.15 } return 1.0 / 1.09 * factor + 1.0 } } class TodayViewController: UIViewController, NCWidgetProviding { // MARK: Properties @IBOutlet weak var currentValueLabel: UILabel! @IBOutlet weak var functionButton: UIButton! @IBOutlet weak var resultLabel: UILabel! var sharing = false var sharingCount : Int = 1 var currentValue : Double = 0.0 { didSet { updateResult() } } var tipLevel : TipLevel = .Standard { didSet { updateResult() } } var currentResult : Double { return currentValue * tipLevel.factor() / Double(sharingCount * 100) } // MARK: View Methods override func viewDidLoad() { super.viewDidLoad() preferredContentSize.height = 220 updateButtons() updateResult() } override func viewWillAppear(animated: Bool) { updateResult() } func updateButtons() { for i in 1...15 { if let button = view.viewWithTag(i) as? UIButton { switch i { case 12: button.backgroundColor = TipLevel.Unsatisfied.color(0.5) case 13: button.backgroundColor = TipLevel.Standard.color(0.5) case 14: button.backgroundColor = TipLevel.Satisfied.color(0.5) case 15: button.backgroundColor = UIColor.UIColorFromRGB(0xD2691E, alpha: 0.5) default: button.backgroundColor = UIColor.UIColorFromRGB(0xF7F7F7, alpha: 0.1) } } } resultLabel.adjustsFontSizeToFitWidth = true; resultLabel.minimumScaleFactor = 0.5; } func updateResult() { currentValueLabel.text = String(format: "%.2f", currentValue / 100) resultLabel.text = String(format: "%.2f", currentResult) } func widgetMarginInsetsForProposedMarginInsets (defaultMarginInsets: UIEdgeInsets) -> (UIEdgeInsets) { var inset = defaultMarginInsets inset.bottom = 0 inset.top = 0 inset.left = 0 inset.right = 0 return inset } // MARK: Data Methods @IBAction func didClickButton(sender: UIButton) { switch sender.tag { case 15: handleSharingButton() case 11: clearContext() case 12...14: tipLevel.changeLevel(sender.tag - 11) resultLabel.textColor = tipLevel.color(1) default: appendNewCharacter(sender.currentTitle) } } func appendNewCharacter(title : String?) { if let title = title { currentValue = currentValue * 10.0 + Double(title.toInt()!) } } func handleSharingButton() { sharingCount++ updateResult() functionButton.setTitle("+\(sharingCount)", forState: .Normal) } func clearContext() { sharing = false sharingCount = 1 functionButton.setTitle("+\(sharingCount)", forState: .Normal) currentValue = 0.0 updateResult() } } extension UIColor { class func UIColorFromRGB(rgbValue: UInt, alpha: CGFloat) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(alpha) ) } }
mit
101758298308efc7847d16e33ac55666
26.522989
89
0.550637
4.708948
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/ConversationList/ListContent/ConversationListAvatarView.swift
1
7310
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // /// Source of random values. public protocol RandomGenerator { func rand<ContentType>() -> ContentType } /// Generates the pseudorandom values from the data given. /// @param data the source of random values. final class RandomGeneratorFromData: RandomGenerator { public let source: Data private var step: Int = 0 init(data: Data) { source = data } public func rand<ContentType>() -> ContentType { let currentStep = self.step let result = source.withUnsafeBytes { (pointer: UnsafePointer<ContentType>) -> ContentType in return pointer.advanced(by: currentStep % source.count).pointee } step += 1 return result } } extension RandomGeneratorFromData { /// Use UUID as plain data to generate random value. convenience init(uuid: UUID) { self.init(data: (uuid as NSUUID).data()!) } } extension Array { public func shuffled(with generator: RandomGenerator) -> Array { var workingCopy = Array(self) var result = Array() self.forEach { _ in let rand: UInt = generator.rand() % UInt(workingCopy.count) result.append(workingCopy[Int(rand)]) workingCopy.remove(at: Int(rand)) } return result } } extension ZMConversation { /// Stable random list of the participants in the conversation. The list would be consistent between platforms /// because the conversation UUID is used as the random indexes source. var stableRandomParticipants: [ZMUser] { let allUsers = self.activeParticipants.array as! [ZMUser] guard let remoteIdentifier = self.remoteIdentifier else { return allUsers } let rand = RandomGeneratorFromData(uuid: remoteIdentifier) return allUsers.shuffled(with: rand) } } private enum Mode { /// 1-2 participants in conversation: /// / AA \ /// \ AA / case one /// 3-4 participants in conversation: /// / AB \ /// \ AB / case two /// 5+ participants in conversation: /// / AB \ /// \ CD / case four } extension Mode { fileprivate init(conversation: ZMConversation) { switch (conversation.activeParticipants.count, conversation.conversationType) { case (0...2, _), (_, .oneOnOne): self = .one case (3...5, _): self = .two default: self = .four } } } final public class ConversationListAvatarView: UIView { public var conversation: ZMConversation? = .none { didSet { guard let conversation = self.conversation else { self.clippingView.subviews.forEach { $0.removeFromSuperview() } return } let stableRandomParticipants = conversation.stableRandomParticipants.filter { !$0.isSelfUser } guard stableRandomParticipants.count > 0 else { self.clippingView.subviews.forEach { $0.removeFromSuperview() } return } self.accessibilityLabel = "Avatar for \(self.conversation?.displayName)" self.mode = Mode(conversation: conversation) var index: Int = 0 self.userImages().forEach { $0.userSession = ZMUserSession.shared() $0.size = .tiny $0.showInitials = (self.mode == .one) $0.isCircular = false $0.user = stableRandomParticipants[index] index += 1 } self.setNeedsLayout() } } private var mode: Mode = .two { didSet { self.clippingView.subviews.forEach { $0.removeFromSuperview() } self.userImages().forEach(self.clippingView.addSubview) if mode == .one { layer.borderWidth = 0 } else { layer.borderWidth = .hairline layer.borderColor = UIColor(white: 1, alpha: 0.24).cgColor } } } func userImages() -> [UserImageView] { switch mode { case .one: return [imageViewLeftTop] case .two: return [imageViewLeftTop, imageViewRightTop] case .four: return [imageViewLeftTop, imageViewRightTop, imageViewLeftBottom, imageViewRightBottom] } } let clippingView = UIView() let imageViewLeftTop = UserImageView() lazy var imageViewRightTop: UserImageView = { return UserImageView() }() lazy var imageViewLeftBottom: UserImageView = { return UserImageView() }() lazy var imageViewRightBottom: UserImageView = { return UserImageView() }() init() { super.init(frame: .zero) updateCornerRadius() backgroundColor = UIColor(white: 0, alpha: 0.16) layer.masksToBounds = true clippingView.clipsToBounds = true self.addSubview(clippingView) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func layoutSubviews() { super.layoutSubviews() guard self.bounds != .zero else { return } clippingView.frame = self.mode == .one ? self.bounds : self.bounds.insetBy(dx: 2, dy: 2) let size: CGSize let inset: CGFloat = 2 let containerSize = self.clippingView.bounds.size switch mode { case .one: size = CGSize(width: containerSize.width, height: containerSize.height) case .two: size = CGSize(width: (containerSize.width - inset) / 2.0, height: containerSize.height) case .four: size = CGSize(width: (containerSize.width - inset) / 2.0, height: (containerSize.height - inset) / 2.0) } var xPosition: CGFloat = 0 var yPosition: CGFloat = 0 self.userImages().forEach { $0.frame = CGRect(x: xPosition, y: yPosition, width: size.width, height: size.height) if xPosition + size.width >= containerSize.width { xPosition = 0 yPosition += size.height + inset } else { xPosition += size.width + inset } } updateCornerRadius() } private func updateCornerRadius() { layer.cornerRadius = self.conversation?.conversationType == .group ? 6 : layer.bounds.width / 2.0 clippingView.layer.cornerRadius = self.conversation?.conversationType == .group ? 4 : clippingView.layer.bounds.width / 2.0 } }
gpl-3.0
d8f04c1463e2934622ee7db10a3fd471
29.33195
131
0.603557
4.746753
false
false
false
false
mukeshthawani/UXMPDFKit
Pod/Classes/Form/PDFFormSignatureField.swift
1
9749
// // PDFFormFieldSignature.swift // Pods // // Created by Chris Anderson on 6/1/16. // // import UIKit open class PDFFormSignatureField: PDFFormField { open var name: String? fileprivate var signatureView: PDFFormFieldSignatureCaptureView? fileprivate var signatureOverlay: UIView? fileprivate let signatureExtraPadding: CGFloat = 22.0 lazy fileprivate var signButton:UIButton = { var button = UIButton(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) button.setTitle("Tap To Sign", for: UIControlState()) button.tintColor = UIColor.black button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0) button.setTitleColor(UIColor.black, for: UIControlState()) button.addTarget(self, action: #selector(PDFFormSignatureField.addSignature), for: .touchUpInside) button.isUserInteractionEnabled = true button.isExclusiveTouch = true return button }() lazy fileprivate var signImage:UIImageView = { var image = UIImageView(frame: CGRect( x: 0, y: -self.signatureExtraPadding, width: self.frame.width, height: self.frame.height + self.signatureExtraPadding * 2 ) ) image.contentMode = .scaleAspectFit image.backgroundColor = UIColor.clear return image }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(red: 0.7, green: 0.85, blue: 1.0, alpha: 0.7) addSubview(signImage) addSubview(signButton) bringSubview(toFront: signButton) } override open func removeFromSuperview() { removeSignatureBox() super.removeFromSuperview() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didSetValue(_ value: AnyObject?) { if let value = value as? UIImage { signImage.image = value } } func addSignature() { let bounds = UIScreen.main.bounds /// Overlay let view = UIView() view.frame = bounds view.backgroundColor = UIColor.white.withAlphaComponent(0.5) window?.addSubview(view) signatureOverlay = view let width = bounds.width let height = width / frame.width * frame.height + 44.0 + signatureExtraPadding * 2 if let window = UIApplication.shared.keyWindow { let signatureView = PDFFormFieldSignatureCaptureView(frame: CGRect( x: (bounds.width - width) / 2, y: bounds.height - height, width: width, height: height ) ) signatureView.delegate = self signatureView.layer.shadowColor = UIColor.black.cgColor signatureView.layer.shadowOpacity = 0.4 signatureView.layer.shadowRadius = 3.0 signatureView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0) window.addSubview(signatureView) self.signatureView = signatureView } } func removeSignatureBox() { if let signatureView = self.signatureView { signImage.image = signatureView.getSignature() value = signatureView.getSignature() delegate?.formFieldValueChanged(self) signatureOverlay?.removeFromSuperview() self.signatureView?.removeFromSuperview() self.signatureView = nil signButton.alpha = 0.0 } } override func renderInContext(_ context: CGContext) { var frame = self.frame frame.origin.y -= signatureExtraPadding frame.size.height += signatureExtraPadding * 2 signImage.image?.draw(in: frame) } } extension PDFFormSignatureField: PDFFormSignatureViewDelegate { func completedSignatureDrawing(_ field: PDFFormFieldSignatureCaptureView) { removeSignatureBox() } } protocol PDFFormSignatureViewDelegate { func completedSignatureDrawing(_ field: PDFFormFieldSignatureCaptureView) } class PDFFormFieldSignatureCaptureView: UIView { var delegate: PDFFormSignatureViewDelegate? // MARK: - Public properties var strokeWidth: CGFloat = 2.0 { didSet { path.lineWidth = strokeWidth } } var strokeColor: UIColor = UIColor.black { didSet { strokeColor.setStroke() } } var signatureBackgroundColor: UIColor = UIColor.white { didSet { backgroundColor = signatureBackgroundColor } } var containsSignature: Bool { get { if path.isEmpty { return false } else { return true } } } // MARK: - Private properties fileprivate var path = UIBezierPath() fileprivate var pts = [CGPoint](repeating: CGPoint(), count: 5) fileprivate var ctr = 0 lazy fileprivate var doneButton: UIBarButtonItem = UIBarButtonItem( title: "Done", style: .plain, target: self, action: #selector(PDFFormFieldSignatureCaptureView.finishSignature) ) lazy fileprivate var clearButton:UIBarButtonItem = UIBarButtonItem( title: "Clear", style: .plain, target: self, action: #selector(PDFFormFieldSignatureCaptureView.clearSignature) ) // MARK: - Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } override init(frame: CGRect) { super.init(frame: frame) setupUI() } func setupUI() { backgroundColor = signatureBackgroundColor path.lineWidth = strokeWidth path.lineJoinStyle = .round let spacerStart = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: self, action: nil) spacerStart.width = 10.0 let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) let spacerEnd = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: self, action: nil) spacerEnd.width = 10.0 let toolbar = UIToolbar(frame: CGRect(x: 0, y: frame.height - 44.0, width: frame.width, height: 44.0)) toolbar.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] toolbar.setItems([spacerStart, clearButton, spacer, doneButton, spacerEnd], animated: false) addSubview(toolbar) } // MARK: - Draw override func draw(_ rect: CGRect) { strokeColor.setStroke() path.stroke() } // MARK: - Touch handling functions override func touchesBegan(_ touches: Set <UITouch>, with event: UIEvent?) { if let firstTouch = touches.first { let touchPoint = firstTouch.location(in: self) ctr = 0 pts[0] = touchPoint } } override func touchesMoved(_ touches: Set <UITouch>, with event: UIEvent?) { if let firstTouch = touches.first { let touchPoint = firstTouch.location(in: self) ctr += 1 pts[ctr] = touchPoint if (ctr == 4) { pts[3] = CGPoint(x: (pts[2].x + pts[4].x)/2.0, y: (pts[2].y + pts[4].y)/2.0) path.move(to: pts[0]) path.addCurve(to: pts[3], controlPoint1: pts[1], controlPoint2: pts[2]) setNeedsDisplay() pts[0] = pts[3] pts[1] = pts[4] ctr = 1 } setNeedsDisplay() } } override func touchesEnded(_ touches: Set <UITouch>, with event: UIEvent?) { if ctr == 0 { let touchPoint = pts[0] path.move(to: CGPoint(x: touchPoint.x-1.0,y: touchPoint.y)) path.addLine(to: CGPoint(x: touchPoint.x+1.0,y: touchPoint.y)) setNeedsDisplay() } else { ctr = 0 } } // MARK: - Methods for interacting with Signature View // Clear the Signature View func clearSignature() { path.removeAllPoints() setNeedsDisplay() } func finishSignature() { delegate?.completedSignatureDrawing(self) } // Save the Signature as an UIImage func getSignature(scale: CGFloat = 1) -> UIImage? { if !containsSignature { return nil } var bounds = self.bounds.size bounds.height = bounds.height - 44.0 UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, scale) path.stroke() let signature = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return signature } func getSignatureCropped(scale: CGFloat = 1) -> UIImage? { guard let fullRender = getSignature(scale:scale) else { return nil } let bounds = scaleRect(path.bounds.insetBy(dx: -strokeWidth/2, dy: -strokeWidth/2), byFactor: scale) guard let imageRef = fullRender.cgImage?.cropping(to: bounds) else { return nil } return UIImage(cgImage: imageRef) } func scaleRect(_ rect: CGRect, byFactor factor: CGFloat) -> CGRect { var scaledRect = rect scaledRect.origin.x *= factor scaledRect.origin.y *= factor scaledRect.size.width *= factor scaledRect.size.height *= factor return scaledRect } }
mit
8e31f8a2109024d991c49a9bc9837952
30.652597
110
0.590009
4.790663
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV2/Models/MessageContextSkill.swift
1
1841
/** * (C) Copyright IBM Corp. 2019, 2022. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import IBMSwiftSDKCore /** Contains information specific to a particular skill used by the assistant. The property name must be the same as the name of the skill (for example, `main skill`). */ public struct MessageContextSkill: Codable, Equatable { /** Arbitrary variables that can be read and written by a particular skill. */ public var userDefined: [String: JSON]? /** System context data used by the skill. */ public var system: MessageContextSkillSystem? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case userDefined = "user_defined" case system = "system" } /** Initialize a `MessageContextSkill` with member variables. - parameter userDefined: Arbitrary variables that can be read and written by a particular skill. - parameter system: System context data used by the skill. - returns: An initialized `MessageContextSkill`. */ public init( userDefined: [String: JSON]? = nil, system: MessageContextSkillSystem? = nil ) { self.userDefined = userDefined self.system = system } }
apache-2.0
190fbf34c0a57fe7a85abf44f0ccf964
30.20339
117
0.693102
4.534483
false
false
false
false
sora0077/AppleMusicKit
Sources/Request/FetchRecommendations.swift
1
5667
// // FetchRecommendations.swift // AppleMusicKit // // Created by 林 達也 on 2017/07/05. // Copyright © 2017年 jp.sora0077. All rights reserved. // import Foundation // MARK: - GetDefaultRecommendations public struct GetDefaultRecommendations< Recommendation: RecommendationDecodable, Song: SongDecodable, Album: AlbumDecodable, Artist: ArtistDecodable, MusicVideo: MusicVideoDecodable, Playlist: PlaylistDecodable, Curator: CuratorDecodable, AppleCurator: AppleCuratorDecodable, Activity: ActivityDecodable, Station: StationDecodable, Storefront: StorefrontDecodable, Genre: GenreDecodable >: PaginatorResourceRequest, InternalPaginatorRequest { public typealias Resource = AppleMusicKit.Resource<Recommendation, Relationships> public var scope: AccessScope { return .user } public let path: String public var parameters: [String: Any]? { return makePaginatorParameters(_parameters, request: self) } public internal(set) var limit: Int? public let offset: Int? private let _parameters: [String: Any] public init(type: ResourceType? = nil, language: Storefront.Language? = nil, limit: Int? = nil, offset: Int? = nil) { assert(type?.contains(in: .albums, .playlists) ?? true) self.init(path: "/v1/me/recommendations", parameters: ["type": type?.rawValue, "l": language?.languageTag, "limit": limit, "offset": offset].cleaned) } init(path: String, parameters: [String: Any]) { self.path = path _parameters = parameters (limit, offset) = parsePaginatorParameters(parameters) } } extension GetDefaultRecommendations { public struct Relationships: Decodable { public let contents: [AnyResource<NoRelationships>]? public let recommendations: [Resource]? public typealias AnyResource<R: Decodable> = AppleMusicKit.AnyResource< Song, Album, Artist, MusicVideo, Playlist, Curator, AppleCurator, Activity, Station, Storefront, Genre, Recommendation, R> } } // MARK: - GetRecommendation public struct GetRecommendation< Recommendation: RecommendationDecodable, Song: SongDecodable, Album: AlbumDecodable, Artist: ArtistDecodable, MusicVideo: MusicVideoDecodable, Playlist: PlaylistDecodable, Curator: CuratorDecodable, AppleCurator: AppleCuratorDecodable, Activity: ActivityDecodable, Station: StationDecodable, Storefront: StorefrontDecodable, Genre: GenreDecodable >: PaginatorResourceRequest, InternalPaginatorRequest { public typealias Relationships = GetDefaultRecommendations<Recommendation, Song, Album, Artist, MusicVideo, Playlist, Curator, AppleCurator, Activity, Station, Storefront, Genre>.Relationships public typealias Resource = AppleMusicKit.Resource<Recommendation, Relationships> public var scope: AccessScope { return .user } public let path: String public var parameters: [String: Any]? { return makePaginatorParameters(_parameters, request: self) } public internal(set) var limit: Int? public let offset: Int? private let _parameters: [String: Any] public init(id: Recommendation.Identifier, language: Storefront.Language? = nil, limit: Int? = nil, offset: Int? = nil) { self.init(path: "/v1/me/recommendations/\(id)", parameters: ["l": language?.languageTag, "limit": limit, "offset": offset].cleaned) } init(path: String, parameters: [String: Any]) { self.path = path _parameters = parameters (limit, offset) = parsePaginatorParameters(parameters) } } // MARK: - GetMultipleRecommendations public struct GetMultipleRecommendations< Recommendation: RecommendationDecodable, Song: SongDecodable, Album: AlbumDecodable, Artist: ArtistDecodable, MusicVideo: MusicVideoDecodable, Playlist: PlaylistDecodable, Curator: CuratorDecodable, AppleCurator: AppleCuratorDecodable, Activity: ActivityDecodable, Station: StationDecodable, Storefront: StorefrontDecodable, Genre: GenreDecodable >: PaginatorResourceRequest, InternalPaginatorRequest { public typealias Relationships = GetRecommendation<Recommendation, Song, Album, Artist, MusicVideo, Playlist, Curator, AppleCurator, Activity, Station, Storefront, Genre>.Relationships public typealias Resource = AppleMusicKit.Resource<Recommendation, Relationships> public var scope: AccessScope { return .user } public let path: String public var parameters: [String: Any]? { return makePaginatorParameters(_parameters, request: self) } public internal(set) var limit: Int? public let offset: Int? private let _parameters: [String: Any] public init(id: Recommendation.Identifier, _ additions: Recommendation.Identifier..., language: Storefront.Language? = nil, limit: Int? = nil, offset: Int? = nil) { self.init(ids: [id] + additions, language: language, limit: limit, offset: offset) } public init(ids: [Recommendation.Identifier], language: Storefront.Language? = nil, limit: Int? = nil, offset: Int? = nil) { self.init(path: "/v1/me/recommendations", parameters: ["ids": makeIds(ids), "l": language?.languageTag, "limit": limit, "offset": offset].cleaned) } init(path: String, parameters: [String: Any]) { self.path = path _parameters = parameters (limit, offset) = parsePaginatorParameters(parameters) } }
mit
a9707ad43fb59a1df159860660987e25
36.470199
196
0.689996
4.533654
false
false
false
false
luismatute/MemeMe
MemeMeApp/MemeCollectionViewController.swift
1
4095
// // MemeCollectionViewController.swift // MemeMeApp // // Created by Luis Matute on 4/13/15. // Copyright (c) 2015 Luis Matute. All rights reserved. // import Foundation import UIKit class MemeCollectionViewController: UICollectionViewController, UICollectionViewDataSource { // MARK: - // MARK: Properties var memes: [Meme]! let applicationDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // MARK: - // MARK: View's Life Cycle override func viewDidLoad() { super.viewDidLoad() self.updateMemes() self.tabBarController?.tabBar.tintColor = UIColor(red: 46/255, green: 189/255, blue: 89/255, alpha: 1.0) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.updateMemes() self.tabBarController?.tabBar.hidden = false self.collectionView?.reloadData() // Setting 3 cells per row let width = CGRectGetWidth(self.collectionView!.frame) / 3 let layout = self.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: width, height: width) } override func viewDidAppear(animated: Bool) { if (self.memes.count == 0) { self.showEditor() } } // MARK: - // MARK: Collection View Data Source Protocol override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.memes.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Instantiating Reusable Cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier("memeContentCell", forIndexPath: indexPath) as! MemeCollectionViewCell // Get the meme for this row let meme = self.memes[indexPath.row] // Set the cell properties cell.imageView?.image = meme.memedImage cell._id = meme._id cell.meme = meme cell.vc = self // Return the cell return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // Instantiating the Meme Detail VC let memeDetailVC = self.storyboard?.instantiateViewControllerWithIdentifier("memeDetailVC") as! MemeDetailViewController // Getting the meme selected memeDetailVC.meme = self.memes[indexPath.row] // Pushing the memeDetailVC to the navigation stack self.navigationController?.pushViewController(memeDetailVC, animated: true) } override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { let editMI = UIMenuItem(title: "Edit", action: "editAction:") let deleteMI = UIMenuItem(title: "Delete", action: "deleteAction:") UIMenuController.sharedMenuController().menuItems = [deleteMI,editMI] return true } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) -> Bool { return true } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) {} // MARK: - // MARK: Actions @IBAction func addMeme(sender: AnyObject) { self.showEditor() } // MARK: - // MARK: Methods func updateMemes() { // Set memes to whatever is on the app delegate self.memes = applicationDelegate.memes } func showEditor() { // Getting the instance of the editor VC let editorVC = self.storyboard?.instantiateViewControllerWithIdentifier("editorVC") as! MemeEditorViewController // Showing the editorVC self.presentViewController(editorVC, animated: true, completion: nil) } }
mit
5f5e748515eefc552ff49273110d5edc
37.632075
185
0.682051
5.290698
false
false
false
false
jihun-kang/ios_a2big_sdk
A2bigSDK/LookMonumentData.swift
1
901
// // LookMonument.swift // nextpage // // Created by a2big on 2016. 11. 12.. // Copyright © 2016년 a2big. All rights reserved. // //import SwiftyJSON public class LookMonumentData { public var monument_no: String! public var monument_name: String! public var media_no: String! public var character_no: String! public var monument_ment: String! public var imageArr:[JSON] required public init(json: JSON, baseUrl:String) { monument_no = json["monument_no"].stringValue monument_name = json["monument_name"].stringValue media_no = baseUrl+json["media_no"].stringValue.replacingOccurrences(of: "./", with: "") character_no = json["character_no"].stringValue monument_ment = json["monument_ment"].stringValue imageArr = json["image_list"].arrayValue ///name = json["image_list"].arrayObject } }
apache-2.0
ad2f24a924f0a5494ffe3e272c11a17f
31.071429
96
0.652561
3.821277
false
false
false
false
michaelcordero/CoreDataStructures
Sources/CoreDataStructures/AVLTree.swift
1
2148
// // AVLTree.swift // CoreDataStructures // // Created by Michael Cordero on 1/2/21. // import Foundation /// Height-Balance Property: for every internal node of Tree, /// the heights of the children of said internal node differ /// by at most 1. /// source: Data Structures & Algorithms, 5th edition /// by Michael T Goodrich & Roberto Tamassia. /// Ch. 10, AVL Trees /// AVLTrees inherit size, isEmpty and get from BST, but overrides put & remove open class AVLTree<T: Comparable> : BinarySearchTree<T> { /// Node Class adds height property open class AVLNode<T: Comparable> : Node<T> { // MARK: - Properties var height: Int override init() { self.height = 0 super.init() } override init(value: T?) { self.height = 0 super.init(value: value) } override init(value: T?, left: Node<T>?, right: Node<T>?, parent: Node<T>?) { self.height = 0 super.init(value: value, left: left, right: right, parent: parent) if left != nil { let left_child: AVLNode<T> = AVLNode(value: self.left?.value, left: self.left?.left, right: self.left?.right, parent: self.left?.parent) height = Swift.max(height, left_child.height ) self.left = left_child } if right != nil { let right_child: AVLNode<T> = AVLNode(value: self.right?.value, left: self.right?.left, right: self.right?.right, parent: self.right?.parent) self.right = right height = Swift.max(height, 1 + right_child.height ) } } init(_ node: Node<T>){ self.height = 0 super.init(value: node.value, left: node.left, right: node.right, parent: node.parent) } } override public func put(_ value: T) throws { try super.put(value) balance() } override public func remove(_ value: T) throws -> Node<T>? { let old_value: Node<T>? = try super.remove(value) balance() return old_value } }
mit
177e6f1ab24fe71fcf56344a870dbe27
30.588235
157
0.561918
3.877256
false
false
false
false
WickedColdfront/Slide-iOS
Slide for Reddit/ReplyViewController.swift
1
39133
// // ReplyViewController.swift // Slide for Reddit // // Created by Carlos Crane on 1/10/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import UIKit import reddift import Photos import ImagePickerSheetController import Alamofire import MobileCoreServices import SwiftyJSON import ActionSheetPicker_3_0 import RealmSwift import MaterialComponents.MaterialSnackbar class ReplyViewController: UITableViewController, UITextViewDelegate { var toReplyTo: Object? var text: UITextView? var subjectCell = InputCell() var recipientCell = InputCell() var message = false var sub: String var scrollView: UIScrollView? var reply: (Comment?) -> Void = {(comment) in } var replyS: (Link?) -> Void = {(link) in } var edit = false var header: UIView? override func numberOfSections(in tableView: UITableView) -> Int { return message ? 1 : 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch(indexPath.section) { case 0: switch(indexPath.row) { case 0: return self.subjectCell case 1: return self.recipientCell default: fatalError("Unknown row in section 0") } default: fatalError("Unknown section") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if(message){ return 2 } else { return 0 } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } init(message: RMessage?, completion: @escaping (Message?) -> Void){ self.toReplyTo = message self.message = true self.sub = "" super.init(nibName: nil, bundle: nil) self.reply = {(comment) in DispatchQueue.main.async { //todo check failed completion(nil) self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: nil) }) } } } init(thing: Object, sub: String, editing: Bool, completion: @escaping (Comment?) -> Void){ self.toReplyTo = thing self.edit = true self.sub = sub super.init(nibName: nil, bundle: nil) self.reply = {(comment) in DispatchQueue.main.async { if(comment == nil){ self.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your message has not been edited (but has been saved as a draft), please try again", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { completion(comment) self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: nil) }) } } } } init(submission: RSubmission, sub: String, editing: Bool, completion: @escaping (Link?) -> Void){ self.toReplyTo = submission self.edit = true self.sub = sub super.init(nibName: nil, bundle: nil) self.replyS = {(link) in DispatchQueue.main.async { if(link == nil){ self.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your submission has not been edited (but has been saved as a draft), please try again", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { completion(link) self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: nil) }) } } } } init(thing: Object, sub: String, view: UIView?, completion: @escaping (Comment?) -> Void){ self.toReplyTo = thing self.sub = sub self.header = view super.init(nibName: nil, bundle: nil) self.reply = {(comment) in DispatchQueue.main.async { if(comment == nil){ self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your message has not been sent (but has been saved as a draft), please try again", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { completion(comment) self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: nil) }) } } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillDisappear(_ animated: Bool) { unregisterKeyboardNotifications() } override func viewDidLoad() { super.viewDidLoad() text?.becomeFirstResponder() addToolbarToTextView() self.view.layer.cornerRadius = 5 self.view.layer.masksToBounds = true } func addToolbarToTextView(){ let scrollView = TouchUIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: text!.frame.size.width, height: 50)) scrollView.contentSize = CGSize.init(width: 50 * 11, height: 50) scrollView.autoresizingMask = .flexibleWidth scrollView.backgroundColor = ColorUtil.backgroundColor var i = 0 for button in ([ generateButtons(image: "save", action: #selector(ReplyViewController.saveDraft(_:))), generateButtons(image: "folder", action: #selector(ReplyViewController.openDrafts(_:))), generateButtons(image: "image", action: #selector(ReplyViewController.uploadImage(_:))), generateButtons(image: "draw", action: #selector(ReplyViewController.draw(_:))), generateButtons(image: "link", action: #selector(ReplyViewController.link(_:))), generateButtons(image: "bold", action: #selector(ReplyViewController.bold(_:))), generateButtons(image: "italic", action: #selector(ReplyViewController.italics(_:))), generateButtons(image: "list", action: #selector(ReplyViewController.list(_:))), generateButtons(image: "list_number", action: #selector(ReplyViewController.numberedList(_:))), generateButtons(image: "size", action: #selector(ReplyViewController.size(_:))), generateButtons(image: "strikethrough", action: #selector(ReplyViewController.strike(_:)))]) { button.0.frame = CGRect.init(x: i * 50, y: 0, width: 50, height: 50) button.0.isUserInteractionEnabled = true button.0.addTarget(self, action: button.1, for: UIControlEvents.touchUpInside) scrollView.addSubview(button.0) i += 1 } scrollView.delaysContentTouches = false text!.inputAccessoryView = scrollView } func generateButtons(image: String, action: Selector) -> (UIButton, Selector) { let more = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 50)) more.setImage(UIImage.init(named: image)?.withColor(tintColor: ColorUtil.fontColor).imageResize(sizeChange: CGSize.init(width: 25, height: 25)), for: UIControlState.normal) return (more, action) } func wrapIn(_ value: String){ text!.replace(text!.selectedTextRange!, withText: value + text!.text(in: text!.selectedTextRange!)! + value) } func replaceIn(_ value: String, with: String){ text!.replace(text!.selectedTextRange!, withText: with + text!.text(in: text!.selectedTextRange!)!.replacingOccurrences(of: value, with: with)) } func saveDraft(_ sender: AnyObject){ if let toSave = text!.text { if(!toSave.isEmpty()){ Drafts.addDraft(s: text!.text) let message = MDCSnackbarMessage() message.text = "Draft saved" MDCSnackbarManager.show(message) } } } var picker: ActionSheetStringPicker? func openDrafts(_ sender: AnyObject){ print("Opening drafts") if(Drafts.drafts.isEmpty){ self.view.makeToast("No drafts found", duration: 4, position: .top) } else { picker = ActionSheetStringPicker(title: "Choose a draft", rows: Drafts.drafts, initialSelection: 0, doneBlock: { (picker, index, value) in self.text!.insertText(Drafts.drafts[index] as String) }, cancel: { (picker) in return }, origin: text!) let doneButton = UIBarButtonItem.init(title: "Insert", style: .done, target: nil, action: nil) picker?.setDoneButton(doneButton) //todo picker?.addCustomButton(withTitle: "Delete", target: self, selector: #selector(ReplyViewController.doDelete(_:))) picker?.show() } } func doDelete(_ sender: AnyObject){ Drafts.deleteDraft(s: Drafts.drafts[(picker?.selectedIndex)!] as String) self.openDrafts(sender) } func uploadImage(_ sender: UIButton!){ let presentImagePickerController: (UIImagePickerControllerSourceType) -> () = { source in let controller = UIImagePickerController() controller.delegate = self var sourceType = source if (!UIImagePickerController.isSourceTypeAvailable(sourceType)) { sourceType = .photoLibrary print("Fallback to camera roll as a source since the simulator doesn't support taking pictures") } controller.sourceType = sourceType self.present(controller, animated: true, completion: nil) } let controller = ImagePickerSheetController(mediaType: .imageAndVideo) controller.delegate = self controller.addAction(ImagePickerAction(title: NSLocalizedString("Photo Library", comment: "Action Title"), secondaryTitle: { NSString.localizedStringWithFormat(NSLocalizedString("Upload", comment: "Action Title") as NSString, $0) as String}, handler: { _ in presentImagePickerController(.photoLibrary) }, secondaryHandler: { _, numberOfPhotos in self.uploadAsync(controller.selectedAssets) })) controller.addAction(ImagePickerAction(cancelTitle: NSLocalizedString("Cancel", comment: "Action Title"))) if UIDevice.current.userInterfaceIdiom == .pad { controller.modalPresentationStyle = .popover controller.popoverPresentationController?.sourceView = view controller.popoverPresentationController?.sourceRect = CGRect(origin: view.center, size: CGSize()) } present(controller, animated: true, completion: nil) } var progressBar = UIProgressView() var alertView: UIAlertController? func uploadAsync(_ assets: [PHAsset]){ alertView = UIAlertController(title: "Uploading...", message: "Your images are uploading to Imgur", preferredStyle: .alert) alertView!.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alertView!, animated: true, completion: { // Add your progressbar after alert is shown (and measured) let margin:CGFloat = 8.0 let rect = CGRect.init(x: margin, y: 72.0, width: (self.alertView?.view.frame.width)! - margin * 2.0 , height: 2.0) self.progressBar = UIProgressView(frame: rect) self.progressBar.progress = 0 self.progressBar.tintColor = ColorUtil.accentColorForSub(sub: self.sub) self.alertView?.view.addSubview(self.progressBar) }) if assets.count > 1 { Alamofire.request("https://api.imgur.com/3/album", method: .post, parameters: nil, encoding: JSONEncoding.default, headers: ["Authorization": "Client-ID bef87913eb202e9"]) .responseJSON { response in print(response) if let status = response.response?.statusCode { switch(status){ case 201: print("example success") default: print("error with response status: \(status)") } } if let result = response.value { let json = JSON(result) print(json) let album = json["data"]["deletehash"].stringValue let url = "https://imgur.com/a/" + json["data"]["id"].stringValue self.uploadImages(assets, album: album, completion: { (last) in DispatchQueue.main.async { self.alertView!.dismiss(animated: true, completion: { if last != "Failure" { let alert = UIAlertController(title: "Link text", message: url, preferredStyle: .alert) alert.addTextField { (textField) in textField.text = "" } alert.addAction(UIAlertAction(title: "Insert", style: .default, handler: { (action) in let textField = alert.textFields![0] // Force unwrapping because we know it exists. self.text!.insertText("[\(textField.text!)](\(url))") })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Uploading failed", message: "Uh oh, something went wrong while uploading to Imgur. Please try again in a few minutes", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } }) } }) } } } else { uploadImages(assets, album: "", completion: { (link) in DispatchQueue.main.async { self.alertView!.dismiss(animated: true, completion: { if link != "Failure" { let alert = UIAlertController(title: "Link text", message: link, preferredStyle: .alert) alert.addTextField { (textField) in textField.text = "" } alert.addAction(UIAlertAction(title: "Insert", style: .default, handler: { (action) in let textField = alert.textFields![0] // Force unwrapping because we know it exists. self.text!.insertText("[\(textField.text!)](\(link))") })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Uploading failed", message: "Uh oh, something went wrong while uploading to Imgur. Please try again in a few minutes", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } }) } }) } } func uploadImages(_ assets: [PHAsset], album: String, completion: @escaping (String) -> Void ){ var count = 0 for image in assets { count += 1 let parameters = [:] as [String: String]//todo albums var name = UUID.init().uuidString PHImageManager.default().requestImageData(for: image, options: nil, resultHandler: { (data, uti, _, info) in if let fileName = (info?["PHImageFileURLKey"] as? NSURL)?.lastPathComponent { name = fileName } let mime = UTTypeCopyPreferredTagWithClass(uti! as CFString, kUTTagClassMIMEType)?.takeRetainedValue() Alamofire.upload(multipartFormData: { (multipartFormData) in multipartFormData.append(data!, withName: "image", fileName: name, mimeType: mime! as String) for (key, value) in parameters { multipartFormData.append((value.data(using: .utf8))!, withName: key) } if(!album.isEmpty){ multipartFormData.append(album.data(using: .utf8)!, withName: "album") } }, to: "https://api.imgur.com/3/image", method: .post, headers: ["Authorization": "Client-ID bef87913eb202e9"], encodingCompletion: { (encodingResult) in switch encodingResult { case .success(let upload, _, _): print("Success") upload.uploadProgress { progress in DispatchQueue.main.async { print(progress.fractionCompleted) self.progressBar.setProgress(Float(progress.fractionCompleted), animated: true) } } upload.responseJSON { response in debugPrint(response) let link = JSON(response.value!)["data"]["link"].stringValue print("Link is \(link)") if(count == assets.count){ completion(link) } } case .failure: completion("Failure") } }) }) } } func draw(_ sender: UIButton!){ } func link(_ sender: UIButton!){ } func bold(_ sender: UIButton!){ wrapIn("*") } func italics(_ sender: UIButton!){ wrapIn("**") } func list(_ sender: UIButton!){ replaceIn("\n", with: "\n* ") } func numberedList(_ sender: UIButton!){ replaceIn("\n", with: "\n1. ") } func size(_ sender: UIButton!){ replaceIn("\n", with: "\n#") } func strike(_ sender: UIButton!){ wrapIn("~~") } func registerKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(ReplyViewController.keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ReplyViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func unregisterKeyboardNotifications() { NotificationCenter.default.removeObserver(self) } func keyboardDidShow(notification: NSNotification) { let userInfo: NSDictionary = notification.userInfo! as NSDictionary let keyboardInfo = userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue let keyboardSize = keyboardInfo.cgRectValue.size // Get the existing contentInset for the scrollView and set the bottom property to be the height of the keyboard var contentInset = self.scrollView?.contentInset contentInset?.bottom = keyboardSize.height self.scrollView?.contentInset = contentInset! self.scrollView?.scrollIndicatorInsets = contentInset! } func keyboardWillHide(notification: NSNotification) { var contentInset = self.scrollView?.contentInset contentInset?.bottom = 0 self.scrollView?.contentInset = contentInset! self.scrollView?.scrollIndicatorInsets = UIEdgeInsets.zero } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = ColorUtil.getColorForSub(sub: sub) navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] navigationController?.navigationBar.tintColor = UIColor.white if(message){ title = "New message" } else { let author = (toReplyTo is RComment) ? ((toReplyTo as! RComment).author) : ((toReplyTo as! RSubmission).author) if(edit){ title = "Editing" } else { title = "Reply to \(author)" } } let close = UIButton.init(type: .custom) close.setImage(UIImage.init(named: "close"), for: UIControlState.normal) close.addTarget(self, action: #selector(self.close(_:)), for: UIControlEvents.touchUpInside) close.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30) let closeB = UIBarButtonItem.init(customView: close) navigationItem.leftBarButtonItems = [closeB] let send = UIButton.init(type: .custom) send.setImage(UIImage.init(named: "send"), for: UIControlState.normal) send.addTarget(self, action: #selector(self.send(_:)), for: UIControlEvents.touchUpInside) send.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) let sendB = UIBarButtonItem.init(customView: send) navigationItem.rightBarButtonItem = sendB registerKeyboardNotifications() } func close(_ sender: AnyObject){ presentingViewController?.dismiss(animated: true, completion: nil) } var alertController: UIAlertController? var session: Session? var comment: Comment? func getCommentEdited(_ name: String){ do { try self.session?.getInfo([name], completion: { (res) in switch res { case .failure: print(res.error ?? "Error?") case .success(let listing): if listing.children.count == 1 { if let comment = listing.children[0] as? Comment { self.comment = comment self.reply(self.comment) } } } }) } catch { } } func getSubmissionEdited(_ name: String){ do { try self.session?.getInfo([name], completion: { (res) in switch res { case .failure: print(res.error ?? "Error?") case .success(let listing): if listing.children.count == 1 { if let submission = listing.children[0] as? Link { self.replyS(submission) } } } }) } catch { } } func send(_ sender: AnyObject){ if(message){ alertController = UIAlertController(title: nil, message: "Sending message...\n\n", preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = UIColor.black spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!,animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session if(toReplyTo == nil){ do { try self.session?.composeMessage(recipientCell.cellLabel.text!, subject: subjectCell.cellLabel.text!, text: text!.text, completion: { (result) in switch result { case .failure(let error): print(error.description) self.reply(nil) case .success( _): self.reply(self.comment) } }) } catch { print((error as NSError).description) } } else { do { let name = toReplyTo is RMessage ? (toReplyTo as! RMessage).getId() : toReplyTo is RComment ? (toReplyTo as! RComment).getId() : (toReplyTo as! RSubmission).getId() try self.session?.replyMessage(text!.text, parentName:name, completion: { (result) -> Void in switch result { case .failure(let error): print(error.description) self.reply(nil) case .success( _): self.reply(self.comment) } }) } catch { print((error as NSError).description) } } } else if(edit){ if(toReplyTo is RSubmission){ alertController = UIAlertController(title: nil, message: "Editing submission...\n\n", preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = UIColor.black spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!,animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session do { let name = toReplyTo is RMessage ? (toReplyTo as! RMessage).getId() : toReplyTo is RComment ? (toReplyTo as! RComment).getId() : (toReplyTo as! RSubmission).getId() try self.session?.editCommentOrLink(name, newBody: text!.text, completion: { (result) in self.getSubmissionEdited(name) }) } catch { print((error as NSError).description) } } else { alertController = UIAlertController(title: nil, message: "Editing comment...\n\n", preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = UIColor.black spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!,animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session do { let name = toReplyTo is RMessage ? (toReplyTo as! RMessage).getId() : toReplyTo is RComment ? (toReplyTo as! RComment).getId() : (toReplyTo as! RSubmission).getId() try self.session?.editCommentOrLink(name, newBody: text!.text, completion: { (result) in self.getCommentEdited(name) }) } catch { print((error as NSError).description) } } } else { alertController = UIAlertController(title: nil, message: "Sending reply...\n\n", preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = UIColor.black spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!,animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session do { let name = toReplyTo is RMessage ? (toReplyTo as! RMessage).getId() : toReplyTo is RComment ? (toReplyTo as! RComment).getId() : (toReplyTo as! RSubmission).getId() try self.session?.postComment(text!.text, parentName:name, completion: { (result) -> Void in switch result { case .failure(let error): print(error.description) self.reply(nil) case .success(let postedComment): self.comment = postedComment self.reply(self.comment) } }) } catch { print((error as NSError).description) } } } override func loadView() { super.loadView() self.tableView.backgroundColor = ColorUtil.backgroundColor text = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: self.tableView.frame.size.width, height: 500)) text?.isEditable = true text?.backgroundColor = ColorUtil.foregroundColor text?.textColor = ColorUtil.fontColor text?.delegate = self text?.font = UIFont.systemFont(ofSize: 18) if(edit){ if(toReplyTo is RComment){ text!.text = (toReplyTo as! RComment).body } else { text!.text = (toReplyTo as! RSubmission).body } } let lineView = UIView(frame: CGRect.init(x: 0, y: 0, width: (text?.frame.size.width)!, height: 1)) lineView.backgroundColor = ColorUtil.backgroundColor text?.addSubview(lineView) subjectCell = InputCell.init(frame: CGRect.init(x: 0, y: 0, width: self.tableView.frame.size.width, height: 70), input: "[menu]Subject") recipientCell = InputCell.init(frame: CGRect.init(x: 0, y: 0, width: self.tableView.frame.size.width, height: 70), input: "[profile]Recipient") if(toReplyTo != nil && message){ subjectCell.cellLabel.text = "re: " + (toReplyTo as! RMessage).subject subjectCell.cellLabel.isEditable = false recipientCell.cellLabel.text = (toReplyTo as! RMessage).author recipientCell.cellLabel.isEditable = false } tableView.tableFooterView = text if(header != nil){ tableView.tableHeaderView = header } } func dismiss(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension UIView { func embedInScrollView()->UIView{ let cont=UIScrollView() self.translatesAutoresizingMaskIntoConstraints = false; cont.translatesAutoresizingMaskIntoConstraints = false; cont.addSubview(self) cont.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[innerView]|", options: NSLayoutFormatOptions(rawValue:0),metrics: nil, views: ["innerView":self])) cont.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[innerView]|", options: NSLayoutFormatOptions(rawValue:0),metrics: nil, views: ["innerView":self])) cont.addConstraint(NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: cont, attribute: .width, multiplier: 1.0, constant: 0)) return cont } } extension ReplyViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } extension ReplyViewController: ImagePickerSheetControllerDelegate { func controllerWillEnlargePreview(_ controller: ImagePickerSheetController) { print("Will enlarge the preview") } func controllerDidEnlargePreview(_ controller: ImagePickerSheetController) { print("Did enlarge the preview") } func controller(_ controller: ImagePickerSheetController, willSelectAsset asset: PHAsset) { print("Will select an asset") } func controller(_ controller: ImagePickerSheetController, didSelectAsset asset: PHAsset) { print("Did select an asset") } func controller(_ controller: ImagePickerSheetController, willDeselectAsset asset: PHAsset) { print("Will deselect an asset") } func controller(_ controller: ImagePickerSheetController, didDeselectAsset asset: PHAsset) { print("Did deselect an asset") } } class InputCell: UITableViewCell { var cellLabel: UITextView! init(frame: CGRect, input: String) { super.init(style: UITableViewCellStyle.default, reuseIdentifier: "cell") cellLabel = UITextView(frame: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: 70)) cellLabel.textColor = ColorUtil.fontColor cellLabel.font = FontGenerator.boldFontOfSize(size: 16, submission: true) cellLabel.placeholder = input cellLabel.textContainerInset = UIEdgeInsets.init(top: 30, left: 10, bottom: 0, right: 0) backgroundColor = ColorUtil.foregroundColor addSubview(cellLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } } extension UITextView: UITextViewDelegate { // Placeholder text var placeholder: String? { get { // Get the placeholder text from the label var placeholderText: String? if let placeHolderLabel = self.viewWithTag(100) as? UILabel { placeholderText = placeHolderLabel.text } return placeholderText } set { // Store the placeholder text in the label let placeHolderLabel = self.viewWithTag(100) as! UILabel? if placeHolderLabel == nil { // Add placeholder label to text view self.addPlaceholderLabel(placeholderText: newValue!) } else { placeHolderLabel?.text = newValue placeHolderLabel?.sizeToFit() } } } // Hide the placeholder label if there is no text // in the text viewotherwise, show the label public func textViewDidChange(textView: UITextView) { let placeHolderLabel = self.viewWithTag(100) if !self.hasText { // Get the placeholder label placeHolderLabel?.isHidden = false } else { placeHolderLabel?.isHidden = true } } // Add a placeholder label to the text view func addPlaceholderLabel(placeholderText: String) { // Create the label and set its properties let placeholderLabel = UILabel() let placeholderImage = placeholderText.startsWith("[") ? placeholderText.substring(1, length: placeholderText.indexOf("]")! - 1) : "" var text = placeholderText if(!placeholderImage.isEmpty){ text = text.substring(placeholderText.indexOf("]")! + 1, length: text.length - placeholderText.indexOf("]")! - 1) } placeholderLabel.text = " " + text placeholderLabel.frame.origin.x = 10 placeholderLabel.frame.origin.y = 5 placeholderLabel.font = UIFont.systemFont(ofSize: 14) placeholderLabel.textColor = ColorUtil.fontColor.withAlphaComponent(0.8) placeholderLabel.tag = 100 if(!placeholderImage.isEmpty){ placeholderLabel.addImage(imageName: placeholderImage) } placeholderLabel.sizeToFit() // Hide the label if there is text in the text view placeholderLabel.isHidden = ((self.text.length) > 0) self.addSubview(placeholderLabel) self.delegate = self; } }
apache-2.0
7550f5370fbea062d084fac1578ef39f
42.48
265
0.55737
5.38415
false
false
false
false
dsay/POPDataSources
Sources/POPDataSources/TableViewDataSource+Composed.swift
1
5930
import UIKit /** * Composed Data Source */ open class ComposedDataSource: TableViewDataSource, DataSourcesContainable { public var dataSources: [TableViewDataSource] = [] public subscript(i: Int) -> TableViewDataSource { get { return dataSources[i] } set { dataSources[i] = newValue } } public init(_ dataSources: [TableViewDataSource] = []) { self.dataSources = dataSources } } /** * Base protocol */ public protocol DataSourcesContainable { typealias DataSource = TableViewDataSource var dataSources: [TableViewDataSource] { get } func numberOfSections() -> Int func dataSource(at index: Int) -> DataSource } public extension DataSourcesContainable { func numberOfSections() -> Int { return dataSources.count } func dataSource(at index: Int) -> DataSource { guard index >= 0 && index < numberOfSections() else { fatalError("Index out of bounds") } return self.dataSources[index] } } /** * Composed Data Source */ public extension TableViewDataSource where Self: DataSourcesContainable { func numberOfSections(for tableView: UITableView) -> Int { return self.numberOfSections() } func numberOfRows(for tableView: UITableView, in section: Int) -> Int { let dataSource = self.dataSource(at: section) return dataSource.numberOfRows(for: tableView, in: section) } func cellHeight(for tableView: UITableView, at indexPath: IndexPath) -> CGFloat { let dataSource = self.dataSource(at: indexPath.section) return dataSource.cellHeight(for: tableView, at: indexPath) } func cell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let dataSource = self.dataSource(at: indexPath.section) return dataSource.cell(for: tableView, at: indexPath) } func headerTitle(for tableView: UITableView, in section: Int) -> String? { let dataSource = self.dataSource(at: section) return dataSource.headerTitle(for: tableView, in: section) } func footerTitle(for tableView: UITableView, in section: Int) -> String? { let dataSource = self.dataSource(at: section) return dataSource.footerTitle(for: tableView, in: section) } func headerHeight(for tableView: UITableView, in section: Int) -> CGFloat { let dataSource = self.dataSource(at: section) return dataSource.headerHeight(for: tableView, in: section) } func footerHeight(for tableView: UITableView, in section: Int) -> CGFloat { let dataSource = self.dataSource(at: section) return dataSource.footerHeight(for: tableView, in: section) } func headerView(for tableView: UITableView, in section: Int) -> UIView? { let dataSource = self.dataSource(at: section) return dataSource.headerView(for: tableView, in: section) } func footerView(for tableView: UITableView, in section: Int) -> UIView? { let dataSource = self.dataSource(at: section) return dataSource.footerView(for: tableView, in: section) } func didSelectRow(in tableView: UITableView, at indexPath: IndexPath) { let dataSource = self.dataSource(at: indexPath.section) dataSource.didSelectRow(in: tableView, at: indexPath) } func didHighlightRow(in tableView: UITableView, at indexPath: IndexPath) { let dataSource = self.dataSource(at: indexPath.section) dataSource.didHighlightRow(in: tableView, at: indexPath) } func didUnhighlightRow(in tableView: UITableView, at indexPath: IndexPath) { let dataSource = self.dataSource(at: indexPath.section) dataSource.didUnhighlightRow(in: tableView, at: indexPath) } func willDisplay(row: UITableViewCell, in tableView: UITableView, at indexPath: IndexPath) { let dataSource = self.dataSource(at: indexPath.section) dataSource.willDisplay(row: row, in: tableView, at: indexPath) } func willDisplay(header: UIView, for tableView: UITableView, in section: Int) { let dataSource = self.dataSource(at: section) dataSource.willDisplay(header: header, for: tableView, in: section) } func willDisplay(footer: UIView, for tableView: UITableView, in section: Int) { let dataSource = self.dataSource(at: section) dataSource.willDisplay(footer: footer, for: tableView, in: section) } func canEditRow(for tableView: UITableView, at indexPath: IndexPath) -> Bool { let dataSource = self.dataSource(at: indexPath.section) return dataSource.canEditRow(for: tableView, at: indexPath) } func editActions(for tableView: UITableView, at indexPath: IndexPath) -> [UITableViewRowAction]? { let dataSource = self.dataSource(at: indexPath.section) return dataSource.editActions(for: tableView, at: indexPath) } func trailingSwipeActions(for tableView: UITableView, at indexPath: IndexPath) -> UISwipeActionsConfiguration? { let dataSource = self.dataSource(at: indexPath.section) return dataSource.trailingSwipeActions(for: tableView, at: indexPath) } func leadingSwipeActions(for tableView: UITableView, at indexPath: IndexPath) -> UISwipeActionsConfiguration? { let dataSource = self.dataSource(at: indexPath.section) return dataSource.leadingSwipeActions(for: tableView, at: indexPath) } func didStartScrolling(for tableView: UITableView) { dataSources.forEach { $0.didStartScrolling(for: tableView) } } func didEndScrolling(for tableView: UITableView) { dataSources.forEach { $0.didEndScrolling(for: tableView) } } }
mit
7ff09d9e7927bc507c113e605792e204
33.882353
116
0.665599
4.840816
false
false
false
false
wwdc14/SkyNet
SkyNet/Classes/Settings/NetworkSettingTableViewController.swift
1
3323
// // NetworkSettingTableViewController.swift // Pods // // Created by FD on 21/08/2017. // // import UIKit struct NetworkSettingModel { let title:String let isOn: Bool let type: HTTPModelShortType } struct NetworkSettingViewModel { let model:[NetworkSettingModel] let sectionTitle: String } class NetworkSettingTableViewController: UITableViewController { var dataSource:[NetworkSettingViewModel]? = nil override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "networkSetting" tableView.register(NetworkSettingTableViewCell.self, forCellReuseIdentifier: "cell") let netViewModel = NetworkSettingViewModel(model: loadData(), sectionTitle: "NetworkFilterType") dataSource = [] dataSource?.append(netViewModel) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return dataSource?.count ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let viewModel = dataSource?[section] return viewModel?.model.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: NetworkSettingTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! NetworkSettingTableViewCell func switchChange() { NetworkSettings.saveFilterType(index: indexPath.row) } if let dataSource = dataSource { let viewModel = dataSource[indexPath.section] let model = viewModel.model[indexPath.row] cell.switchControl.isOn = model.isOn cell.textLabel?.text = model.type.rawValue cell.handler = switchChange } return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let dataSource = dataSource { return dataSource[section].sectionTitle }else{ return "" } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } //MARK: - load method func loadData() -> [NetworkSettingModel] { let filter = NetworkSettings.getFilterTypes() let xml = NetworkSettingModel(title: "xml", isOn: filter[HTTPModelShortType.allValues.index(of: .XML)!], type:.XML) let json = NetworkSettingModel(title: "json", isOn: filter[HTTPModelShortType.allValues.index(of: .JSON)!], type: .JSON) let html = NetworkSettingModel(title: "html", isOn: filter[HTTPModelShortType.allValues.index(of: .HTML)!], type: .HTML) let image = NetworkSettingModel(title: "image", isOn: filter[HTTPModelShortType.allValues.index(of: .IMAGE)!], type: .IMAGE) let other = NetworkSettingModel(title: "other", isOn: filter[HTTPModelShortType.allValues.index(of: .OTHER)!], type: .OTHER) return [json,xml,html,image,other] } }
mit
592c0f9fa3daf1716175590023dbc43c
35.119565
134
0.668974
4.788184
false
false
false
false
areifers/Swift-iOS-Bootcamp-2014-Code-Fellows
CF-Day-3/HW-TableView-Seque-App/HW-TableView-Seque-App/TableViewDS.swift
1
1362
// // TableViewDS.swift // HW-TableView-Seque-App // // Created by Andrew Reifers on 11/5/14. // Copyright (c) 2014 DrIST Coach. All rights reserved. // import Foundation import UIKit class TableViewDS : NSObject, UITableViewDataSource { var persons = [Person](); //this creates an empty array override init(){ var nolan = Person(firstname: "Nolan", lastname: "Reifers"); self.persons.append(nolan) //this appends myPerson to array var addison = Person(firstname: "Addison", lastname: "Reifers"); self.persons.append(addison) //this appends myPerson to array var sandy = Person(firstname: "Sandy", lastname: "Reifers"); self.persons.append(sandy) //this appends myPerson to array self.persons.append(Person()); } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.persons.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PERSON_CELL", forIndexPath: indexPath) as UITableViewCell var personToDisplay = self.persons[indexPath.row] cell.textLabel.text = personToDisplay.getFullName(); return cell; } }
gpl-2.0
873d1e642ef52cfef9d62d13a3185653
29.977273
121
0.660059
4.509934
false
false
false
false
Alex-ZHOU/XYQSwift
XYQSwiftTests/Learn-from-Imooc/Play-with-Swift-2/04-Control-Flow/03-if-else-switch.playground/Contents.swift
1
864
// // 4-3 Swift 2.0逻辑控制之选择结构 - if,else和switch // 03-if-else-switch.playground // // Created by AlexZHOU on 21/05/2017. // Copyright © 2016年 AlexZHOU. All rights reserved. // import UIKit var str = "03-if-else-switch" print(str) // if - else var rating = "A" if rating == "A"{ print("Great!") } else if rating == "B"{ print("Just so-so") } else if rating == "C"{ print("It's Bad") } else{ print("Error") } rating = "a" // switch switch rating{ case "a","A": print("Great!") case "B": print("Just so-so") case "C": print("It's Bad") default: print("Error") } // 使用switch判断浮点数 let x = 2.8 switch x{ case 2.8: print("I'm 2.8") default: print("I'm not 2.8") } // 使用switch判断布尔值 let y = true switch y{ case true: print("I'm true") default: print("I'm false") }
apache-2.0
50b3714b040101ca618a3e9f4b9db37d
12.566667
52
0.586716
2.63961
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/Calculate.swift
1
1189
// // Calculate.swift // LeetCode // // Created by xiAo_Ju on 2019/9/19. // Copyright © 2019 伯驹 黄. All rights reserved. // import Foundation class Solution { class func calculate(_ s: String) -> Int { var result = 0 var stack: [Int] = [] var num = 0 var sign = "+" for (i, char) in s.enumerated() { let isNum = char >= "0" && char <= "9" if isNum { num = num * 10 + Int(String(char))! } if !isNum && char != " " || i == s.count - 1 { switch sign { case "+": stack.append(num) case "-": stack.append(-num) case "*": stack.append(stack.removeLast() * num) case "/": stack.append(stack.removeLast() / num) default: break } num = 0 sign = String(char) } } for n in stack { result += n } return result } }
mit
6832dca14c0de1ef32387ea4d186726b
22.176471
58
0.362944
4.690476
false
false
false
false
oskarpearson/rileylink_ios
NightscoutUploadKit/DeviceStatus/RecommendedTempBasal.swift
1
715
// // LoopSuggested.swift // RileyLink // // Created by Pete Schwamb on 7/28/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct RecommendedTempBasal { let timestamp: Date let rate: Double let duration: TimeInterval public init(timestamp: Date, rate: Double, duration: TimeInterval) { self.timestamp = timestamp self.rate = rate self.duration = duration } public var dictionaryRepresentation: [String: Any] { var rval = [String: Any]() rval["timestamp"] = TimeFormat.timestampStrFromDate(timestamp) rval["rate"] = rate rval["duration"] = duration / 60.0 return rval } }
mit
7a4ea83f87b605cc90d30b6fb7c29b29
22.032258
72
0.640056
4.275449
false
false
false
false
GraphicsLab/RoyaleBase
RoyaleBase/AppDelegate.swift
1
6108
// // AppDelegate.swift // RoyaleBase // // Created by Juneyoung Oh on 4/24/16. // Copyright © 2016 Juneyoung Oh. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "org.owls.team.royale.RoyaleBase" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("RoyaleBase", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
f60108dfe98d5780918c233108dfa907
54.018018
291
0.71983
5.844019
false
false
false
false
Jnosh/swift
stdlib/public/SDK/CryptoTokenKit/TKSmartCard.swift
25
1782
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import CryptoTokenKit import Foundation @available(OSX 10.10, *) extension TKSmartCard { public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, le: Int? = nil, reply: @escaping (Data?, UInt16, Error?) -> Void) { self.__sendIns(ins, p1: p1, p2: p2, data: data, le: le.map { NSNumber(value: $0) }, reply: reply) } @available(OSX 10.12, *) public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, le: Int? = nil) throws -> (sw: UInt16, response: Data) { var sw: UInt16 = 0 let response = try self.__sendIns(ins, p1: p1, p2: p2, data: data, le: le.map { NSNumber(value: $0) }, sw: &sw) return (sw: sw, response: response) } @available(OSX 10.12, *) public func withSession<T>(_ body: @escaping () throws -> T) throws -> T { var result: T? try self.__inSession(executeBlock: { (errorPointer: NSErrorPointer) -> Bool in do { result = try body() return true } catch let error as NSError { errorPointer?.pointee = error return false } }) // it is safe to force unwrap the result here, as the self.__inSession // function rethrows the errors which happened inside the block return result! } }
apache-2.0
e2bc718d7c889a081303bef79274095f
32
80
0.578002
3.751579
false
false
false
false
lseeker/HeidiKit
HeidiKit/HDAssetCollection.swift
1
5539
// // HDAssetCollection.swift // HeidiKit // // Created by Yun-young LEE on 2015. 2. 4.. // Copyright (c) 2015년 inode.kr. All rights reserved. // import UIKit import Photos import Darwin class HDAssetCollection: NSObject { var assetCollection : PHAssetCollection { didSet { _assetsFetchResult = nil } } var keyImage : UIImage? var _assetsFetchResult : PHFetchResult<AnyObject>? { didSet { keyImage = nil } } var assetsFetchResult : PHFetchResult<AnyObject> { get { if _assetsFetchResult != nil { return _assetsFetchResult! } let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) fetchOptions.wantsIncrementalChangeDetails = true //fetchOptions.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: true) ] _assetsFetchResult = PHAsset.fetchAssets(in: self.assetCollection, options: fetchOptions) return _assetsFetchResult! } } var title : String { get { return assetCollection.localizedTitle! } } var count : Int { get { return assetsFetchResult.count } } init (_ assetCollection : PHAssetCollection) { self.assetCollection = assetCollection super.init() } func cleanUp() { keyImage = nil; _assetsFetchResult = nil; } func fetchKeyImage(_ resultHandler : @escaping ((_ keyImage : UIImage?) -> Void)) { if let keyImage = keyImage { resultHandler(keyImage) return } OperationQueue().addOperation { () -> Void in let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) var resultOptional = PHAsset.fetchKeyAssets(in: self.assetCollection, options: fetchOptions) if resultOptional?.count == 0 { resultOptional = self.assetsFetchResult } guard let result = resultOptional else { return } //let options = self.assetCollection.assetCollectionSubtype == .SmartAlbumUserLibrary ? .Reverse : NSEnumerationOptions() var assets = [PHAsset]() result.enumerateObjects({ (obj, index, stop) -> Void in assets.append(obj ) if assets.count == 3 { stop.pointee = true } }) if assets.isEmpty { return } let imageRequestOptions = PHImageRequestOptions() imageRequestOptions.isSynchronous = true // synchronous for asset order imageRequestOptions.version = .current imageRequestOptions.deliveryMode = .highQualityFormat imageRequestOptions.resizeMode = .exact let scale = UIScreen.main.scale let width = 68 * scale let height = 72 * scale var color = UITableViewCell.appearance().backgroundColor if color == nil { color = UIColor.white } // scale is 1.0 for line stroke UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), true, 1.0) let context = UIGraphicsGetCurrentContext() context?.setFillColor((color?.cgColor)!) context?.fill(CGRect(x: 0, y: 0, width: width, height: height)) let count = assets.count for (index, asset) in Array(assets.reversed()).enumerated() { let factor = CGFloat((count - 1 - index) * 2) * scale let sideLength = 68 * scale - factor * 2 let size = CGSize(width: sideLength, height: sideLength) PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: PHImageContentMode.aspectFill, options: imageRequestOptions, resultHandler: { (image, info) -> Void in guard let image = image else { return } let rect = CGRect(origin: CGPoint(x: factor, y: factor * 3), size: size) let cropSize = min(image.size.width, image.size.height) let cropOrigin = CGPoint(x: (image.size.width - cropSize) / 2, y: (image.size.height - cropSize) / 2) context?.draw((image.cgImage?.cropping(to: CGRect(origin: cropOrigin, size: CGSize(width: cropSize, height: cropSize)))!)!, in: rect) }) } context?.setStrokeColor((color?.cgColor)!) context?.addRect(CGRect(x: 0, y: height - 4 * scale + 0.5, width: width, height: 2 * scale)) context?.strokePath() if let cgImage = context?.makeImage() { UIGraphicsEndImageContext() self.keyImage = UIImage(cgImage: cgImage, scale: scale, orientation: UIImageOrientation.downMirrored) } DispatchQueue.main.async { resultHandler(self.keyImage) } } } }
apache-2.0
9a186d097575ec30905e1beb92988f09
36.161074
199
0.543616
5.487611
false
false
false
false
ecwineland/Presente
Presente/CreateClassViewController.swift
1
4298
// // CreateClassViewController.swift // Presente // // Created by Evan Wineland on 10/15/15. // Copyright © 2015 Evan Wineland. All rights reserved. // import UIKit class CreateClassViewController: UIViewController { @IBOutlet var clssName: UITextField! @IBOutlet var clssNum: UITextField! @IBOutlet var clssDesc: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancel(sender: AnyObject) { self.performSegueWithIdentifier("backToClasses", sender: self) } @IBAction func createClass(sender: AnyObject) { // Create error message if one or more fields is empty if (clssName.text!.isEmpty || clssNum.text!.isEmpty || clssDesc.text!.isEmpty ) { let alert = UIAlertView() alert.title = "Missing fields" alert.message = "Fill in all fields to create the new class" alert.addButtonWithTitle("Ok") alert.show() // Create new class } else { var newClass = PFObject(className: "Class") newClass.setObject(clssName.text!, forKey: "Name") newClass.setObject(clssNum.text!, forKey: "Num") newClass.setObject(clssDesc.text!, forKey: "Description") // Save newClass newClass.saveInBackgroundWithBlock({ (succeeded, error) -> Void in // Object created if succeeded { // Users :: Classes is a many to many, so create user_classes to resolve let userClass = PFObject(className: "User_Class") userClass.setObject(newClass, forKey: "Class") userClass.setObject(PFUser.currentUser()!, forKey: "User") // Save userClass userClass.saveInBackgroundWithBlock({ (succeeded, error) -> Void in if succeeded { print("UserClass created for class: \(self.clssName.text!) and user \(PFUser.currentUser()!)") // Show error, if there is one } else { let alertController : UIAlertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) self.presentViewController(alertController, animated: true, completion: nil) } }) print("Class created with name: \(self.clssName.text!)") self.performSegueWithIdentifier("backToClasses", sender: self) // Create error message } else { let alertController : UIAlertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) self.presentViewController(alertController, animated: true, completion: nil) } }) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
f31d4e3b5e98f36288fdb2794129e538
37.026549
148
0.528741
5.894376
false
false
false
false
betalun/Dollar
Dollar/DollarTests/DollarTests.swift
3
21092
// // DollarTests.swift // DollarTests // // Created by Ankur Patel on 6/3/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import XCTest import Dollar class DollarTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testFirst() { if let result = $.first([1, 2, 3, 4]) { XCTAssertEqual(result, 1, "Return first element") } XCTAssertNil($.first([Int]()), "Returns nil when array is empty") } func testSecond() { if let result = $.second([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { XCTAssertEqual(result, 2, "Return second element") } XCTAssertNil($.second([Int]()), "Returns nil when array is empty") } func testThird() { if let result = $.third([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { XCTAssertEqual(result, 3, "Return third element") } XCTAssertNil($.third([Int]()), "Returns nil when array is empty") } func testNoop() { $.noop() } func testCompact() { XCTAssert($.compact([3, nil, 4, 5]) == [3, 4, 5], "Return truth array") XCTAssertEqual($.compact([nil, nil]) as [NSObject], [], "Return truth array") } func testEach() { var arr: [Int] = [] var result = $.each([1, 3, 4, 5], callback: { arr.append($0 * 2) }) XCTAssert(result == [1, 3, 4, 5], "Return the array itself") XCTAssert(arr == [2, 6, 8, 10], "Return array with doubled numbers") } func testEqual() { XCTAssert($.equal(Optional("hello"), Optional("hello")), "optionalString and otherOptionalString should be equal.") XCTAssertFalse($.equal(Optional("hello"), Optional("goodbye")), "optionalString and thirdOptionalString should not be equal.") XCTAssert($.equal(nil as String?, nil as String?), "Nil optionals should be equal.") } func testFlatten() { XCTAssertEqual($.flatten([[3], 4, 5]), [3, 4, 5], "Return flat array") XCTAssertEqual($.flatten([[[3], 4], 5] as [NSObject]), [3, 4, 5], "Return flat array") } func testShuffle() { XCTAssertEqual($.shuffle([1]), [1], "Return shuffled array") XCTAssertEqual($.shuffle([1, 2, 3]).count, 3, "Return shuffled array") XCTAssertEqual($.shuffle([Int]()), [], "Return empty array") } func testIndexOf() { XCTAssertEqual($.indexOf(["A", "B", "C"], value: "B")!, 1, "Return index of value") XCTAssertEqual($.indexOf([3, 4, 5], value: 5)!, 2, "Return index of value") XCTAssertEqual($.indexOf([3, 4, 5], value: 3)!, 0, "Return index of value") XCTAssertNil($.indexOf([3, 4, 5], value: 2), "Return index of value") } func testInitial() { XCTAssertEqual($.initial([3, 4, 5]), [3, 4], "Return all values except for last") XCTAssertEqual($.initial([3, 4, 5], numElements: 2), [3], "Return all values except for last") XCTAssertEqual($.initial([3, 4, 5], numElements: 4), [], "Return all values except for last") } func testRest() { XCTAssertEqual($.rest([3, 4, 5]), [4, 5], "Returns all value except for first") XCTAssertEqual($.rest([3, 4, 5], numElements: 2), [5], "Returns all value except for first") XCTAssertEqual($.rest([3, 4, 5], numElements: 4), [], "Returns all value except for first") } func testLast() { if let result = $.last([3, 4, 5]) { XCTAssertEqual(result, 5, "Returns last element in array") } XCTAssertNil($.last([NSObject]()), "Returns nil when array is empty") } func testFindIndex() { let arr = [["age": 36], ["age": 40], ["age": 1]] XCTAssertEqual($.findIndex(arr) { $0["age"] < 20 }!, 2, "Returns index of element in array") } func testFindLastIndex() { let arr = [["age": 36], ["age": 40], ["age": 1]] XCTAssertEqual($.findLastIndex(arr) { $0["age"] > 30 }!, 1, "Returns last index of element in array") } func testLastIndexOf() { XCTAssertEqual($.lastIndexOf([1, 2, 3, 1, 2, 3], value: 2)!, 4, "Returns last index of element in array") } func testContains() { XCTAssertTrue($.contains([1, 2, 3, 1, 2, 3], value: 2), "Checks if array contains element") XCTAssertFalse($.contains([1, 2, 3, 1, 2, 3], value: 10), "Checks if array contains element") } func testRange() { XCTAssertEqual($.range(4), [0, 1, 2, 3], "Generates range") XCTAssertEqual($.range(from: 1, to: 5), [1, 2, 3, 4], "Generates range") XCTAssertEqual($.range(from: 0, to: 20, incrementBy: 5), [0, 5, 10, 15], "Generates range") XCTAssertEqual($.range(4.0), [0.0, 1.0, 2.0, 3.0], "Generates range of doubles") XCTAssertEqual($.range(from: -2.0, to: 2.0), [-2.0, -1.0, 0.0, 1.0], "Generates range of doubles") XCTAssertEqual($.range(from: -10.0, to: 10.0, incrementBy: 5), [-10.0, -5.0, 0.0, 5.0], "Generates range of doubles") XCTAssertEqual($.range(from: 1, through: 5), [1, 2, 3, 4, 5], "Increments by 1 and includes 5") XCTAssertEqual($.range(from: 0, through: 20, incrementBy: 5), [0, 5, 10, 15, 20], "Includes 20") XCTAssertEqual($.range(from: -10.0, through: 10.0, incrementBy: 5), [-10.0, -5.0, 0.0, 5.0, 10.0], "Includes 10.0") } func testSequence() { XCTAssertEqual($.sequence("abc"), ["a", "b", "c"], "Generates array of characters") } func testRemove() { XCTAssertEqual($.remove([1, 2, 3, 4, 5, 6], callback: { $0 == 2 || $0 == 3 }), [1, 4, 5, 6], "Remove based on callback") } func testSortedIndex() { XCTAssertEqual($.sortedIndex([3, 4, 6, 10], value: 5), 2, "Index to insert element at in a sorted array") XCTAssertEqual($.sortedIndex([10, 20, 30, 50], value: 40), 3, "Index to insert element at in a sorted array") } func testWithout() { XCTAssertEqual($.without([3, 4, 5, 3, 5], values: 3, 5), [4], "Removes elements passed after the array") XCTAssertEqual($.without([3, 4, 5, 3, 5], values: 4), [3, 5, 3, 5], "Removes elements passed after the array") XCTAssertEqual($.without([3, 4, 5, 3, 5], values: 3, 4, 5), [], "Removes elements passed after the array") } func testPull() { XCTAssertEqual($.pull([3, 4, 5, 3, 5], values: 3, 5), [4], "Removes elements passed after the array") XCTAssertEqual($.pull([3, 4, 5, 3, 5], values: 4), [3, 5, 3, 5], "Removes elements passed after the array") XCTAssertEqual($.pull([3, 4, 5, 3, 5], values: 3, 4, 5), [], "Removes elements passed after the array") } func testZip() { XCTAssertTrue($.zip(["fred", "barney"], [30, 40], [true, false]) as [NSObject] == [["fred", 30, true], ["barney", 40, false]], "Zip up arrays") } func testZipObject() { XCTAssertTrue($.zipObject(["fred", "barney"], values: [30, 40]) as [String: Int] == ["fred": 30, "barney": 40], "Zip up array to object") } func testIntersection() { XCTAssertEqual($.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]).sorted({$0<$1}), [1, 2], "Intersection of arrays") } func testDifference() { XCTAssertEqual($.difference([1, 2, 3, 4, 5], [5, 2, 10]).sorted({$0<$1}), [1, 3, 4], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [], [3]).sorted({$0<$1}), [1, 1, 1, 2, 2], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [1, 1], [3]).sorted({$0<$1}), [2, 2], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [1, 1], [1, 2, 2]), [], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], [1, 1, 1], [1, 2, 2]), [], "Difference of arrays") XCTAssertEqual($.difference([1, 1, 1, 2, 2], []).sorted({$0<$1}), [1, 1, 1, 2, 2], "Difference of arrays") } func testUniq() { XCTAssertEqual($.uniq([1, 2, 1, 3, 1]), [1, 2, 3], "Uniq of arrays") XCTAssertEqual($.uniq([1, 2.5, 3, 1.5, 2, 3.5], by: {floor($0)}), [1, 2.5, 3], "Uniq numbers by condition") } func testUnion() { XCTAssertEqual($.union([1, 2, 3], [5, 2, 1, 4], [2, 1]), [1, 2, 3, 5, 4], "Union of arrays") } func testXOR() { XCTAssertEqual($.xor([1, 2, 3], [5, 2, 1, 4]).sorted{$0<$1}, [3, 4, 5], "Xor of arrays") } func testAt() { XCTAssertEqual($.at(["ant", "bat", "cat", "dog", "egg"], indexes: 0, 2, 4), ["ant", "cat", "egg"], "At of arrays") } func testEvery() { XCTAssertTrue($.every([1, 2, 3, 4]) { $0 < 20 }, "All elements in collection are true") XCTAssertFalse($.every([1, 2, 3, 4]) { $0 == 1 }, "All elements in collection are true") } func testFind() { XCTAssertEqual($.find([1, 2, 3, 4], callback: { $0 == 2 })!, 2, "Return element when object is found") XCTAssertNil($.find([1, 2, 3, 4], callback: { $0 as! Int == 10 }), "Return nil when object not found") } func testMax() { XCTAssert($.max([1, 2, 3, 4, 2, 1]) == 4, "Returns maximum element") XCTAssertNil($.max([Int]()), "Returns nil when array is empty") } func testMin() { XCTAssert($.min([2, 1, 2, 3, 4]) == 1, "Returns minumum element") XCTAssertNil($.min([Int]()), "Returns nil when array is empty") } func testSample() { let arr = [2, 1, 2, 3, 4] XCTAssertTrue($.contains(arr, value: $.sample(arr)), "Returns sample which is an element from the array") } func testPluck() { let arr = [["age": 20], ["age": 30], ["age": 40]] XCTAssertEqual($.pluck(arr, value: "age"), [20, 30, 40], "Returns values from the object where they key is the value") } func testFrequencies() { XCTAssertTrue($.frequencies(["a", "a", "b", "c", "a", "b"]) == ["a": 3, "b": 2, "c": 1], "Returns correct frequency dictionary") XCTAssertTrue($.frequencies([1,2,3,4,5]) { $0 % 2 == 0 } == [false: 3, true: 2], "Returns correct frequency dictionary from cond") } func testKeys() { let dict = ["Dog": 1, "Cat": 2] XCTAssertEqual($.keys(dict).sorted({$0<$1}), ["Cat", "Dog"], "Returns correct array with keys") } func testValues() { let dict = ["Dog": 1, "Cat": 2] XCTAssertEqual($.values(dict).sorted({$0<$1}), [1, 2], "Returns correct array with values") } func testMerge() { let dict = ["Dog": 1, "Cat": 2] let dict2 = ["Cow": 3] let dict3 = ["Sheep": 4] XCTAssertTrue($.merge(dict, dict2, dict3) == ["Dog": 1, "Cat": 2, "Cow": 3, "Sheep": 4], "Returns correct merged dictionary") let arr = [1, 5] let arr2 = [2, 4] let arr3 = [5, 6] XCTAssertEqual($.merge(arr, arr2, arr3), [1, 5, 2, 4, 5, 6], "Returns correct merged array") } func testPick() { let dict = ["Dog": 1, "Cat": 2, "Cow": 3] XCTAssertTrue($.pick(dict, keys: "Dog", "Cow") == ["Dog": 1, "Cow": 3], "Returns correct picked dictionary") } func testOmit() { let dict = ["Dog": 1, "Cat": 2, "Cow": 3] XCTAssertTrue($.omit(dict, keys: "Dog") == ["Cat": 2, "Cow": 3], "Returns correct omited dictionary") } func testTap() { var beatle = CarExample(name: "Fusca") $.tap(beatle, function: {$0.name = "Beatle"}).color = "Blue" XCTAssertEqual(beatle.name!, "Beatle", "Set the car name") XCTAssertEqual(beatle.color!, "Blue", "Set the car color") } func testChaining() { var chain = $.chain([1, 2, 3]) XCTAssertEqual(chain.first()!, 1, "Returns first element which ends the chain") chain = $.chain([10, 20, 30, 40, 50]) var elements: [Int] = [] chain.each { elements.append($0 as Int) } chain.value XCTAssertEqual(elements, [10, 20, 30, 40, 50], "Goes through each element in the array") XCTAssertTrue(chain.all({ ($0 as Int) < 100 }), "All elements are less than 100") chain = $.chain([10, 20, 30, 40, 50]) XCTAssertFalse(chain.all({ ($0 as Int) < 40 }), "All elements are not less than 40") chain = $.chain([10, 20, 30, 40, 50]) XCTAssertTrue(chain.any({ ($0 as Int) < 40 }), "At least one element is less than 40") chain = $.chain([10, 20, 30, 40, 50]) elements = [Int]() chain.slice(0, end: 3).each { elements.append($0 as Int) } chain.value XCTAssertEqual(elements, [10, 20, 30], "Chained seld") let testarr = [[[1, 2]], 3, [[4], 5]] let chainA = $.chain(testarr) XCTAssertEqual(chainA.flatten().initial(2).value, [1, 2, 3], "Returns flatten array from chaining") let chainB = $.chain(testarr) XCTAssertEqual(chainB.initial().flatten().first()!, 1, "Returns flatten array from chaining") let chainC = $.chain(testarr) // XCTAssertEqual(chainC.flatten().map({ (elem) in elem as Int * 10 }).value, [10, 20, 30, 40, 50], "Returns mapped values") // XCTAssertEqual(chainC.flatten().map({ (elem) in elem as Int * 10 }).first()!, 100, "Returns first element from mapped value") } func testPartial() { let s = "ABCD" let partialFunc = $.partial({(T: String...) in T[0] + " " + T[1] + " from " + T[2] }, "Hello") XCTAssertEqual(partialFunc("World", "Swift"), "Hello World from Swift", "Returns curry function that is evaluated") } func testBind() { let helloWorldFunc = $.bind({(T: String...) in T[0] + " " + T[1] + " from " + T[2] }, "Hello", "World", "Swift") XCTAssertEqual(helloWorldFunc(), "Hello World from Swift", "Returns curry function that is evaluated") } func testTimes() { let fun = $.bind({ (names: String...) -> String in let people = $.join(names, separator: " from ") return "Hello \(people)" }, "Ankur", "Swift") XCTAssertEqual($.times(3, function: fun) as [String], ["Hello Ankur from Swift", "Hello Ankur from Swift", "Hello Ankur from Swift"], "Call a function 3 times") } func testAfter() { var saves = ["profile", "settings"] let asyncSave = { (function: () -> ()?) in function() } var isDone = false var completeCallback = $.after(saves.count) { isDone = true } for elem in saves { asyncSave(completeCallback) } XCTAssertTrue(isDone, "Should be done") } func testPartition() { var array = [1, 2, 3, 4, 5] XCTAssertEqual($.partition(array, n: 2), [[1, 2], [3, 4]], "Partition uses n for step if not supplied.") XCTAssertTrue($.partition(array, n: 2, step: 1) == [[1, 2], [2, 3], [3, 4], [4, 5]], "Partition allows specifying a custom step.") XCTAssertEqual($.partition(array, n: 2, step: 1, pad: nil), [[1, 2], [2, 3], [3, 4], [4, 5], [5]], "Partition with nil pad allows the last partition to be less than n length") XCTAssertEqual($.partition(array, n: 4, step: 1, pad: nil), [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5]], "Partition with nil pad stops at the first partition less than n length.") XCTAssertEqual($.partition(array, n: 2, step: 1, pad: [6,7,8]), [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]], "Partition pads the last partition to the right length.") XCTAssertEqual($.partition(array, n: 4, step: 3, pad: [6]), [[1, 2, 3, 4], [4, 5, 6]], "Partition doesn't add more elements than pad has.") XCTAssertEqual($.partition([1, 2, 3, 4, 5], n: 2, pad: [6]), [[1, 2], [3, 4], [5, 6]], "Partition with pad and no step uses n as step.") XCTAssertTrue($.partition([1, 2, 3, 4, 5, 6], n: 2, step: 4) == [[1, 2], [5, 6]], "Partition step length works.") XCTAssertEqual($.partition(array, n: 10), [[]], "Partition without pad returns [[]] if n is longer than array.") } func testPartitionAll() { var array = [1, 2, 3, 4, 5] XCTAssertTrue($.partitionAll(array, n: 2, step: 1) == [[1, 2], [2, 3], [3, 4], [4, 5], [5]], "PartitionAll includes partitions less than n.") XCTAssertTrue($.partitionAll(array, n: 2) == [[1, 2], [3, 4], [5]], "PartitionAll uses n as the step when not supplied.") XCTAssertTrue($.partitionAll(array, n:4, step: 1) == [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5], [4, 5], [5]], "PartitionAll does not stop at the first partition less than n length.") } func testPartitionBy() { XCTAssertTrue($.partitionBy([1, 2, 3, 4, 5]) { $0 > 10 } == [[1, 2, 3, 4, 5]], "PartitionBy doesn't try to split unnecessarily.") XCTAssertTrue($.partitionBy([1, 2, 4, 3, 5, 6]) { $0 % 2 == 0 } == [[1], [2, 4], [3, 5], [6]], "PartitionBy splits appropriately on Bool.") XCTAssertTrue($.partitionBy([1, 7, 3, 6, 10, 12]) { $0 % 3 } == [[1, 7], [3, 6], [10], [12]], "PartitionBy can split on functions other than Bool.") } func testMap() { XCTAssertEqual($.map([1, 2, 3, 4, 5]) { $0 * 2 }, [2, 4, 6, 8, 10], "Map function should double values in the array") } func testFlatMap() { XCTAssertEqual($.flatMap([1, 2, 3]) { [$0, $0] }, [1, 1, 2, 2, 3, 3], "FlatMap should double every item in the array and concatenate them.") let expected: String? = "swift" let actual = $.flatMap(NSURL(string: "https://apple.com/swift/")) { $0.lastPathComponent } XCTAssert($.equal(actual, expected), "FlatMap on optionals should run the function and produce a single-level optional containing the last path component of the url.") } func testReduce() { XCTAssertEqual($.reduce([1, 2, 3, 4, 5], initial: 0) { $0 + $1 } as Int, 15, "Reduce function should sum elements in the array") } func testSlice() { XCTAssertEqual($.slice([1,2,3,4,5], start: 0, end: 2), [1, 2], "Slice subarray 0..2") XCTAssertEqual($.slice([1,2,3,4,5], start: 0), [1, 2, 3, 4, 5], "Slice at 0 is whole array") XCTAssertEqual($.slice([1,2,3,4,5], start: 3), [4, 5], "Slice with start goes till end") XCTAssertEqual($.slice([1,2,3,4,5], start: 8), [], "Slice out of bounds is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 8, end: 10), [], "Slice out of bounds is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 8 , end: 2), [], "Slice with end < start is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 3, end: 3), [], "Slice at x and x is empty") XCTAssertEqual($.slice([1,2,3,4,5], start: 2, end: 5), [3,4,5], "Slice at x and x is subarray") } func testFib() { var times = 0 let fibMemo = $.memoize { (fib: (Int -> Int), val: Int) -> Int in times += 1 return val == 1 || val == 0 ? 1 : fib(val - 1) + fib(val - 2) } let x = fibMemo(5) XCTAssertEqual(times, 6, "Function called 6 times") times = 0 let y = fibMemo(5) XCTAssertEqual(times, 0, "Function called 0 times due to memoize") times = 0 let z = fibMemo(6) XCTAssertEqual(times, 1, "Function called 1 times due to memoize") } func testId() { XCTAssertEqual($.id(1), 1, "Id should return the argument it gets passed") } func testComposeVariadic() { let double = { (params: Int...) -> [Int] in return $.map(params) { $0 * 2 } } let subtractTen = { (params: Int...) -> [Int] in return $.map(params) { $0 - 10 } } let doubleSubtractTen = $.compose(double, subtractTen) XCTAssertEqual(doubleSubtractTen(5, 6, 7), [0, 2, 4], "Should double value and then subtract 10") } func testComposeArray() { let double = { (params: [Int]) -> [Int] in return $.map(params) { $0 * 2 } } let subtractTen = { (params: [Int]) -> [Int] in return $.map(params) { $0 - 10 } } let doubleSubtractTen = $.compose(double, subtractTen) XCTAssertEqual(doubleSubtractTen([5, 6, 7]), [0, 2, 4], "Should double value and then subtract 10") } func testChunk() { XCTAssertEqual($.chunk([1, 2, 3, 4], size: 2), [[1, 2], [3, 4]], "Should chunk with elements in groups of 2") XCTAssertEqual($.chunk([1, 2, 3, 4], size: 3), [[1, 2, 3], [4]], "Should chunk with elements in groups of 2") } func testFill() { var arr = Array<Int>(count: 5, repeatedValue: 1) XCTAssertEqual($.fill(&arr, withElem: 42), [42,42,42,42,42], "Should fill array with 42") $.fill(&arr, withElem: 1, startIndex: 1, endIndex: 3) XCTAssertEqual($.fill(&arr, withElem: 1, startIndex: 1, endIndex: 3), [42,1,1,1,42], "Should fill array with 1") } func testPullAt() { XCTAssertEqual($.pullAt([10, 20, 30, 40, 50], indices: 1, 2, 3), [10, 50], "Remove elements at index") } func testSize() { XCTAssertEqual($.size([10, 20, 30, 40, 50]), 5, "Returns size") } }
mit
a1f3e29d050b9f8734b46b71bcc0288c
44.65368
187
0.551489
3.513577
false
true
false
false
gbuenoandrade/e-urbano
e-urbano/HomeVC.swift
1
735
// // HomeVC.swift // e-urbano // // Created by Guilherme Andrade on 7/4/15. // Copyright (c) 2015 Laboratório de Estudos Urbanos da Unicamp. All rights reserved. // import UIKit import Parse import MapKit class HomeVC: UIViewController { let logInScreenSegue = "goToLogInScreen" let settingsScreenSegue = "goToSettingsScreen" let locationManager = CLLocationManager() override func viewDidAppear(animated: Bool) { let user = PFUser.currentUser() if user == nil || !user!.isAuthenticated() { self.performSegueWithIdentifier(self.logInScreenSegue, sender: nil) } else { if CLLocationManager.authorizationStatus() != .AuthorizedWhenInUse { locationManager.requestWhenInUseAuthorization() } } } }
mit
cbc56c37fabd407eea8eb974f897057c
22.677419
86
0.734332
3.744898
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/SearchVC/KidsPicker/HLKidAgePickerView.swift
1
5330
import UIKit protocol HLKidAgePickerViewDelegate: class, NSObjectProtocol { func didSelectAge(_ age: Int) func didCloseAgeSelector() } class HLKidAgePickerView: UIView, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet fileprivate var pickerHeaderView: UIView! @IBOutlet fileprivate var agePickerView: UIPickerView! @IBOutlet fileprivate var applyButton: UIButton! @IBOutlet fileprivate var cancelButton: UIButton! @IBOutlet fileprivate var pickerBottomConstraint: NSLayoutConstraint! weak var delegate: HLKidAgePickerViewDelegate? var presented: Bool = false var kidAge: Int = 7 { didSet { self.agePickerView?.selectRow(self.kidAge, inComponent: 0, animated: false) } } override func awakeFromNib() { super.awakeFromNib() self.initialize() } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if pickerHeaderView.frame.contains(point) || agePickerView.frame.contains(point) { return super.point(inside: point, with: event) } hide(true) return false } // MARK: - Internal methods func show(_ onView: UIView, animated: Bool, bottomOffset: CGFloat) { onView.addSubview(self) self.translatesAutoresizingMaskIntoConstraints = false self.backgroundColor = UIColor.clear let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|[selfView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["selfView": self]) onView.addConstraints(verticalConstraint) let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|[selfView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["selfView": self]) onView.addConstraints(horizontalConstraint) onView.layoutIfNeeded() self.pickerBottomConstraint.constant = -(self.agePickerView.bounds.height + self.pickerHeaderView.bounds.height) self.layoutIfNeeded() let duration = (animated ? 0.4 : 0.0) UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(), animations: { [weak self] () -> Void in self?.pickerBottomConstraint.constant = bottomOffset self?.layoutIfNeeded() }, completion: { [weak self] (finished) -> Void in self?.presented = true }) } func hide(_ animated: Bool) { self.delegate?.didCloseAgeSelector() let duration = (animated ? 0.4 : 0.0) UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(), animations: { [weak self] () -> Void in let agePickerBounds = self?.agePickerView?.bounds ?? CGRect.zero let pickerHeaderBounds = self?.pickerHeaderView?.bounds ?? CGRect.zero self?.backgroundColor = UIColor.clear self?.pickerBottomConstraint.constant = -(agePickerBounds.height + pickerHeaderBounds.height) self?.layoutIfNeeded() }, completion: { [weak self] (finished) -> Void in self?.removeFromSuperview() self?.presented = false }) } // MARK: - Private methods fileprivate func initialize() { agePickerView?.showsSelectionIndicator = true agePickerView?.backgroundColor = UIColor.white agePickerView?.selectRow(kidAge, inComponent: 0, animated: false) let normalColor = JRColorScheme.actionColor() applyButton.setTitleColor(normalColor, for: UIControl.State()) cancelButton.setTitleColor(normalColor, for: UIControl.State()) applyButton.titleLabel?.font = UIFont.systemFont(ofSize: 14.0) applyButton.setTitle(NSLS("HL_KIDS_PICKER_APPLY_BUTTON_TITLE"), for: .normal) cancelButton.setTitle(NSLS("HL_KIDS_PICKER_CANCEL_BUTTON_TITLE"), for: .normal) } // MARK: - IBActions methods @IBAction fileprivate func onApply(_ sender: AnyObject!) { self.delegate?.didSelectAge(self.agePickerView.selectedRow(inComponent: 0)) self.hide(true) } @IBAction fileprivate func onCancel(_ sender: AnyObject!) { self.hide(true) } // MARK: - UIPickerViewDataSource methods func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 18 } // MARK: - UIPickerViewDelegate methods func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return (row == 0) ? NSLS("HL_KIDS_PICKER_LESS_THAN_ONE_YEAR_TITLE") : "\(row)" } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var label: UILabel? = view as? UILabel if label == nil { label = UILabel() } label?.textAlignment = NSTextAlignment.center label?.textColor = UIColor.darkText label?.text = (row == 0) ? NSLS("HL_KIDS_PICKER_LESS_THAN_ONE_YEAR_TITLE") : "\(row)" return label! } }
mit
1369a6e0f32d03468e0d20fd577a8cac
36.013889
198
0.653471
4.827899
false
false
false
false
Performador/Pickery
Pickery/AssetGridCell.swift
1
3312
// // AssetCell.swift // Pickery // // Created by Okan Arikan on 7/1/16. // // import UIKit import Photos import ReactiveSwift import FontAwesome_swift /// Regular asset display insude a grid view with an overlay class AssetGridCell: UICollectionViewCell { /// Da constants struct Constants { static let kReuseIdentifier = "AssetGridCell" static let kSize = CGFloat(24) static let kCheckFont = UIFont.fontAwesome(ofSize: kSize) } /// The image view that will display the thumbnail let assetView = AssetView(frame: CGRect.zero) /// Displays the select view over the image let selectView = UILabel(frame: CGRect.zero) /// Whether we are currently editing or not private var isEditing : Bool = false /// Are we selected or not override var isSelected : Bool { didSet { selectView.text = isSelected ? FontAwesome.checkCircleO.rawValue : FontAwesome.circleO.rawValue selectView.sizeToFit() setNeedsLayout() } } /// Ctor override init(frame: CGRect) { super.init(frame: frame) // Setup the selected selectView.font = Constants.kCheckFont selectView.textColor = UIColor.white selectView.text = isSelected ? FontAwesome.checkCircleO.rawValue : FontAwesome.circleO.rawValue selectView.sizeToFit() selectView.alpha = 0 selectView.addShadow(color: UIColor.black) // Add it as a subview addSubview(assetView) addSubview(selectView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Is the collection view in the editing mode? func set(editing: Bool, animated: Bool) { // Animated transition? if animated { UIView.animate(withDuration: 0.5, animations: { self.selectView.alpha = editing ? 1 : 0 self.assetView.overlayView.alpha = editing ? 0 : 1 }, completion: { (Bool) in self.isEditing = editing }) } else { selectView.alpha = editing ? 1 : 0 assetView.overlayView.alpha = editing ? 0 : 1 isEditing = editing } } /// Reset the image view animations override func prepareForReuse() { super.prepareForReuse() // Reset the asset assetView.asset = nil } /// Do the layout override func layoutSubviews() { super.layoutSubviews() // Cover the entire view assetView.frame = self.bounds // Center the select mark selectView.center = CGPoint(x: bounds.midX, y: bounds.midY) } } /// MARK: - AssetCell corformance extension AssetGridCell : AssetCell { /// The asset we are displaying var asset: Asset? { get { return assetView.asset } set { assetView.asset = newValue } } /// Get the transition view to use var transitionView: UIView { return assetView } }
mit
3c49e869c68407d7fb88980cc7583ab6
28.309735
113
0.567029
4.813953
false
false
false
false
KarlWarfel/nutshell-ios
Nutshell/ViewControllers/EventViewNavController.swift
1
2360
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import UIKit class EventViewNavController: ENSideMenuNavigationController, ENSideMenuDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let storyboard = UIStoryboard(name: "EventView", bundle: nil) let menuController = storyboard.instantiateViewControllerWithIdentifier("sidebarController") as! MenuAccountSettingsViewController sideMenu = ENSideMenu(sourceView: self.view, menuViewController: menuController, menuPosition:.Left) //sideMenu?.delegate = self //optional sideMenu?.menuWidth = 235.0 // optional, default is 160 //sideMenu?.bouncingEnabled = false //sideMenu?.allowPanGesture = false // make navigation bar showing over side menu view.bringSubviewToFront(navigationBar) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - ENSideMenu Delegate func sideMenuWillOpen() { print("sideMenuWillOpen") } func sideMenuWillClose() { print("sideMenuWillClose") } func sideMenuDidClose() { print("sideMenuDidClose") } func sideMenuDidOpen() { print("sideMenuDidOpen") } }
bsd-2-clause
a6a20fc9d65056e15e10e2d8e9d7ab49
33.202899
138
0.701695
5.186813
false
false
false
false
abertelrud/swift-package-manager
Sources/Workspace/ResolvedFileWatcher.swift
2
2194
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2018-2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import class Foundation.NSLock import PackageModel import PackageGraph import TSCBasic import class TSCUtility.FSWatch /// A file watcher utility for the Package.resolved file. /// /// This is not intended to be used directly by clients. final class ResolvedFileWatcher { private var fswatch: FSWatch! private var existingValue: ByteString? private let valueLock = NSLock() private let resolvedFile: AbsolutePath public func updateValue() { valueLock.withLock { self.existingValue = try? localFileSystem.readFileContents(resolvedFile) } } init(resolvedFile: AbsolutePath, onChange: @escaping () -> ()) throws { self.resolvedFile = resolvedFile let block = { [weak self] (paths: [AbsolutePath]) in guard let self = self else { return } // Check if resolved file is part of the received paths. let hasResolvedFile = paths.contains{ $0.appending(component: resolvedFile.basename) == resolvedFile } guard hasResolvedFile else { return } self.valueLock.withLock { // Compute the contents of the resolved file and fire the onChange block // if its value is different than existing value. let newValue = try? localFileSystem.readFileContents(resolvedFile) if self.existingValue != newValue { self.existingValue = newValue onChange() } } } fswatch = FSWatch(paths: [resolvedFile.parentDirectory], latency: 1, block: block) try fswatch.start() } deinit { fswatch.stop() } }
apache-2.0
5551a0b344a79e19d1ec0771aa62c342
33.825397
114
0.602552
5.126168
false
false
false
false
Shivam0911/IOS-Training-Projects
webServiceHitDemo/webServiceHitDemo/ViewController.swift
1
3139
// // ViewController.swift // WebServiceHitDemo // // Created by MAC on 20/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit import SwiftyJSON import Alamofire import AlamofireImage class ViewController: UIViewController { var carsPicturesData = [JSON]() var previewURL: String = "" //var carModel : CarModel? let tempData = CarModel() @IBOutlet weak var carsTable: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. carsTable.delegate = self carsTable.dataSource = self self.fetchData(withQuery: "Cars") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func fetchData(withQuery query: String) { let URL = "https://pixabay.com/api/" let parameters = ["key" : "4608367-6e44818b4d4b3d9094faa3be8", "q" : query ] Alamofire.request(URL, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response :DataResponse<Any>) in if let value = response.result.value as? [String:Any] { let json = JSON(value) //print(json) self.carsPicturesData = json["hits"].array! //print("--------------------------------------------") // print(self.carsPicturesData) self.tempData.setValues(json) self.carsTable.reloadData() } else if let error = response.result.error { print(error) } } } } extension ViewController : UITableViewDelegate, UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return carsPicturesData.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ guard let cell = tableView.dequeueReusableCell(withIdentifier: "CarsTableID", for: indexPath) as? CarsTableCell else{fatalError("nil") } let ur = NSURL(string: self.tempData.getValue() ) as! URL cell.carsImageView.af_setImage(withURL: ur) return cell } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return 250.0 } } class CarsTableCell : UITableViewCell{ @IBOutlet weak var carsImageView: UIImageView! }
mit
d5744dad005434475ebe3deae3c82090
29.764706
145
0.519439
5.553982
false
false
false
false