repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
practicalswift/swift
test/decl/var/static_var.swift
8
15087
// RUN: %target-typecheck-verify-swift -parse-as-library // See also rdar://15626843. static var gvu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class var gvu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override static var gvu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override class var gvu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static override var gvu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class override var gvu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static var gvu7: Int { // expected-error {{static properties may only be declared on a type}}{{1-8=}} return 42 } class var gvu8: Int { // expected-error {{class properties may only be declared on a type}}{{1-7=}} return 42 } static let glu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} class let glu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} override static let glu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} override class let glu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static override let glu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} class override let glu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static var gvi1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class var gvi2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static var gvi3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class var gvi4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override var gvi5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override var gvi6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} static let gli1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class let gli2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static let gli3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class let gli4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override let gli5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override let gli6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} func inGlobalFunc() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{3-10=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{3-9=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{3-10=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{3-9=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } struct InMemberFunc { func member() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{5-12=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{5-11=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{5-12=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{5-11=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } } struct S { // expected-note 3{{extended type declared here}} expected-note{{did you mean 'S'?}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension S { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } enum E { // expected-note 3{{extended type declared here}} expected-note{{did you mean 'E'?}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension E { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } class C { // expected-note{{did you mean 'C'?}} static var v1: Int = 0 class final var v3: Int = 0 // expected-error {{class stored properties not supported}} class var v4: Int = 0 // expected-error {{class stored properties not supported}} static var v5: Int { return 0 } class var v6: Int { return 0 } static final var v7: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} class final let l3: Int = 0 // expected-error {{class stored properties not supported}} static final let l4 = 2 // expected-error {{static declarations are already final}} {{10-16=}} } extension C { static var ev1: Int = 0 class final var ev2: Int = 0 // expected-error {{class stored properties not supported}} class var ev3: Int = 0 // expected-error {{class stored properties not supported}} static var ev4: Int { return 0 } class var ev5: Int { return 0 } static final var ev6: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} class final let el3: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} static final let el4: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} } protocol P { // expected-note{{did you mean 'P'?}} expected-note{{extended type declared here}} // Both `static` and `class` property requirements are equivalent in protocols rdar://problem/17198298 static var v1: Int { get } class var v2: Int { get } // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}} static final var v3: Int { get } // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} class let l2: Int // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}} expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} } extension P { class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } struct S1 { // rdar://15626843 static var x: Int // expected-error {{'static var' declaration requires an initializer expression or getter/setter specifier}} var y = 1 static var z = 5 } extension S1 { static var zz = 42 static var xy: Int { return 5 } } enum E1 { static var y: Int { get {} } } class C1 { class var x: Int // expected-error {{class stored properties not supported}} expected-error {{'class var' declaration requires an initializer expression or getter/setter specifier}} } class C2 { var x: Int = 19 class var x: Int = 17 // expected-error{{class stored properties not supported}} func xx() -> Int { return self.x + C2.x } } class ClassHasVars { static var computedStatic: Int { return 0 } // expected-note 3{{overridden declaration is here}} final class var computedFinalClass: Int { return 0 } // expected-note 3{{overridden declaration is here}} class var computedClass: Int { return 0 } var computedInstance: Int { return 0 } } class ClassOverridesVars : ClassHasVars { override static var computedStatic: Int { return 1 } // expected-error {{cannot override static property}} override static var computedFinalClass: Int { return 1 } // expected-error {{static property overrides a 'final' class property}} override class var computedClass: Int { return 1 } override var computedInstance: Int { return 1 } } class ClassOverridesVars2 : ClassHasVars { override final class var computedStatic: Int { return 1 } // expected-error {{cannot override static property}} override final class var computedFinalClass: Int { return 1 } // expected-error {{class property overrides a 'final' class property}} } class ClassOverridesVars3 : ClassHasVars { override class var computedStatic: Int { return 1 } // expected-error {{cannot override static property}} override class var computedFinalClass: Int { return 1 } // expected-error {{class property overrides a 'final' class property}} } struct S2 { var x: Int = 19 static var x: Int = 17 func xx() -> Int { return self.x + C2.x } } // Mutating vs non-mutating conflict with static stored property witness - rdar://problem/19887250 protocol Proto { static var name: String {get set} } struct ProtoAdopter : Proto { static var name: String = "name" // no error, even though static setters aren't mutating } // Make sure the logic remains correct if we synthesized accessors for our stored property protocol ProtosEvilTwin { static var name: String {get set} } extension ProtoAdopter : ProtosEvilTwin {} // rdar://18990358 public struct Foo { // expected-note {{to match this opening '{'}}} public static let S { a // expected-error{{computed property must have an explicit type}} {{22-22=: <# Type #>}} // expected-error@-1{{type annotation missing in pattern}} // expected-error@-2{{'let' declarations cannot be computed properties}} {{17-20=var}} // expected-error@-3{{use of unresolved identifier 'a'}} } // expected-error@+1 {{expected '}' in struct}}
apache-2.0
76c3830e6fbf0fecf04471c48075b15f
54.877778
294
0.699012
3.900465
false
false
false
false
uchuugaka/OysterKit
Mac/OysterKit/OysterKitTests/Tests/stateTestRepeat.swift
1
2277
// // stateTestRepeat.swift // OysterKit Mac // // Created by Nigel Hughes on 03/07/2014. // Copyright (c) 2014 RED When Excited Limited. All rights reserved. // import XCTest import OysterKit class stateTestRepeat: XCTestCase { var tokenizer = Tokenizer() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. tokenizer = Tokenizer() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testRepeat2HexDigits(){ //Test for 2 tokenizer.branch( Repeat(state:OKStandard.hexDigit, min:2,max:2).token("xx"), OKStandard.eot ) XCTAssert(tokenizer.tokenize("AF") == [token("xx",chars:"AF")]) XCTAssert(tokenizer.tokenize("A") != [token("xx",chars:"A")]) XCTAssert(tokenizer.tokenize("AF00") == [token("xx",chars:"AF"),token("xx",chars:"00")]) } func testRepeat4HexDigits(){ tokenizer.branch( Repeat(state:OKStandard.hexDigit, min:4,max:4).token("xx"), OKStandard.eot ) XCTAssert(tokenizer.tokenize("AF00") == [token("xx",chars:"AF00")]) } func testRepeatXYFixed1(){ tokenizer.branch( Repeat(state:char("x").sequence(char("y").token("xy")),min:3,max:3).token("xyxyxy") ) XCTAssert(tokenizer.tokenize("xyxyxy") == [token("xyxyxy")]) } func testRepeatXYFixed2(){ tokenizer.branch( Repeat(state:Branch().branch( sequence(char("x"),char("y").token("xy")) ),min:3,max:3).token("xyxyxy"), OKStandard.eot ) XCTAssert(tokenizer.tokenize("xyxyxy") == [token("xyxyxy")]) } func testSentance(){ tokenizer.branch( OKStandard.word, OKStandard.whiteSpaces, OKStandard.eot ) XCTAssert(tokenizer.tokenize("Quick fox") == [token("word",chars: "Quick"), token("whitespace",chars: " "),token("word",chars: "fox")]) } }
bsd-2-clause
2f54f212b89e4ffd343f692b4c5e7e13
28.571429
143
0.562143
4.073345
false
true
false
false
tomquist/ReverseJson
Sources/ReverseJsonObjc/ObjcModelTranslator.swift
1
19513
import Foundation import ReverseJsonCore public struct ObjcModelCreator: ModelTranslator { public var atomic = false public var readonly = true public var createToJson = false public var typePrefix = "" private var atomicyModifier: String { return (atomic ? "atomic" : "nonatomic") } public init() {} public func translate(_ type: FieldType, name: String) -> [TranslatorOutput] { let a = declarationsFor(type, name: name, valueToParse: "jsonValue") var result: [TranslatorOutput] = Array(a.interfaces).sorted(by: { $0.name < $1.name }) let implementations: [TranslatorOutput] = a.implementations.sorted(by: { $0.name < $1.name }) result.append(contentsOf: implementations) return result } public func isNullable(_ type: FieldType) -> Bool { switch type { case .optional: return true default: return false } } func memoryManagementModifier(_ type: FieldType) -> String { switch type { case .optional(.number), .text: return "copy" case .number: return "assign" default: return "strong" } } struct ObjectiveCDeclaration { let interfaces: Set<TranslatorOutput> let implementations: Set<TranslatorOutput> let parseExpression: String let fieldRequiredTypeNames: Set<String> let fullTypeName: String let toJson: (String) -> String } struct ObjectFieldDeclaration { let property: String let initialization: String let requiredTypeNames: Set<String> let fieldTypeName: String let interfaces: Set<TranslatorOutput> let implementations: Set<TranslatorOutput> let toJson: String } private func fieldDeclarationFor(_ type: FieldType, variableNameBase: String? = nil, parentName: String, forceNullable: Bool, valueToParse: String) -> ObjectFieldDeclaration { let typeIsNullable = isNullable(type) let nullable = forceNullable || typeIsNullable let type = forceNullable && !typeIsNullable ? .optional(type) : type let nonOptionalVariableNameBase = variableNameBase ?? type.objectTypeName let variableName = nonOptionalVariableNameBase.pascalCased().asValidObjcIdentifier let subDeclaration = declarationsFor(type, name: "\(parentName)\(nonOptionalVariableNameBase.camelCasedString)", valueToParse: valueToParse) var modifiers = [atomicyModifier, memoryManagementModifier(type)] if (readonly) { modifiers.append("readonly") } if nullable { modifiers.append("nullable") } let modifierList = String(joined: modifiers, separator: ", ") let propertyName: String if subDeclaration.fullTypeName.hasSuffix("*") { propertyName = variableName } else { propertyName = " \(variableName)" } let property = "@property (\(modifierList)) \(subDeclaration.fullTypeName)\(propertyName);" let initialization = "_\(variableName) = \(subDeclaration.parseExpression);" let jsonReturnValue = subDeclaration.toJson("_\(variableName)") let toJson: String if let variableNameBase = variableNameBase { toJson = "ret[@\"\(variableNameBase)\"] = \(jsonReturnValue);" } else { toJson = "if (_\(variableName)) {\n return \(jsonReturnValue);\n}" } return ObjectFieldDeclaration(property: property, initialization: initialization, requiredTypeNames: subDeclaration.fieldRequiredTypeNames, fieldTypeName: subDeclaration.fullTypeName, interfaces: subDeclaration.interfaces, implementations: subDeclaration.implementations, toJson: toJson) } private func declarationsFor(_ type: FieldType, name: String, valueToParse: String, isOptional: Bool = false) -> ObjectiveCDeclaration { switch type { case let .enum(enumTypeName, enumTypes): let className = "\(typePrefix)\(enumTypeName ?? name.camelCasedString)" let fieldValues = enumTypes.sorted{$0.0.enumCaseName < $0.1.enumCaseName}.map { fieldDeclarationFor($0, parentName: (enumTypeName ?? name.camelCasedString), forceNullable: enumTypes.count > 1, valueToParse: "jsonValue") } let requiredTypeNames = Set(fieldValues.flatMap{$0.requiredTypeNames}) let forwardDeclarations = requiredTypeNames.sorted(by: <) let sortedFieldValues = fieldValues.sorted{$0.0.fieldTypeName < $0.1.fieldTypeName} let properties = sortedFieldValues.map {$0.property} let initializations = sortedFieldValues.map {$0.initialization.indent(2)} var interface = "#import <Foundation/Foundation.h>\n" if !forwardDeclarations.isEmpty { let forwardDeclarationList = String(joined: forwardDeclarations, separator: ", ") interface += "@class \(forwardDeclarationList);\n" } interface += String(joined: [ "NS_ASSUME_NONNULL_BEGIN", "@interface \(className) : NSObject", "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;", ] + (createToJson ? ["- (id<NSObject>)toJson;"] : []) + properties + [ "@end", "NS_ASSUME_NONNULL_END", ]) let imports = forwardDeclarations.map {"#import \"\($0).h\""} var implementationLines = [ "#import \"\(className).h\"", ] + imports + [ "@implementation \(className)", "- (instancetype)initWithJsonValue:(id)jsonValue {", " self = [super init];", " if (self) {", ] implementationLines += initializations implementationLines += [ " }", " return self;", "}", ] if createToJson { let toJsonImplementation = sortedFieldValues.map {$0.toJson}.joined(separator: " else ") implementationLines += [ "- (id<NSObject>)toJson {", toJsonImplementation.indent(1), " return nil;", "}" ] } implementationLines += [ "@end" ] let implementation = String(joined: implementationLines) let interfaces = fieldValues.lazy.map {$0.interfaces}.reduce(Set([TranslatorOutput(name: "\(className).h", content: interface)])) { $0.union($1) } let implementations = fieldValues.lazy.map{$0.implementations}.reduce(Set([TranslatorOutput(name: "\(className).m", content: implementation)])) { $0.union($1) } let parseExpression = "[[\(className) alloc] initWithJsonValue:\(valueToParse)]" return ObjectiveCDeclaration(interfaces: interfaces, implementations: implementations, parseExpression: parseExpression, fieldRequiredTypeNames: [className], fullTypeName: "\(className) *", toJson: { (name: String) in "[\(name) toJson]"}) case let .object(objectTypeName, fields): let className = "\(typePrefix)\(objectTypeName ?? name.camelCasedString)" let fieldValues = fields.sorted{$0.0.name < $0.1.name}.map { fieldDeclarationFor($0.type, variableNameBase: $0.name, parentName: objectTypeName ?? name.camelCasedString, forceNullable: false, valueToParse: "dict[@\"\($0.name)\"]") } let requiredTypeNames = Set(fieldValues.flatMap{$0.requiredTypeNames}) let forwardDeclarations = requiredTypeNames.sorted(by: <) let sortedFieldValues = fieldValues.sorted{$0.0.fieldTypeName < $0.1.fieldTypeName} let properties = sortedFieldValues.map {$0.property} let initializations = sortedFieldValues.map {$0.initialization.indent(2)} var interface = "#import <Foundation/Foundation.h>\n" if !forwardDeclarations.isEmpty { let forwardDeclarationList = String(joined: forwardDeclarations, separator: ", ") interface += "@class \(forwardDeclarationList);\n" } interface += String(joined: [ "NS_ASSUME_NONNULL_BEGIN", "@interface \(className) : NSObject", "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;", "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;", ] + (createToJson ? ["- (NSDictionary<NSString *, id<NSObject>> *)toJson;"] : []) + properties + [ "@end", "NS_ASSUME_NONNULL_END" ]) let imports = forwardDeclarations.map {"#import \"\($0).h\""} var implementationLines = [ "#import \"\(className).h\"" ] implementationLines += imports implementationLines += [ "@implementation \(className)", "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {", " self = [super init];", " if (self) {", ] implementationLines += initializations implementationLines += [ " }", " return self;", "}", "- (instancetype)initWithJsonValue:(id)jsonValue {", " if ([jsonValue isKindOfClass:[NSDictionary class]]) {", " self = [self initWithJsonDictionary:jsonValue];", " } else {", " self = nil;", " }", " return self;", "}", ] if createToJson { implementationLines += [ "- (NSDictionary<NSString *, id<NSObject>> *)toJson {", " NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithCapacity:\(sortedFieldValues.count)];", ] implementationLines += sortedFieldValues.map {$0.toJson.indent(1)} implementationLines += [ " return [ret copy];", "}", ] } implementationLines += [ "@end", ] let implementation = String(joined: implementationLines) let interfaces = fieldValues.lazy.map {$0.interfaces}.reduce(Set([TranslatorOutput(name: "\(className).h", content: interface)])) { $0.union($1) } let implementations = fieldValues.lazy.map{$0.implementations}.reduce(Set([TranslatorOutput(name: "\(className).m", content: implementation)])) { $0.union($1) } var parseExpression = "[[\(className) alloc] initWithJsonValue:\(valueToParse)]" if !isOptional { parseExpression = "(\(parseExpression) ?: [[\(className) alloc] initWithJsonDictionary:@{}])" } return ObjectiveCDeclaration(interfaces: interfaces, implementations: implementations, parseExpression: parseExpression, fieldRequiredTypeNames: [className], fullTypeName: "\(className) *", toJson: { (name: String) in "[\(name) toJson]"}) case .text: let fallback = isOptional ? "nil" : "@\"\"" return ObjectiveCDeclaration(interfaces: [], implementations: [], parseExpression: "[\(valueToParse) isKindOfClass:[NSString class]] ? \(valueToParse) : \(fallback)", fieldRequiredTypeNames: [], fullTypeName: "NSString *", toJson: { $0 }) case let .number(numberType): return ObjectiveCDeclaration(interfaces: [], implementations: [], parseExpression: "[\(valueToParse) isKindOfClass:[NSNumber class]] ? [\(valueToParse) \(numberType.objcNSNumberMethod)] : 0", fieldRequiredTypeNames: [], fullTypeName: numberType.objcNumberType, toJson: { (name: String) in "@(\(name))" }) case let .list(origListType): var listType = origListType if case let .number(numberType) = listType { listType = .optional(.number(numberType)) } let subName: String if case .list = listType { subName = name } else { subName = "\(name)Item" } let listTypeValues = declarationsFor(listType, name: subName, valueToParse: "item") let subParseExpression: String if let lineBreakRange = listTypeValues.parseExpression.range(of: "\n") { let firstLine = listTypeValues.parseExpression.substring(to: lineBreakRange.lowerBound) let remainingLines = listTypeValues.parseExpression.substring(from: lineBreakRange.lowerBound).indent(3) subParseExpression = "\(firstLine)\n\(remainingLines)" } else { subParseExpression = listTypeValues.parseExpression; } let listTypeName: String if listTypeValues.fullTypeName.hasSuffix("*") { listTypeName = listTypeValues.fullTypeName } else { listTypeName = "\(listTypeValues.fullTypeName) " } let fallback = isOptional ? "" : " ?: @[]" let parseExpression = String(lines: "({", " id value = \(valueToParse);", " NSMutableArray<\(listTypeValues.fullTypeName)> *values = nil;", " if ([value isKindOfClass:[NSArray class]]) {", " NSArray *array = value;", " values = [NSMutableArray arrayWithCapacity:array.count];", " for (id item in array) {", " \(listTypeName)parsedItem = \(subParseExpression);", " [values addObject:parsedItem ?: (id)[NSNull null]];", " }", " }", " [values copy]\(fallback);", "})" ) let valueToJson = listTypeValues.toJson("item") let subValueToJson: String if let lineBreakRange = valueToJson.range(of: "\n") { let firstLine = valueToJson.substring(to: lineBreakRange.lowerBound) let remainingLines = valueToJson.substring(from: lineBreakRange.lowerBound).indent(3) subValueToJson = "\(firstLine)\n\(remainingLines)" } else { subValueToJson = valueToJson; } let toJson = { (variableName: String) -> String in return String(lines: "({", " NSMutableArray<id<NSObject>> *values = nil;", " NSArray *array = \(variableName);", " if (array) {", " values = [NSMutableArray arrayWithCapacity:array.count];", " for (id item in array) {", " if (item == [NSNull null]) {", " [values addObject:item];", " } else {", " id json = \(subValueToJson);", " [values addObject:json ?: (id)[NSNull null]];", " }", " }", " }", " [values copy]\(fallback);", "})") } return ObjectiveCDeclaration(interfaces: listTypeValues.interfaces, implementations: listTypeValues.implementations, parseExpression: parseExpression, fieldRequiredTypeNames: listTypeValues.fieldRequiredTypeNames, fullTypeName: "NSArray<\(listTypeValues.fullTypeName)> *", toJson: toJson) case let .optional(.number(numberType)): return ObjectiveCDeclaration(interfaces: [], implementations: [], parseExpression: "[\(valueToParse) isKindOfClass:[NSNumber class]] ? \(valueToParse) : nil", fieldRequiredTypeNames: [], fullTypeName: "NSNumber/*\(numberType.objcNumberType)*/ *", toJson: {$0}) case .optional(let optionalType): return declarationsFor(optionalType, name: name, valueToParse: valueToParse, isOptional: true) case .unknown: return ObjectiveCDeclaration(interfaces: [], implementations: [], parseExpression: valueToParse, fieldRequiredTypeNames: [], fullTypeName: "id<NSObject>", toJson: {$0}) } } } extension FieldType { fileprivate var objectTypeName: String { switch self { case let .object(name?, _): return name case let .enum(name?, _): return name case let .optional(type): return type.objectTypeName default: return enumCaseName } } } extension NumberType { fileprivate var objcNumberType: String { switch self { case .bool: return "BOOL" case .int: return "NSInteger" case .float: return "float" case .double: return "double" } } fileprivate var objcNSNumberMethod: String { switch self { case .bool: return "boolValue" case .int: return "integerValue" case .float: return "floatValue" case .double: return "doubleValue" } } }
mit
d94bff0087e4cc75c7fdff05d723318a
47.660848
179
0.511351
5.629833
false
false
false
false
safx/EJDB-Swift
Source/List.swift
1
1365
// // List.swift // EJDB-Swift // // Created by Safx Developer on 2015/07/28. // Copyright © 2015年 Safx Developers. All rights reserved. // import Foundation public protocol RawMemoryConvertible { init(memory: UnsafePointer<Int8>) } public final class OpaqueList<T: RawMemoryConvertible> { private(set) var list: UnsafeMutablePointer<TCLIST> public init(list: UnsafeMutablePointer<TCLIST>) { self.list = list } deinit { ejdbqresultdispose(list) } public var count: Int { return Int(ejdbqresultnum(list)) } } extension OpaqueList: SequenceType { public typealias Generator = OpaqueItemGenerator<T> public func generate() -> Generator { return OpaqueItemGenerator(list: list) } } public final class OpaqueItemGenerator<T: RawMemoryConvertible>: GeneratorType { private let list: UnsafeMutablePointer<TCLIST> private(set) var index: Int = 0 public init(list: UnsafeMutablePointer<TCLIST>) { self.list = list } private var length: Int { return Int(tclistnum(list)) } public func next() -> T? { if index < length { let memPtr = list.memory.array.advancedBy(index).memory.ptr // FIXME: remove `memory` ++index return T(memory: memPtr) } return nil } }
mit
acdd6744b4704c49c83f6a24802e3440
20.967742
97
0.639501
3.947826
false
false
false
false
HarukaMa/iina
iina/MPVCommand.swift
1
5563
import Foundation struct MPVCommand: RawRepresentable { typealias RawValue = String var rawValue: RawValue init(_ string: String) { self.rawValue = string } init?(rawValue: RawValue) { self.rawValue = rawValue } /** ignore */ static let ignore = MPVCommand("ignore") /** seek <seconds> [relative|absolute|absolute-percent|relative-percent|exact|keyframes] */ static let seek = MPVCommand("seek") /** revert-seek [mode] */ static let revertSeek = MPVCommand("revert-seek") /** frame-step */ static let frameStep = MPVCommand("frame-step") /** frame-back-step */ static let frameBackStep = MPVCommand("frame-back-step") /** set <property> "<value>" */ static let set = MPVCommand("set") /** add <property> [<value>] */ static let add = MPVCommand("add") /** cycle <property> [up|down] */ static let cycle = MPVCommand("cycle") /** multiply <property> <factor> */ static let multiply = MPVCommand("multiply") /** screenshot [subtitles|video|window|- [single|each-frame]] */ static let screenshot = MPVCommand("screenshot") /** screenshot-to-file "<filename>" [subtitles|video|window] */ static let screenshotToFile = MPVCommand("screenshot-to-file") /** playlist-next [weak|force] */ static let playlistNext = MPVCommand("playlist-next") /** playlist-prev [weak|force] */ static let playlistPrev = MPVCommand("playlist-prev") /** loadfile "<file>" [replace|append|append-play [options]] */ static let loadfile = MPVCommand("loadfile") /** loadlist "<playlist>" [replace|append] */ static let loadlist = MPVCommand("loadlist") /** playlist-clear */ static let playlistClear = MPVCommand("playlist-clear") /** playlist-remove current|<index> */ static let playlistRemove = MPVCommand("playlist-remove") /** playlist-move <index1> <index2> */ static let playlistMove = MPVCommand("playlist-move") /** playlist-shuffle */ static let playlistShuffle = MPVCommand("playlist-shuffle") /** run "command" "arg1" "arg2" ... */ static let run = MPVCommand("run") /** quit [<code>] */ static let quit = MPVCommand("quit") /** quit-watch-later [<code>] */ static let quitWatchLater = MPVCommand("quit-watch-later") /** sub-add "<file>" [<flags> [<title> [<lang>]]] */ static let subAdd = MPVCommand("sub-add") /** sub-remove [<id>] */ static let subRemove = MPVCommand("sub-remove") /** sub-reload [<id>] */ static let subReload = MPVCommand("sub-reload") /** sub-step <skip> */ static let subStep = MPVCommand("sub-step") /** sub-seek <skip> */ static let subSeek = MPVCommand("sub-seek") /** osd [<level>] */ static let osd = MPVCommand("osd") /** print-text "<string>" */ static let printText = MPVCommand("print-text") /** show-text "<string>" [<duration>|- [<level>]] */ static let showText = MPVCommand("show-text") /** show-progress */ static let showProgress = MPVCommand("show-progress") /** write-watch-later-config */ static let writeWatchLaterConfig = MPVCommand("write-watch-later-config") /** stop */ static let stop = MPVCommand("stop") /** mouse <x> <y> [<button> [single|double]] */ static let mouse = MPVCommand("mouse") /** keypress <key_name> */ static let keypress = MPVCommand("keypress") /** keydown <key_name> */ static let keydown = MPVCommand("keydown") /** keyup [<key_name>] */ static let keyup = MPVCommand("keyup") /** audio-add "<file>" [<flags> [<title> [<lang>]]] */ static let audioAdd = MPVCommand("audio-add") /** audio-remove [<id>] */ static let audioRemove = MPVCommand("audio-remove") /** audio-reload [<id>] */ static let audioReload = MPVCommand("audio-reload") /** rescan-external-files [<mode>] */ static let rescanExternalFiles = MPVCommand("rescan-external-files") /** af set|add|toggle|del|clr "filter1=params,filter2,..." */ static let af = MPVCommand("af") /** vf set|add|toggle|del|clr "filter1=params,filter2,..." */ static let vf = MPVCommand("vf") /** cycle-values ["!reverse"] <property> "<value1>" "<value2>" ... */ static let cycleValues = MPVCommand("cycle-values") /** enable-section "<section>" [flags] */ static let enableSection = MPVCommand("enable-section") /** disable-section "<section>" */ static let disableSection = MPVCommand("disable-section") /** define-section "<section>" "<contents>" [default|force] */ static let defineSection = MPVCommand("define-section") /** overlay-add <id> <x> <y> "<file>" <offset> "<fmt>" <w> <h> <stride> */ static let overlayAdd = MPVCommand("overlay-add") /** overlay-remove <id> */ static let overlayRemove = MPVCommand("overlay-remove") /** script-message "<arg1>" "<arg2>" ... */ static let scriptMessage = MPVCommand("script-message") /** script-message-to "<target>" "<arg1>" "<arg2>" ... */ static let scriptMessageTo = MPVCommand("script-message-to") /** script-binding "<name>" */ static let scriptBinding = MPVCommand("script-binding") /** ab-loop */ static let abLoop = MPVCommand("ab-loop") /** drop-buffers */ static let dropBuffers = MPVCommand("drop-buffers") /** screenshot-raw [subtitles|video|window] */ static let screenshotRaw = MPVCommand("screenshot-raw") /** vf-command "<label>" "<cmd>" "<args>" */ static let vfCommand = MPVCommand("vf-command") /** af-command "<label>" "<cmd>" "<args>" */ static let afCommand = MPVCommand("af-command") /** apply-profile "<name>" */ static let applyProfile = MPVCommand("apply-profile") /** load-script "<path>" */ static let loadScript = MPVCommand("load-script") }
gpl-3.0
65b2331f4e712439e4ea1d41cda7ebc7
41.465649
93
0.65684
3.836552
false
false
false
false
Ribeiro/Alamofire
Tests/ParameterEncodingTests.swift
69
19954
// ParameterEncodingTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import XCTest class ParameterEncodingTestCase: BaseTestCase { let URLRequest = NSURLRequest(URL: NSURL(string: "http://example.com/")!) } // MARK: - class URLParameterEncodingTestCase: ParameterEncodingTestCase { // MARK: Properties let encoding: ParameterEncoding = .URL // MARK: Tests - Parameter Types func testURLParameterEncodeNilParameters() { // Given // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: nil) // Then XCTAssertNil(URLRequest.URL?.query, "query should be nil") } func testURLParameterEncodeOneStringKeyStringValueParameter() { // Given let parameters = ["foo": "bar"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo=bar", "query is incorrect") } func testURLParameterEncodeOneStringKeyStringValueParameterAppendedToQuery() { // Given var mutableURLRequest = self.URLRequest.mutableCopy() as! NSMutableURLRequest let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false)! URLComponents.query = "baz=qux" mutableURLRequest.URL = URLComponents.URL let parameters = ["foo": "bar"] // When let (URLRequest, error) = encoding.encode(mutableURLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "baz=qux&foo=bar", "query is incorrect") } func testURLParameterEncodeTwoStringKeyStringValueParameters() { // Given let parameters = ["foo": "bar", "baz": "qux"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "baz=qux&foo=bar", "query is incorrect") } func testURLParameterEncodeStringKeyIntegerValueParameter() { // Given let parameters = ["foo": 1] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo=1", "query is incorrect") } func testURLParameterEncodeStringKeyDoubleValueParameter() { // Given let parameters = ["foo": 1.1] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo=1.1", "query is incorrect") } func testURLParameterEncodeStringKeyBoolValueParameter() { // Given let parameters = ["foo": true] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo=1", "query is incorrect") } func testURLParameterEncodeStringKeyArrayValueParameter() { // Given let parameters = ["foo": ["a", 1, true]] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo%5B%5D=a&foo%5B%5D=1&foo%5B%5D=1", "query is incorrect") } func testURLParameterEncodeStringKeyDictionaryValueParameter() { // Given let parameters = ["foo": ["bar": 1]] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo%5Bbar%5D=1", "query is incorrect") } func testURLParameterEncodeStringKeyNestedDictionaryValueParameter() { // Given let parameters = ["foo": ["bar": ["baz": 1]]] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo%5Bbar%5D%5Bbaz%5D=1", "query is incorrect") } func testURLParameterEncodeStringKeyNestedDictionaryArrayValueParameter() { // Given let parameters = ["foo": ["bar": ["baz": ["a", 1, true]]]] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo%5Bbar%5D%5Bbaz%5D%5B%5D=a&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1", "query is incorrect") } // MARK: Tests - All Reserved / Unreserved / Illegal Characters According to RFC 3986 func testThatReservedCharactersArePercentEscapedMinusQuestionMarkAndForwardSlash() { // Given let generalDelimiters = ":#[]@" let subDelimiters = "!$&'()*+,;=" let parameters = ["reserved": "\(generalDelimiters)\(subDelimiters)"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D", "query is incorrect") } func testThatReservedCharactersQuestionMarkAndForwardSlashAreNotPercentEscaped() { // Given let parameters = ["reserved": "?/"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "reserved=?/", "query is incorrect") } func testThatUnreservedNumericCharactersAreNotPercentEscaped() { // Given let parameters = ["numbers": "0123456789"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "numbers=0123456789", "query is incorrect") } func testThatUnreservedLowercaseCharactersAreNotPercentEscaped() { // Given let parameters = ["lowercase": "abcdefghijklmnopqrstuvwxyz"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "lowercase=abcdefghijklmnopqrstuvwxyz", "query is incorrect") } func testThatUnreservedUppercaseCharactersAreNotPercentEscaped() { // Given let parameters = ["uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "uppercase=ABCDEFGHIJKLMNOPQRSTUVWXYZ", "query is incorrect") } func testThatIllegalASCIICharactersArePercentEscaped() { // Given let parameters = ["illegal": " \"#%<>[]\\^`{}|"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "illegal=%20%22%23%25%3C%3E%5B%5D%5C%5E%60%7B%7D%7C", "query is incorrect") } // MARK: Tests - Special Character Queries func testURLParameterEncodeStringWithAmpersandKeyStringWithAmpersandValueParameter() { // Given let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo%26bar=baz%26qux&foobar=bazqux", "query is incorrect") } func testURLParameterEncodeStringWithQuestionMarkKeyStringWithQuestionMarkValueParameter() { // Given let parameters = ["?foo?": "?bar?"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "?foo?=?bar?", "query is incorrect") } func testURLParameterEncodeStringWithSlashKeyStringWithQuestionMarkValueParameter() { // Given let parameters = ["foo": "/bar/baz/qux"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "foo=/bar/baz/qux", "query is incorrect") } func testURLParameterEncodeStringWithSpaceKeyStringWithSpaceValueParameter() { // Given let parameters = [" foo ": " bar "] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "%20foo%20=%20bar%20", "query is incorrect") } func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameter() { // Given let parameters = ["+foo+": "+bar+"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "%2Bfoo%2B=%2Bbar%2B", "query is incorrect") } func testURLParameterEncodeStringKeyPercentEncodedStringValueParameter() { // Given let parameters = ["percent": "%25"] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "percent=%2525", "query is incorrect") } func testURLParameterEncodeStringKeyNonLatinStringValueParameter() { // Given let parameters = [ "french": "français", "japanese": "日本語", "arabic": "العربية", "emoji": "😃" ] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9&emoji=%F0%9F%98%83&french=fran%C3%A7ais&japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E", "query is incorrect") } func testURLParameterEncodeStringForRequestWithPrecomposedQuery() { // Given let URL = NSURL(string: "http://example.com/movies?hd=[1]")! let parameters = ["page": "0"] // When let (URLRequest, error) = encoding.encode(NSURLRequest(URL: URL), parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "hd=%5B1%5D&page=0", "query is incorrect") } func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameterForRequestWithPrecomposedQuery() { // Given let URL = NSURL(string: "http://example.com/movie?hd=[1]")! let parameters = ["+foo+": "+bar+"] // When let (URLRequest, error) = encoding.encode(NSURLRequest(URL: URL), parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "hd=%5B1%5D&%2Bfoo%2B=%2Bbar%2B", "query is incorrect") } // MARK: Tests - Varying HTTP Methods func testURLParameterEncodeGETParametersInURL() { // Given var mutableURLRequest = self.URLRequest.mutableCopy() as! NSMutableURLRequest mutableURLRequest.HTTPMethod = Method.GET.rawValue let parameters = ["foo": 1, "bar": 2] // When let (URLRequest, error) = encoding.encode(mutableURLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.URL?.query ?? "", "bar=2&foo=1", "query is incorrect") XCTAssertNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil") XCTAssertNil(URLRequest.HTTPBody, "HTTPBody should be nil") } func testURLParameterEncodePOSTParametersInHTTPBody() { // Given var mutableURLRequest = self.URLRequest.mutableCopy() as! NSMutableURLRequest mutableURLRequest.HTTPMethod = Method.POST.rawValue let parameters = ["foo": 1, "bar": 2] // When let (URLRequest, error) = encoding.encode(mutableURLRequest, parameters: parameters) // Then XCTAssertEqual(URLRequest.valueForHTTPHeaderField("Content-Type") ?? "", "application/x-www-form-urlencoded", "Content-Type should be application/x-www-form-urlencoded") XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil") if let HTTPBody = URLRequest.HTTPBody, decodedHTTPBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding) { XCTAssertEqual(decodedHTTPBody, "bar=2&foo=1", "HTTPBody is incorrect") } else { XCTFail("decoded http body should not be nil") } } } // MARK: - class JSONParameterEncodingTestCase: ParameterEncodingTestCase { // MARK: Properties let encoding: ParameterEncoding = .JSON // MARK: Tests func testJSONParameterEncodeNilParameters() { // Given // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: nil) // Then XCTAssertNil(error, "error should be nil") XCTAssertNil(URLRequest.URL?.query, "query should be nil") XCTAssertNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil") XCTAssertNil(URLRequest.HTTPBody, "HTTPBody should be nil") } func testJSONParameterEncodeComplexParameters() { // Given let parameters = [ "foo": "bar", "baz": ["a", 1, true], "qux": [ "a": 1, "b": [2, 2], "c": [3, 3, 3] ] ] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertNil(error, "error should be nil") XCTAssertNil(URLRequest.URL?.query, "query should be nil") XCTAssertNotNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil") XCTAssertEqual(URLRequest.valueForHTTPHeaderField("Content-Type") ?? "", "application/json", "Content-Type should be application/json") XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil") if let HTTPBody = URLRequest.HTTPBody, JSON = NSJSONSerialization.JSONObjectWithData(HTTPBody, options: .AllowFragments, error: nil) as? NSObject { XCTAssertEqual(JSON, parameters as NSObject, "HTTPBody JSON does not equal parameters") } else { XCTFail("JSON should not be nil") } } } // MARK: - class PropertyListParameterEncodingTestCase: ParameterEncodingTestCase { // MARK: Properties let encoding: ParameterEncoding = .PropertyList(.XMLFormat_v1_0, 0) // MARK: Tests func testPropertyListParameterEncodeNilParameters() { // Given // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: nil) // Then XCTAssertNil(error, "error should be nil") XCTAssertNil(URLRequest.URL?.query, "query should be nil") XCTAssertNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil") XCTAssertNil(URLRequest.HTTPBody, "HTTPBody should be nil") } func testPropertyListParameterEncodeComplexParameters() { // Given let parameters = [ "foo": "bar", "baz": ["a", 1, true], "qux": [ "a": 1, "b": [2, 2], "c": [3, 3, 3] ] ] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertNil(error, "error should be nil") XCTAssertNil(URLRequest.URL?.query, "query should be nil") XCTAssertNotNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil") XCTAssertEqual(URLRequest.valueForHTTPHeaderField("Content-Type") ?? "", "application/x-plist", "Content-Type should be application/x-plist") XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil") if let HTTPBody = URLRequest.HTTPBody, plist = NSPropertyListSerialization.propertyListWithData(HTTPBody, options: 0, format: nil, error: nil) as? NSObject { XCTAssertEqual(plist, parameters as NSObject, "HTTPBody plist does not equal parameters") } else { XCTFail("plist should not be nil") } } func testPropertyListParameterEncodeDateAndDataParameters() { // Given let date: NSDate = NSDate() let data: NSData = "data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let parameters = [ "date": date, "data": data ] // When let (URLRequest, error) = encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertNil(error, "error should be nil") XCTAssertNil(URLRequest.URL?.query, "query should be nil") XCTAssertNotNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil") XCTAssertEqual(URLRequest.valueForHTTPHeaderField("Content-Type") ?? "", "application/x-plist", "Content-Type should be application/x-plist") XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil") if let HTTPBody = URLRequest.HTTPBody, plist = NSPropertyListSerialization.propertyListWithData(HTTPBody, options: 0, format: nil, error: nil) as? NSObject { XCTAssertTrue(plist.valueForKey("date") is NSDate, "date is not NSDate") XCTAssertTrue(plist.valueForKey("data") is NSData, "data is not NSData") } else { XCTFail("plist should not be nil") } } } // MARK: - class CustomParameterEncodingTestCase: ParameterEncodingTestCase { // MARK: Tests func testCustomParameterEncode() { // Given let encodingClosure: (URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) = { URLRequest, parameters in let mutableURLRequest = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest mutableURLRequest.setValue("Xcode", forHTTPHeaderField: "User-Agent") return (mutableURLRequest, nil) } // When let encoding: ParameterEncoding = .Custom(encodingClosure) // Then let URL = NSURL(string: "http://example.com")! let URLRequest = NSURLRequest(URL: URL) let parameters: [String: AnyObject] = [:] XCTAssertEqual(encoding.encode(URLRequest, parameters: parameters).0, encodingClosure(URLRequest, parameters).0, "URLRequest should be equal") } }
mit
a99b47ab809ba38a7db078527a97452b
35.577982
203
0.640682
4.634969
false
true
false
false
boolkybear/ChromaProjectApp
ChromaProjectApp/ChromaProjectApp/Classes/EditController.swift
1
3739
// // EditController.swift // ChromaProjectApp // // Created by Boolky Bear on 26/1/15. // Copyright (c) 2015 ByBDesigns. All rights reserved. // import UIKit typealias CreationHandler = (ChromaDocument)->Void class EditController: UIViewController { @IBOutlet var previewImageView: UIImageView? @IBOutlet var tableView: UITableView? @IBOutlet var nameField: UITextField? var document: ChromaDocument? var creationHandler: CreationHandler? var documentViewModel: DocumentViewModel? 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. } /* // 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. } */ func setDocument(document: ChromaDocument?, onCreate: CreationHandler?) { self.document = document if self.document == nil { self.creationHandler = onCreate } self.documentViewModel = DocumentViewModel() self.documentViewModel?.document = self.document self.tableView?.reloadData() self.nameField?.text = self.documentViewModel?.name ?? "" } } extension EditController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() if let name = nameField?.text { if let document = self.document { document.setName(name) self.creationHandler?(document) } else { let localDocumentsPath = NSFileManager.localDocumentsPath() let randomName = NSUUID().UUIDString let pathExtension = ChromaDocument.validExtensions().first ?? "chroma" let filePath = "\(localDocumentsPath)/\(randomName).\(pathExtension)" if let fileUrl = NSURL.fileURLWithPath(filePath) { let newDocument = ChromaDocument(fileURL: fileUrl) newDocument.saveToURL(fileUrl, forSaveOperation: UIDocumentSaveOperation.ForCreating) { success in if success { self.creationHandler?(newDocument) newDocument.setName(name) } } } } } return true } } extension EditController: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.documentViewModel?.count() ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = { let visibleLayer = self.documentViewModel?[indexPath.row] if let layerType = visibleLayer?.type { let visibleCell: VisibilityCell? = { switch layerType { case .Caption: return tableView.dequeueReusableCellWithIdentifier("CaptionCell") as? VisibilityCaptionCell case .Chroma: return tableView.dequeueReusableCellWithIdentifier("ChromaCell") as? VisibilityLayerCell case .Background: return tableView.dequeueReusableCellWithIdentifier("BackgroundCell") as? VisibilityBackgroundCell } }() if let visibleCell = visibleCell { visibleCell.visibleLayer = visibleLayer return visibleCell } } return UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "DefaultCell") }() return cell } }
mit
62b3b79483e1794502fb30c572597aa8
25.153846
106
0.708211
4.504819
false
false
false
false
codevlabs/Screenotate
Screenotate/Tesseract.swift
2
1160
// // Tesseract.swift // Screenotate // // Created by Omar Rizwan on 7/17/15. // Copyright (c) 2015 Omar Rizwan. All rights reserved. // import Foundation let resourcePath = NSBundle.mainBundle().resourcePath! let tesseractPath = resourcePath.stringByAppendingPathComponent("tesseract") func pngToText(png: NSData) -> String { // So we're going to use a hack here. // We're going to write png to a temporary file: let fileName = NSString(format: "%@_%@", NSProcessInfo.processInfo().globallyUniqueString, "tmp.png") let fileURL = NSURL.fileURLWithPath(NSTemporaryDirectory().stringByAppendingPathComponent(fileName as String))! png.writeToURL(fileURL, atomically: true) // And then we're going to tell tesseract to read that file: let task = NSTask() task.launchPath = tesseractPath task.arguments = [ "--tessdata-dir", resourcePath, fileURL.path!, "stdout" ] let outPipe = NSPipe() task.standardOutput = outPipe let outHandle = outPipe.fileHandleForReading task.launch() return NSString(data: outHandle.readDataToEndOfFile(), encoding: NSUTF8StringEncoding) as! String }
gpl-3.0
480934963d472122c1f3650d36915cba
30.351351
115
0.709483
4.377358
false
false
false
false
rasmusth/BluetoothKit
Example/Source/View Controllers/PeripheralViewController.swift
1
5516
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import SnapKit import BluetoothKit import CryptoSwift internal class PeripheralViewController: UIViewController, AvailabilityViewController, BKPeripheralDelegate, LoggerDelegate, BKRemotePeerDelegate { // MARK: Properties internal var availabilityView = AvailabilityView() private let peripheral = BKPeripheral() private let logTextView = UITextView() private lazy var sendDataBarButtonItem: UIBarButtonItem! = { UIBarButtonItem(title: "Send Data", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PeripheralViewController.sendData)) }() // MARK: UIViewController Life Cycle internal override func viewDidLoad() { navigationItem.title = "Peripheral" view.backgroundColor = UIColor.white Logger.delegate = self applyAvailabilityView() logTextView.isEditable = false logTextView.alwaysBounceVertical = true view.addSubview(logTextView) applyConstraints() startPeripheral() sendDataBarButtonItem.isEnabled = false navigationItem.rightBarButtonItem = sendDataBarButtonItem } deinit { _ = try? peripheral.stop() } // MARK: Functions private func applyConstraints() { logTextView.snp.makeConstraints { make in make.top.equalTo(topLayoutGuide.snp.bottom) make.leading.trailing.equalTo(view) make.bottom.equalTo(availabilityView.snp.top) } } private func startPeripheral() { do { peripheral.delegate = self peripheral.addAvailabilityObserver(self) let dataServiceUUID = UUID(uuidString: "6E6B5C64-FAF7-40AE-9C21-D4933AF45B23")! let dataServiceCharacteristicUUID = UUID(uuidString: "477A2967-1FAB-4DC5-920A-DEE5DE685A3D")! let localName = Bundle.main.infoDictionary!["CFBundleName"] as? String let configuration = BKPeripheralConfiguration(dataServiceUUID: dataServiceUUID, dataServiceCharacteristicUUID: dataServiceCharacteristicUUID, localName: localName) try peripheral.startWithConfiguration(configuration) Logger.log("Awaiting connections from remote centrals") } catch let error { print("Error starting: \(error)") } } private func refreshControls() { sendDataBarButtonItem.isEnabled = peripheral.connectedRemoteCentrals.count > 0 } // MARK: Target Actions @objc private func sendData() { let numberOfBytesToSend: Int = Int(arc4random_uniform(950) + 50) let data = Data.dataWithNumberOfBytes(numberOfBytesToSend) Logger.log("Prepared \(numberOfBytesToSend) bytes with MD5 hash: \(data.md5().toHexString())") for remoteCentral in peripheral.connectedRemoteCentrals { Logger.log("Sending to \(remoteCentral)") peripheral.sendData(data, toRemotePeer: remoteCentral) { data, remoteCentral, error in guard error == nil else { Logger.log("Failed sending to \(remoteCentral)") return } Logger.log("Sent to \(remoteCentral)") } } } // MARK: BKPeripheralDelegate internal func peripheral(_ peripheral: BKPeripheral, remoteCentralDidConnect remoteCentral: BKRemoteCentral) { Logger.log("Remote central did connect: \(remoteCentral)") remoteCentral.delegate = self refreshControls() } internal func peripheral(_ peripheral: BKPeripheral, remoteCentralDidDisconnect remoteCentral: BKRemoteCentral) { Logger.log("Remote central did disconnect: \(remoteCentral)") refreshControls() } // MARK: BKRemotePeerDelegate func remotePeer(_ remotePeer: BKRemotePeer, didSendArbitraryData data: Data) { Logger.log("Received data of length: \(data.count) with hash: \(data.md5().toHexString())") } // MARK: LoggerDelegate internal func loggerDidLogString(_ string: String) { if logTextView.text.characters.count > 0 { logTextView.text = logTextView.text + ("\n" + string) } else { logTextView.text = string } logTextView.scrollRangeToVisible(NSRange(location: logTextView.text.characters.count - 1, length: 1)) } }
mit
5be8a4b83942b3b1c62f74cc80d6d400
39.262774
207
0.690174
4.951526
false
false
false
false
stripe/stripe-ios
StripePayments/StripePayments/API Bindings/Legacy Compatability/StripeAPI+Deprecated.swift
1
4551
// // StripeAPI+Deprecated.swift // StripePayments // // Created by David Estes on 10/15/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import Foundation import PassKit extension StripeAPI { /// A convenience method to build a `PKPaymentRequest` with sane default values. /// You will still need to configure the `paymentSummaryItems` property to indicate /// what the user is purchasing, as well as the optional `requiredShippingAddressFields`, /// `requiredBillingAddressFields`, and `shippingMethods` properties to indicate /// what contact information your application requires. /// Note that this method sets the payment request's countryCode to "US" and its /// currencyCode to "USD". /// - Parameter merchantIdentifier: Your Apple Merchant ID. /// - Returns: a `PKPaymentRequest` with proper default values. Returns nil if running on < iOS8. /// @deprecated Use `paymentRequestWithMerchantIdentifier:country:currency:` instead. /// Apple Pay is available in many countries and currencies, and you should use /// the appropriate values for your business. @available( *, deprecated, message: "Use `paymentRequestWithMerchantIdentifier:country:currency:` instead." ) @objc(paymentRequestWithMerchantIdentifier:) public class func paymentRequest( withMerchantIdentifier merchantIdentifier: String ) -> PKPaymentRequest { return self.paymentRequest( withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD" ) } } // MARK: Deprecated top-level Stripe functions. // These are included so Xcode can offer guidance on how to replace top-level Stripe usage. /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.defaultPublishableKey instead. (StripeAPI.defaultPublishableKey = \"pk_12345_xyzabc\")" ) public func setDefaultPublishableKey(_ publishableKey: String) { StripeAPI.defaultPublishableKey = publishableKey } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.advancedFraudSignalsEnabled instead." ) public var advancedFraudSignalsEnabled: Bool { get { StripeAPI.advancedFraudSignalsEnabled } set { StripeAPI.advancedFraudSignalsEnabled = newValue } } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.jcbPaymentNetworkSupported instead." ) public var jcbPaymentNetworkSupported: Bool { get { StripeAPI.jcbPaymentNetworkSupported } set { StripeAPI.jcbPaymentNetworkSupported = newValue } } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.additionalEnabledApplePayNetworks instead." ) public var additionalEnabledApplePayNetworks: [PKPaymentNetwork] { get { StripeAPI.additionalEnabledApplePayNetworks } set { StripeAPI.additionalEnabledApplePayNetworks = newValue } } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.canSubmitPaymentRequest(_:) instead." ) public func canSubmitPaymentRequest(_ paymentRequest: PKPaymentRequest) -> Bool { return StripeAPI.canSubmitPaymentRequest(paymentRequest) } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.deviceSupportsApplePay() instead." ) public func deviceSupportsApplePay() -> Bool { return StripeAPI.deviceSupportsApplePay() } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.paymentRequest(withMerchantIdentifier:country:currency:) instead." ) public func paymentRequest( withMerchantIdentifier merchantIdentifier: String, country countryCode: String, currency currencyCode: String ) -> PKPaymentRequest { return StripeAPI.paymentRequest( withMerchantIdentifier: merchantIdentifier, country: countryCode, currency: currencyCode ) } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.paymentRequest(withMerchantIdentifier:country:currency:) instead." ) func paymentRequest( withMerchantIdentifier merchantIdentifier: String ) -> PKPaymentRequest { return StripeAPI.paymentRequest( withMerchantIdentifier: merchantIdentifier, country: "US", currency: "USD" ) } /// :nodoc: @available( *, deprecated, message: "Use StripeAPI.handleURLCallback(with:) instead." ) public func handleURLCallback(with url: URL) -> Bool { return StripeAPI.handleURLCallback(with: url) }
mit
4afb89e9f15ab564577f62be5c250f99
25.923077
110
0.701758
4.719917
false
false
false
false
kevinlindkvist/lind
lind/STLCTypes.swift
1
2352
// // LCSimpleTypes.swift // lind // // Created by Kevin Lindkvist on 9/4/16. // Copyright © 2016 lindkvist. All rights reserved. // typealias TypeContext = [Int:STLCType] public indirect enum STLCType { case t_t(STLCType, STLCType) case bool case nat } extension STLCType: Equatable { } public func ==(lhs: STLCType, rhs: STLCType) -> Bool { switch (lhs, rhs) { case (.bool, .bool): return true case (.nat, .nat): return true case let (.t_t(t1,t2), .t_t(t11, t22)): return t1 == t11 && t2 == t22 default: return false } } extension STLCType: CustomStringConvertible { public var description: String { switch self { case .bool: return "bool" case .nat: return "int" case let .t_t(t1, t2): return "\(t1.description)->\(t2.description)" } } } public indirect enum STLCTerm { case tmTrue case tmFalse case ifElse(STLCTerm, STLCTerm, STLCTerm) case zero case succ(STLCTerm) case pred(STLCTerm) case isZero(STLCTerm) case va(String, Int) case abs(String, STLCType, STLCTerm) case app(STLCTerm, STLCTerm) } extension STLCTerm: CustomStringConvertible { public var description: String { switch self { case .tmTrue: return "true" case .tmFalse: return "false" case let .ifElse(t1, t2, t3): return "if (\(t1))\n\tthen (\(t2))\n\telse (\(t3))" case .zero: return "0" case let .succ(t): return "succ(\(t))" case let .pred(t): return "pred(\(t))" case let .isZero(t): return "isZero(\(t))" case let .va(x, idx): return "\(x):\(idx)" case let .abs(x, type, t): return "\\\(x):\(type).\(t)" case let .app(lhs, rhs): return "(\(lhs) \(rhs))" } } } extension STLCTerm: Equatable { } public func ==(lhs: STLCTerm, rhs: STLCTerm) -> Bool { switch (lhs, rhs) { case (.tmTrue, .tmTrue): return true case (.tmFalse, .tmFalse): return true case (.zero, .zero): return true case let (.succ(t1), .succ(t2)): return t1 == t2 case let (.pred(t1), .pred(t2)): return t1 == t2 case let (.isZero(t1), .isZero(t2)): return t1 == t2 case let (.ifElse(t1,t2,t3), .ifElse(t11, t22, t33)): return t1 == t11 && t2 == t22 && t3 == t33 case let (.va(ln, li), .va(rn, ri)): return ln == rn && ri == li case let (.abs(lv), .abs(rv)): return lv == rv case let (.app(lv), .app(rv)): return lv == rv default: return false } }
apache-2.0
cee6146e1cd01e1f59152a62710503b7
26.337209
98
0.615483
2.909653
false
false
false
false
wanqingrongruo/RNPlanning3.23
baseDataType.playground/Contents.swift
1
5772
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // 十进制 let fifteenInDecimal = 15 // 十六进制 let fifteenInHex = 0xF // 八进制 let fifteenInOctal = 0o17 // 二进制 let fifteenInBinary = 0b1111 let million = 1_000_000 var PI = 314e-2 // "一个在屏幕上显示的字符可能由多个code unit组合而成。" // 0xD800和0xDC00,就叫做surrogate pair // unicode scalar就是除了surrogate pair之外的code unit /* // 编码单位 code unit 可变是指: // UTF-8 中的编码单位是 8位二进制数, 表示一个字符可以通过几个编码单位进行组合 // UTF-16 中的编码单位是 16位二进制数, 表示一个字符可以通过几个编码单位进行组合 // UTF-32 中的编码单位是 32位二进制数 */ // Unicode grapheme clusters 字素簇 // é , 它的unicode scalar是U00e9 // 英文字母e,它的unicode scalar是U0065,name是LATIN SMALL LETTER E // 声调字符',它的unicode scalar是U0301,name是COMBINING ACUTE ACCENT let cafe = "Caf\u{00e9}" var cafee = "Caf\u{0065}\u{0301}" // Canonically equivalent 标准相等 cafe.characters.count cafee.characters.count // é的UTF-8编码是C3 A9 cafe.utf8.count // 声调字符'的UTF-8编码是CC 81 cafee.utf8.count cafe.utf16.count cafee.utf16.count cafe == cafee // NSString let nsCafe = NSString(characters: [0x43, 0x61, 0x66, 0xe9], length: 4) let nsCafee = NSString(characters: [0x43, 0x61, 0x66, 0x65, 0x0301], length: 5) nsCafe.length nsCafee.length nsCafe == nsCafee // ==对NSString来说,并没有执行canonically equivalent的语义 let result = nsCafe.compare(nsCafee as String) result == ComparisonResult.orderedSame // 为什么String不是一个Collection类型? extension String: Collection { } // 面对unicode复杂的组合规则,我们很难保证所有的集合算法都是安全并且语义正确的。 cafee.dropFirst(4) // cafee.dropLast() // cash // 使用不能的 View 去告诉 String 类型如何去理解字符串中的内容. 这些 View 是 String 的不同属性 // 划分方式 // 1. unicodeScalar: 按照字符中每个字符的 Unicode scalar 来形成集合 // 2. utf8: 按照字符串中每个字符的 UTF-8 编码来形成集合 // 3. utf16: 按照字符串中每个字符的 UTF-16 编码来形成集合 // Swift 把 UTF-32 码元叫做「Unicode 标量(unicode scalars)」 print("******** 划分 *********") cafee.unicodeScalars.forEach { (c) in print(c) } cafee.utf8.forEach { (c) in print(c) } cafee.utf16.forEach { (c) in print(c) } cafee.unicodeScalars.dropLast(1) cafee.utf16.dropLast(1) cafee.utf8.dropLast(1) // String.CharacterView cafee.characters.count cafee.characters.startIndex cafee.characters.endIndex // 最后一个字符的下一个位置 // endIndex == 5 是因为 Index是面向集合的,它不处理Unicode语义,但是characters这个属性却是带有unicode语义的,所以就会这样。。。 cafe.characters.count cafe.characters.endIndex cafee.utf8.count cafee.utf8.endIndex "hello".characters.count "hello".characters.startIndex "hello".endIndex //public struct String { // /// The index type for subscripting a string. // public typealias Index = String.CharacterView.Index //} // characters属性中的索引,是可以直接用来索引字符串特定位置的。但是由于你无法确定两个字符之间到底相隔了多少字符,因此,你并不能像访问一个Array一样去使用characters: // cafee.characters[2] // wrong!!!! // `String.CharacterView只遵从了BidirectionalCollection protocol,因此,它只能顺序向前,或者向后移动,而不能随机指定位置移动。如果我们要获得特定位置的字符,只能使用index(_:offsetBy:)这个方法。例如: let index = cafee.index(cafee.startIndex, offsetBy: 3) cafee[index] let index0 = cafee.index(cafee.characters.endIndex, offsetBy: -1) cafee[index0] // limitedBy - 限制越界 let index01 = cafee.index(cafee.characters.startIndex, offsetBy: 100, limitedBy: cafee.endIndex) // 越界返回 nil // 基于unicode的字符串常用操作 // 前缀 let pre = cafee.characters.prefix(3) String(pre) // 遍历 for (index, value) in cafee.characters.enumerated() { print("\(index): \(value)") } // 插入内容 if let index = cafee.characters.index(of: "a") { index cafee.insert(contentsOf: "9", at: index) } // 基于 Range 的查找和替换 var mixStr = "Swift很有趣" if let s = mixStr.characters.index(of: "很") { mixStr.replaceSubrange(s ..< mixStr.endIndex, with: " is interesting!") } // 字符串切片 let view = mixStr.characters.suffix(12).dropLast() String(view) let strView = mixStr.characters.split(separator: " ") strView.map(String.init) var i = 0 let singleCharViews = mixStr.characters.split { _ in if i > 0 { i = 0 return true } else { i += 1 return false } } singleCharViews.map(String.init) // 使用 Tuple 打包数据 let success = (200, "OK") let fileNotFound = (404, "File not found") let me = (name: "roni", no: 28, email: "zwxwqrr@gmail") me.name me.1 // Tuple Decomposition var (sCode, smsg) = success sCode smsg sCode = 500 success let (_, error) = fileNotFound error // Tuple type -- type annotation(注释,注解) var redirect: (Int, String) = (302, "temporary redirect") // Tuple comparison let tuple01 = (1, 2) let tuple02 = (1, 2, 3) // 个数类型相同,逐个元素比较 // tuple01 < tuple02 // compare error let largeTuple1 = (1, 2, 3, 4, 5, 6, 7) let largeTuple2 = (1, 2, 3, 4, 5, 6, 7) // 最多包含6个元素进行比较 // largeTuple1 == largeTuple2 // Error !!! // 使用 Markdown 编写代码注释
mit
7728c87b71480208a10c450ac12c2ce9
18.581197
136
0.710607
2.660859
false
false
false
false
scotlandyard/expocity
expocity/View/Chat/Main/VChat.swift
1
7341
import UIKit class VChat:UIView { weak var controller:CChat! weak var input:VChatInput! weak var display:VChatDisplay! weak var conversation:VChatConversation! weak var emojiKeyboard:VChatEmojiKeyboard! weak var layoutInputBottom:NSLayoutConstraint! weak var spinner:VMainLoader? private let kAnimationDuration:TimeInterval = 0.4 convenience init(controller:CChat) { self.init() clipsToBounds = true backgroundColor = UIColor.white translatesAutoresizingMaskIntoConstraints = false self.controller = controller let spinner:VMainLoader = VMainLoader() self.spinner = spinner let barHeight:CGFloat = controller.parentController.viewParent.kBarHeight addSubview(spinner) let views:[String:UIView] = [ "spinner":spinner] let metrics:[String:CGFloat] = [ "barHeight":barHeight] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[spinner]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-(barHeight)-[spinner]-0-|", options:[], metrics:metrics, views:views)) } deinit { NotificationCenter.default.removeObserver(self) } //MARK: notified func notifiedKeyboardChanged(sender notification:Notification) { let userInfo:[AnyHashable:Any] = notification.userInfo! let keyboardFrameValue:NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue let keyRect:CGRect = keyboardFrameValue.cgRectValue let yOrigin = keyRect.origin.y let screenHeight:CGFloat = UIScreen.main.bounds.size.height let keyboardHeight:CGFloat if yOrigin < screenHeight { keyboardHeight = screenHeight - yOrigin } else { keyboardHeight = 0 } let newInputBottom:CGFloat = -keyboardHeight animateInput(bottom:newInputBottom) } //MARK: private private func animateInput(bottom:CGFloat) { let currentOffset:CGPoint = conversation.collectionView.contentOffset let newCollectionOffsetY:CGFloat = currentOffset.y - bottom layoutInputBottom.constant = bottom conversation.collectionView.contentOffset = CGPoint(x:0, y:newCollectionOffsetY) UIView.animate(withDuration:kAnimationDuration) { [weak self] in self?.layoutIfNeeded() } } //MARK: public func chatLoaded() { spinner?.removeFromSuperview() let input:VChatInput = VChatInput(controller:controller) self.input = input let conversation:VChatConversation = VChatConversation(controller:controller) self.conversation = conversation let display:VChatDisplay = VChatDisplay(controller:controller) self.display = display let emojiKeyboard:VChatEmojiKeyboard = VChatEmojiKeyboard(controller:controller) self.emojiKeyboard = emojiKeyboard addSubview(conversation) addSubview(display) addSubview(input) addSubview(emojiKeyboard) let views:[String:UIView] = [ "input":input, "conversation":conversation, "display":display, "emojiKeyboard":emojiKeyboard] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[input]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[display]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[conversation]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[emojiKeyboard]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[conversation]-0-[display]-0-[input]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[emojiKeyboard]-0-|", options:[], metrics:metrics, views:views)) layoutInputBottom = NSLayoutConstraint( item:input, attribute:NSLayoutAttribute.bottom, relatedBy:NSLayoutRelation.equal, toItem:self, attribute:NSLayoutAttribute.bottom, multiplier:1, constant:0) input.layoutHeight = NSLayoutConstraint( item:input, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1, constant:input.kMinHeight) display.layoutHeight = NSLayoutConstraint( item:display, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1, constant:display.kMinHeight) emojiKeyboard.layoutHeight = NSLayoutConstraint( item:emojiKeyboard, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1, constant:0) addConstraint(layoutInputBottom) addConstraint(input.layoutHeight) addConstraint(display.layoutHeight) addConstraint(emojiKeyboard.layoutHeight) listenToKeyboard() } func presentImagePicker() { let chatPicker:CChatDisplayPicker = CChatDisplayPicker(controller:controller) controller.present(chatPicker, animated:true, completion:nil) } func listenToKeyboard() { NotificationCenter.default.addObserver( self, selector:#selector(notifiedKeyboardChanged(sender:)), name:NSNotification.Name.UIKeyboardWillChangeFrame, object:nil) } func displayEmojiKeyboard() { UIApplication.shared.keyWindow!.endEditing(true) emojiKeyboard.animateKeyboard(show:true) let emojiKeyboardHeight:CGFloat = emojiKeyboard.layoutHeight.constant let inputHeight:CGFloat = input.layoutHeight.constant let inputBottom:CGFloat = -(emojiKeyboardHeight - inputHeight) animateInput(bottom:inputBottom) } func hideEmojiKeyboard() { emojiKeyboard.animateKeyboard(show:false) animateInput(bottom:0) } }
mit
98da4a7fb50912bcebb71bd53ff40a75
31.197368
92
0.608773
5.664352
false
false
false
false
ChristianKienle/highway
Sources/FSKit/Model/File.swift
1
1051
import Foundation // All throwing methods HAVE to throw FileSystemError if they throw anything at all. public class File { // MARK: - Init init(url: Absolute, fileSystem: FileSystem) { self.url = url self.fileSystem = fileSystem } // MARK: - Properties let url: Absolute let fileSystem: FileSystem public var isExistingFile: Bool { guard let type = try? fileSystem.itemMetadata(at: url).type else { return false } return type == .file } // MARK: - Working with the File public func data() throws -> Data { return try fileSystem.data(at: url) } public func setData(_ data: Data) throws { try fileSystem.writeData(data, to: url) } public func string() throws -> String { let data = try self.data() guard let result = String(data: data, encoding: .utf8) else { throw FSError.other("Cannot convert contents of file \(url.description) to string.") } return result } }
mit
8bcd69e302b319f3db5877e1acae3b2f
28.194444
96
0.602284
4.434599
false
false
false
false
collegboi/DIT-Timetable-iOS
DIT-Timetable-V2/Applications/Timetable/TimetableViewController.swift
1
4399
// // TimetableViewController.swift // DIT-Timetable-V2 // // Created by Timothy Barnard on 16/09/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import RealmSwift import UIKit class TimetableViewController: UIPageViewController { // Some hard-coded data for our walkthrough screens var allTimetables = [AllTimetables]() @IBOutlet weak var toggleNotifications: UIBarButtonItem! var notificationsSet : Bool = true // make the status bar white (light content) override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() let defaults = UserDefaults.standard if defaults.integer(forKey: "notification") == 1 { self.turnOnOffNotification(OnOff: true) } else { self.turnOnOffNotification(OnOff: false) } self.getTimetablesDB() // this class is the page view controller's data source itself self.dataSource = self } @IBAction func addClassButton(_ sender: Any) { let notificationName = Notification.Name("NotificationIdentifier") NotificationCenter.default.post(name: notificationName, object: nil) } @IBAction func toggleNotifications(_ sender: AnyObject) { let defaults = UserDefaults.standard let notificationManager = NotificationManager() notificationManager.registerForNotifications() if notificationsSet { defaults.set(0, forKey: "notification") notificationManager.cancelAllNotifications() self.turnOnOffNotification(OnOff: false) } else { defaults.set(1, forKey: "notification") notificationManager.createAllNotifications(myTimetable: self.allTimetables ) self.turnOnOffNotification(OnOff: true) } } func turnOnOffNotification( OnOff : Bool) { if OnOff { self.notificationsSet = true self.toggleNotifications.image = UIImage(named : "notificationOn") } else { self.notificationsSet = false self.toggleNotifications.image = UIImage(named: "notificationOff") } } func getTimetablesDB() { let database = Database() self.allTimetables = database.getAllTimetables() let today = Date() let day = today.weekday() let indexVal = (day+5) % 7 // create the first walkthrough vc if let startWalkthroughVC = self.viewControllerAtIndex(indexVal) { self.setViewControllers([startWalkthroughVC], direction: .forward, animated: true, completion: nil) } } // MARK: - Navigate func nextPageWithIndex(_ index: Int) { if let nextWalkthroughVC = self.viewControllerAtIndex(index+1) { setViewControllers([nextWalkthroughVC], direction: .forward, animated: true, completion: nil) } } func viewControllerAtIndex(_ index: Int) -> DayTableViewController? { if index == NSNotFound || index < 0 || index >= self.allTimetables.count { return nil } // create a new walkthrough view controller and assing appropriate date if let dayTableViewController = storyboard?.instantiateViewController(withIdentifier: "DayTableViewController") as? DayTableViewController { dayTableViewController.index = index dayTableViewController.dayTimetable = self.allTimetables return dayTableViewController } return nil } } extension TimetableViewController : UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { var index = (viewController as! DayTableViewController).index index += 1 return self.viewControllerAtIndex(index) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { var index = (viewController as! DayTableViewController).index index -= 1 return self.viewControllerAtIndex(index) } }
mit
64665c07a1cf44aa7beb4f3e75a290ca
33.093023
149
0.648931
5.567089
false
false
false
false
zbw209/-
StudyNotes/Pods/Alamofire/Source/HTTPMethod.swift
18
2345
// // HTTPMethod.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so /// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. /// /// See https://tools.ietf.org/html/rfc7231#section-4.3 public struct HTTPMethod: RawRepresentable, Equatable, Hashable { /// `CONNECT` method. public static let connect = HTTPMethod(rawValue: "CONNECT") /// `DELETE` method. public static let delete = HTTPMethod(rawValue: "DELETE") /// `GET` method. public static let get = HTTPMethod(rawValue: "GET") /// `HEAD` method. public static let head = HTTPMethod(rawValue: "HEAD") /// `OPTIONS` method. public static let options = HTTPMethod(rawValue: "OPTIONS") /// `PATCH` method. public static let patch = HTTPMethod(rawValue: "PATCH") /// `POST` method. public static let post = HTTPMethod(rawValue: "POST") /// `PUT` method. public static let put = HTTPMethod(rawValue: "PUT") /// `TRACE` method. public static let trace = HTTPMethod(rawValue: "TRACE") public let rawValue: String public init(rawValue: String) { self.rawValue = rawValue } }
mit
f1fb08ba62d1373804408452f26501da
42.425926
98
0.707036
4.240506
false
false
false
false
debugsquad/nubecero
nubecero/Controller/Photos/CPhotosAlbum.swift
1
9867
import UIKit class CPhotosAlbum:CController { private weak var viewAlbum:VPhotosAlbum! let model:MPhotosItem init(model:MPhotosItem) { self.model = model super.init() } required init?(coder:NSCoder) { fatalError() } override func viewWillAppear(_ animated:Bool) { super.viewWillAppear(animated) parentController.statusBarDefault() viewAlbum.collectionView.scrollsToTop = true } override func viewWillDisappear(_ animated:Bool) { super.viewWillDisappear(animated) parentController.statusBarLight() } override func loadView() { let viewAlbum:VPhotosAlbum = VPhotosAlbum(controller:self) self.viewAlbum = viewAlbum view = viewAlbum } //MARK: private private func confirmDeleteAll() { model.removeAll() DispatchQueue.main.async { [weak self] in self?.viewAlbum.hideLoading() } } private func confirmDeleteAlbum() { guard let userId:MSession.UserId = MSession.sharedInstance.user.userId, let albumUser:MPhotosItemUser = model as? MPhotosItemUser else { return } albumUser.moveAll() let parentUser:String = FDatabase.Parent.user.rawValue let propertyAlbums:String = FDatabaseModelUser.Property.albums.rawValue let albumId:MPhotos.AlbumId = albumUser.albumId let pathAlbum:String = "\(parentUser)/\(userId)/\(propertyAlbums)/\(albumId)" FMain.sharedInstance.database.removeChild(path:pathAlbum) MPhotos.sharedInstance.loadPhotos() DispatchQueue.main.async { [weak self] in self?.parentController.pop(completion:nil) } } private func confirmRenameAlbum(newName:String) { guard let userId:MSession.UserId = MSession.sharedInstance.user.userId, let albumUser:MPhotosItemUser = model as? MPhotosItemUser else { return } let parentUser:String = FDatabase.Parent.user.rawValue let propertyAlbums:String = FDatabaseModelUser.Property.albums.rawValue let albumId:MPhotos.AlbumId = albumUser.albumId let propertyAlbumName:String = FDatabaseModelAlbum.Property.name.rawValue let pathAlbum:String = "\(parentUser)/\(userId)/\(propertyAlbums)/\(albumId)/\(propertyAlbumName)" FMain.sharedInstance.database.updateChild( path:pathAlbum, json:newName) albumUser.rename(name:newName) DispatchQueue.main.async { [weak self] in self?.viewAlbum.hideLoading() } } private func renameAlbum() { let alert:UIAlertController = UIAlertController( title: NSLocalizedString("CPhotosAlbum_renameTitle", comment:""), message:nil, preferredStyle:UIAlertControllerStyle.alert) let actionCancel:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_renameCancel", comment:""), style: UIAlertActionStyle.cancel) let actionSave:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_renameSave", comment:""), style: UIAlertActionStyle.default) { [weak self] (action:UIAlertAction) in if let newName:String = alert.textFields?.first?.text { if !newName.isEmpty { self?.viewAlbum.showLoading() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.confirmRenameAlbum(newName:newName) } } else { let error:String = NSLocalizedString("CPhotosAlbum_renameError", comment:"") VAlert.message(message:error) } } } alert.addAction(actionSave) alert.addAction(actionCancel) alert.addTextField { [weak self] (textfield:UITextField) in textfield.text = self?.model.name textfield.returnKeyType = UIReturnKeyType.done textfield.placeholder = NSLocalizedString("CPhotosAlbum_renamePlaceholder", comment:"") textfield.keyboardType = UIKeyboardType.alphabet } present(alert, animated:true, completion:nil) } private func deleteAlbum() { let alert:UIAlertController = UIAlertController( title: NSLocalizedString("CPhotosAlbum_deleteAlbumTitle", comment:""), message: NSLocalizedString("CPhotosAlbum_deleteAlbumMessage", comment:""), preferredStyle:UIAlertControllerStyle.actionSheet) let actionCancel:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_deleteAlbumCancel", comment:""), style: UIAlertActionStyle.cancel) let actionDelete:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_deleteAlbumDelete", comment:""), style: UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.viewAlbum.showLoading() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.confirmDeleteAlbum() } } alert.addAction(actionDelete) alert.addAction(actionCancel) present(alert, animated:true, completion:nil) } private func deleteAllPhotos() { let alert:UIAlertController = UIAlertController( title: NSLocalizedString("CPhotosAlbum_deleteAllTitle", comment:""), message: NSLocalizedString("CPhotosAlbum_deleteAllMessage", comment:""), preferredStyle:UIAlertControllerStyle.actionSheet) let actionCancel:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_deleteAllCancel", comment:""), style: UIAlertActionStyle.cancel) let actionDelete:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_deleteAllDelete", comment:""), style: UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.viewAlbum.showLoading() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.confirmDeleteAll() } } alert.addAction(actionDelete) alert.addAction(actionCancel) present(alert, animated:true, completion:nil) } //MARK: public func back() { parentController.pop(completion:nil) } func options() { let alert:UIAlertController = UIAlertController( title: nil, message: nil, preferredStyle:UIAlertControllerStyle.actionSheet) let actionCancel:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_alertCancel", comment:""), style: UIAlertActionStyle.cancel) let actionRename:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_alertRename", comment:""), style: UIAlertActionStyle.default) { [weak self] (action:UIAlertAction) in self?.renameAlbum() } let actionDeleteAlbum:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_alertDeleteAlbum", comment:""), style: UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.deleteAlbum() } let actionDeleteAll:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbum_alertDeleteAll", comment:""), style: UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.deleteAllPhotos() } if let _:MPhotosItemUser = model as? MPhotosItemUser { alert.addAction(actionRename) alert.addAction(actionDeleteAlbum) } alert.addAction(actionDeleteAll) alert.addAction(actionCancel) present(alert, animated:true, completion:nil) } func selectPhoto(item:Int, inRect:CGRect) { viewAlbum.collectionView.scrollsToTop = false let controller:CPhotosAlbumPhoto = CPhotosAlbumPhoto( albumController:self, selected:item, inRect:inRect) parentController.over( controller:controller, pop:false, animate:false) } func removeFromList(photo:MPhotosItemPhoto) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.model.removePhoto(item:photo) } } }
mit
a5e1fb6a5fed5b14ec8cd769f29e1f32
29.36
106
0.563596
5.783705
false
false
false
false
brentdax/swift
test/SILOptimizer/closure_lifetime_fixup_objc.swift
1
5630
// RUN: %target-swift-frontend %s -emit-sil -o - | %FileCheck %s // REQUIRES: objc_interop import Foundation @objc public protocol DangerousEscaper { @objc func malicious(_ mayActuallyEscape: () -> ()) } // CHECK: sil @$s27closure_lifetime_fixup_objc19couldActuallyEscapeyyyyc_AA16DangerousEscaper_ptF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @guaranteed DangerousEscaper) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> (), [[SELF:%.*]] : $DangerousEscaper): // CHECK: [[OE:%.*]] = open_existential_ref [[SELF]] // Copy (1). // CHECK: strong_retain [[ARG]] : $@callee_guaranteed () -> () // Extend the lifetime to the end of this function (2). // CHECK: strong_retain [[ARG]] : $@callee_guaranteed () -> () // CHECK: [[OPT_CLOSURE:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[ARG]] : $@callee_guaranteed () -> () // CHECK: [[NE:%.*]] = convert_escape_to_noescape [[ARG]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[WITHOUT_ACTUALLY_ESCAPING_THUNK:%.*]] = function_ref @$sIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[WITHOUT_ACTUALLY_ESCAPING_THUNK]]([[NE]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // Sentinel without actually escaping closure (3). // CHECK: [[SENTINEL:%.*]] = mark_dependence [[C]] : $@callee_guaranteed () -> () on [[NE]] : $@noescape @callee_guaranteed () -> () // Copy of sentinel (4). // CHECK: strong_retain [[SENTINEL]] : $@callee_guaranteed () -> () // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> () // CHECK: [[CLOSURE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> () // CHECK: store [[SENTINEL]] to [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> () // CHECK: [[BLOCK_INVOKE:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> (), invoke [[BLOCK_INVOKE]] : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> () // Optional sentinel (4). // CHECK: [[OPT_SENTINEL:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[SENTINEL]] : $@callee_guaranteed () -> () // Copy of sentinel closure (5). // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) @noescape () -> () // Release of sentinel closure (3). // CHECK: destroy_addr [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> () // CHECK: dealloc_stack [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> () // Release of closure copy (1). // CHECK: strong_release %0 : $@callee_guaranteed () -> () // CHECK: [[METH:%.*]] = objc_method [[OE]] : $@opened("{{.*}}") DangerousEscaper, #DangerousEscaper.malicious!1.foreign : <Self where Self : DangerousEscaper> (Self) -> (() -> ()) -> (), $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> () // CHECK: apply [[METH]]<@opened("{{.*}}") DangerousEscaper>([[BLOCK_COPY]], [[OE]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> () // Release sentinel closure copy (5). // CHECK: strong_release [[BLOCK_COPY]] : $@convention(block) @noescape () -> () // CHECK: [[ESCAPED:%.*]] = is_escaping_closure [objc] [[OPT_SENTINEL]] : $Optional<@callee_guaranteed () -> ()> // CHECK: cond_fail [[ESCAPED]] : $Builtin.Int1 // Release of sentinel copy (4). // CHECK: release_value [[OPT_SENTINEL]] : $Optional<@callee_guaranteed () -> ()> // Extendend lifetime (2). // CHECK: release_value [[OPT_CLOSURE]] : $Optional<@callee_guaranteed () -> ()> // CHECK: return public func couldActuallyEscape(_ closure: @escaping () -> (), _ villian: DangerousEscaper) { villian.malicious(closure) } // We need to store nil on the back-edge. // CHECK sil {{.*}}dontCrash // CHECK: is_escaping_closure [objc] // CHECK: cond_fail // CHECK: destroy_addr %0 // CHECK: [[NONE:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.none!enumelt // CHECK: store [[NONE]] to %0 : $*Optional<@callee_guaranteed () -> ()> public func dontCrash() { for i in 0 ..< 2 { let queue = DispatchQueue(label: "Foo") queue.sync { } } } @_silgen_name("getDispatchQueue") func getDispatchQueue() -> DispatchQueue // We must not release the closure after calling super.deinit. // CHECK: sil hidden @$s27closure_lifetime_fixup_objc1CCfD : $@convention(method) (@owned C) -> () { // CHECK: bb0([[SELF:%.*]] : $C): // CHECK: [[F:%.*]] = function_ref @$s27closure_lifetime_fixup_objc1CCfdyyXEfU_ // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[F]](%0) // CHECK: [[OPT:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[PA]] // CHECK: [[DEINIT:%.*]] = objc_super_method [[SELF]] : $C, #NSObject.deinit!deallocator.1.foreign // CHECK: release_value [[OPT]] : $Optional<@callee_guaranteed () -> ()> // CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $C to $NSObject // user: %34 // CHECK-NEXT: apply [[DEINIT]]([[SUPER]]) : $@convention(objc_method) (NSObject) -> () // CHECK-NEXT: [[T:%.*]] = tuple () // CHECK-NEXT: return [[T]] : $() class C: NSObject { deinit { getDispatchQueue().sync(execute: { _ = self }) } }
apache-2.0
978ff3116abc3e9a7f66e2aeb42ff653
54.137255
307
0.604908
3.452425
false
false
false
false
davejlin/treehouse
swift/swift2/restaurant-finder/RestaurantFinder/LocationManager.swift
1
1581
// // LocationManager.swift // RestaurantFinder // // Created by Lin David, US-205 on 10/10/16. // Copyright © 2016 Treehouse. All rights reserved. // import Foundation import CoreLocation extension Coordinate { init(location: CLLocation) { latitude = location.coordinate.latitude longitude = location.coordinate.longitude } } final class LocationManager: NSObject, CLLocationManagerDelegate { let manager = CLLocationManager() var onLocationFix: (Coordinate -> Void)? override init() { super.init() manager.delegate = self manager.requestLocation() manager.desiredAccuracy = kCLLocationAccuracyBest } func getPermission() { if CLLocationManager.authorizationStatus() == .NotDetermined { manager.requestWhenInUseAuthorization() } } // MARK: CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedWhenInUse { manager.requestLocation() } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print(error.description) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first else { return } let coordinate = Coordinate(location: location) if let onLocationFix = onLocationFix { onLocationFix(coordinate) } } }
unlicense
c619bfd4cee34d18232d833ed78005f2
27.232143
114
0.668987
5.505226
false
false
false
false
weibo3721/ZeroTier-iOS
ZeroTier One/ZeroTier One/NotConnectedViewController.swift
1
3556
// // NotConnectedViewController.swift // ZeroTier One // // Created by Grant Limberg on 4/18/16. // Copyright © 2016 Zero Tier, Inc. All rights reserved. // import UIKit import NetworkExtension class NotConnectedViewController: UIViewController { @IBOutlet var networkIdLabel: UILabel! @IBOutlet var networkNameLabel: UILabel! @IBOutlet weak var routeViaZTSwitch: UISwitch! var _deviceId: String? = nil var manager: ZTVPN! override func viewDidLoad() { super.viewDidLoad() let defaults = UserDefaults.standard if var deviceId = defaults.string(forKey: "com.zerotier.one.deviceId") { while deviceId.characters.count < 10 { deviceId = "0\(deviceId)" } _deviceId = deviceId let idButton = UIBarButtonItem(title: deviceId, style: .plain, target: self, action: #selector(NotConnectedViewController.copyId(_:))) idButton.tintColor = UIColor.white self.setToolbarItems([idButton], animated: true) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //PiwikTracker.sharedInstance().sendView("Network Info: Not Connected"); let curNetworkId = manager.getNetworkID().uint64Value let networkIdTxt = String(curNetworkId, radix: 16) networkIdLabel.text = networkIdTxt networkNameLabel.text = manager.getNetworkName() if let mgr = manager as? ZTVPN_Device { let proto = mgr.mgr.protocolConfiguration as! NETunnelProviderProtocol if let allowDefault = proto.providerConfiguration?["allowDefault"] as? NSNumber { routeViaZTSwitch.isOn = allowDefault.boolValue } else { routeViaZTSwitch.isOn = false } } manager.addStatusObserver(self, selector: #selector(NotConnectedViewController.onConnectionStateChanged(_:))) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) manager.removeStatusOserver(self) } func copyId(_ sender: AnyObject) { if let id = _deviceId { //DDLogDebug("id \(id) copied!") let pb = UIPasteboard.general pb.string = id } } func onConnectionStateChanged(_ note: Notification) { if let connection = note.object as? NETunnelProviderSession { if connection.status == .connected { // let root = self.navigationController?.viewControllers[0] // // root?.navigationController?.popViewControllerAnimated(false) // root?.performSegueWithIdentifier("ShowNetworkInfo", sender: root) let newvc: NetworkInfoViewController = self.storyboard?.instantiateViewController(withIdentifier: "network-info") as! NetworkInfoViewController newvc.manager = self.manager var controllers = self.navigationController!.viewControllers controllers.removeLast() controllers.append(newvc) self.navigationController?.viewControllers = controllers } } } @IBAction func onRouteSwitchChanged(_ sender: AnyObject) { if let mgr = manager as? ZTVPN_Device { let proto = mgr.mgr.protocolConfiguration as! NETunnelProviderProtocol proto.providerConfiguration!["allowDefault"] = NSNumber(value: routeViaZTSwitch.isOn as Bool) } manager.save() } }
mit
af0bb3a6b5faec4602f648a0f47e2120
32.537736
159
0.640506
5.035411
false
false
false
false
linbin00303/Dotadog
DotaDog/DotaDog/Classes/LeftView/View/DDogMatchCell.swift
1
4060
// // DDogMatchCell.swift // DotaDog // // Created by 林彬 on 16/5/25. // Copyright © 2016年 linbin. All rights reserved. // import UIKit class DDogMatchCell: UITableViewCell { @IBOutlet weak var icon: UIImageView! @IBOutlet weak var item0: UIImageView! @IBOutlet weak var item1: UIImageView! @IBOutlet weak var item2: UIImageView! @IBOutlet weak var item3: UIImageView! @IBOutlet weak var item4: UIImageView! @IBOutlet weak var item5: UIImageView! @IBOutlet weak var dataView: UIView! @IBOutlet weak var playerName: UILabel! @IBOutlet weak var KDA: UILabel! @IBOutlet weak var heroName: UILabel! @IBOutlet weak var level: UILabel! @IBOutlet weak var deniesAndHits: UILabel! @IBOutlet weak var totalMoney: UILabel! @IBOutlet weak var expPerM: UILabel! @IBOutlet weak var tower_damage: UILabel! @IBOutlet weak var moneyPerM: UILabel! @IBOutlet weak var heroHeal: UILabel! @IBOutlet weak var hero_damage: UILabel! var name : String? { didSet{ if name == nil { return }else { // 获取玩家中文名字 self.playerName.text = name! } } } var hero : DDogMatchHeroModel? { didSet{ // nil值校验 guard let _ = hero else { return } // 显示物品图标 let heroItem = [hero!.item_0,hero!.item_1,hero!.item_2,hero!.item_3,hero!.item_4,hero!.item_5] let itemViews = [item0,item1,item2,item3,item4,item5] showItemIcon(heroItem, itemViews: itemViews) // 通过英雄ID获得英雄名称和头像 var sql = "select name_zh from hero where id = \(hero!.hero_id)" DDogFMDBTool.shareInstance.query_DataByColumn(sql, targetString: "name_zh") { [weak self](results) in self?.heroName.text = results! as? String } sql = "select name_en from hero where id = \(hero!.hero_id)" DDogFMDBTool.shareInstance.query_DataByColumn(sql, targetString: "name_en") { [weak self](results) in let url = NSURL(string: "http://cdn.dota2.com/apps/dota2/images/heroes/\(results! as! String)_hphover.png") self?.icon.sd_setImageWithURL(url) } KDA.text = String(format: "\(hero!.kills)/\(hero!.deaths)/\(hero!.assists)") level.text = String(format: "\(hero!.level)级") deniesAndHits.text = String(format: "正补:\(hero!.last_hits) 反补:\(hero!.denies)") totalMoney.text = String(format: "\((hero!.gold.intValue) + (hero!.gold_spent.intValue))") expPerM.text = hero!.xp_per_min.stringValue tower_damage.text = hero!.tower_damage.stringValue moneyPerM .text = hero!.gold_per_min.stringValue heroHeal.text = hero!.hero_healing.stringValue hero_damage.text = hero!.hero_damage.stringValue } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } func showItemIcon(heroItems:[NSNumber] , itemViews:[UIImageView!]) { let count = itemViews.count var sql = "" for i in 0..<count { let id = heroItems[i] sql = "select name from items where id = \(id)" DDogFMDBTool.shareInstance.query_DataByColumn(sql, targetString: "name") { (results) in if results != nil { let url = NSURL(string: "http://cdn.dota2.com/apps/dota2/images/items/\(results! as! String)_lg.png") itemViews[i].sd_setImageWithURL(url) }else{ itemViews[i].image = UIImage(named: "nullIcon") } } } } }
mit
311304954b5123ea5e708b9e48554fdb
29.638462
123
0.549084
4.192632
false
false
false
false
QueryKit/RxQueryKit
RxQueryKitTests/RxQueryKitTests.swift
1
5405
import XCTest import CoreData import QueryKit import RxQueryKit class RxQueryKitTests: XCTestCase { var context: NSManagedObjectContext! override func setUp() { let model = NSManagedObjectModel() model.entities = [Person.createEntityDescription(), Comment.createEntityDescription()] let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) try! persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = persistentStoreCoordinator } // Make sure we've configure our store and model correctly func testCoreData() { let person = Person.create(context, name: "kyle") XCTAssertEqual(person.name, "kyle") } func testCount() { var counts: [Int] = [] let queryset = Person.queryset(context) let disposable = try! queryset.count().subscribe(onNext: { counts.append($0) }) // Initial value XCTAssertEqual(counts, [0]) // Created let p1 = Person.create(context, name: "kyle1") _ = Person.create(context, name: "kyle2") let p3 = Person.create(context, name: "kyle3") try! context.save() XCTAssertEqual(counts, [0, 3]) // Deleted context.delete(p1) context.delete(p3) try! context.save() XCTAssertEqual(counts, [0, 3, 1]) // Doesn't update when nothing changes _ = Comment.create(context, text: "Hello World") try! context.save() XCTAssertEqual(counts, [0, 3, 1]) disposable.dispose() } func testCountWithPredicate() { var counts: [Int] = [] let disposable = try! Person.queryset(context) .filter(\.name != "kyle") .count() .subscribe(onNext: { counts.append($0) }) // Initial value XCTAssertEqual(counts, [0]) // Created let p1 = Person.create(context, name: "kyle1") _ = Person.create(context, name: "kyle2") let p3 = Person.create(context, name: "kyle3") let p4 = Person.create(context, name: "kyle") try! context.save() XCTAssertEqual(counts, [0, 3]) // Deleted context.delete(p1) context.delete(p3) try! context.save() XCTAssertEqual(counts, [0, 3, 1]) // Doesn't update when nothing changes _ = Comment.create(context, text: "Hello World") try! context.save() XCTAssertEqual(counts, [0, 3, 1]) // Modify comes into count p4.name = "kyle4" try! context.save() XCTAssertEqual(counts, [0, 3, 1, 2]) disposable.dispose() } func testObjects() { var objects: [[Person]] = [] let disposable = try! Person.queryset(context) .orderBy { $0.name.ascending() } .objects() .subscribe(onNext: { objects.append($0) }) // Initial value XCTAssertEqual(objects.count, 1) XCTAssertTrue(objects[0].isEmpty) // Created let p1 = Person.create(context, name: "kyle1") let p2 = Person.create(context, name: "kyle2") let p3 = Person.create(context, name: "kyle3") try! context.save() XCTAssertEqual(objects.count, 2) XCTAssertEqual(objects[1], [p1, p2, p3]) // Deleted context.delete(p1) context.delete(p3) try! context.save() XCTAssertEqual(objects.count, 3) XCTAssertEqual(objects[2], [p2]) // Modified Object context.delete(p1) context.delete(p3) p2.name = "kyle updated" try! context.save() XCTAssertEqual(objects.count, 4) XCTAssertEqual(objects[3], [p2]) // Doesn't update when nothing changes _ = Comment.create(context, text: "Hello World") try! context.save() XCTAssertEqual(objects.count, 4) disposable.dispose() } } @objc(Person) class Person : NSManagedObject { class var name:Attribute<String> { return Attribute("name") } class func createEntityDescription() -> NSEntityDescription { let name = NSAttributeDescription() name.name = "name" name.attributeType = .stringAttributeType name.isOptional = false let entity = NSEntityDescription() entity.name = "Person" entity.managedObjectClassName = "Person" entity.properties = [name] return entity } class func queryset(_ context: NSManagedObjectContext) -> QuerySet<Person> { return QuerySet(context, "Person") } class func create(_ context: NSManagedObjectContext, name: String) -> Person { let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)! let person = Person(entity: entity, insertInto: context) person.name = name return person } @NSManaged var name: String } @objc(Comment) class Comment : NSManagedObject { class func createEntityDescription() -> NSEntityDescription { let text = NSAttributeDescription() text.name = "text" text.attributeType = .stringAttributeType text.isOptional = false let entity = NSEntityDescription() entity.name = "Comment" entity.managedObjectClassName = "Comment" entity.properties = [text] return entity } class func create(_ context: NSManagedObjectContext, text: String) -> Comment { let entity = NSEntityDescription.entity(forEntityName: "Comment", in: context)! let comment = Comment(entity: entity, insertInto: context) comment.text = text return comment } @NSManaged var text: String }
bsd-2-clause
070501d683963cd5961a0faeaccb69d2
26.576531
130
0.6679
4.116527
false
false
false
false
fernandomarins/food-drivr-pt
hackathon-for-hunger/Modules/Donor/AddDonation/Views/DonorDonationViewController.swift
1
3693
// // DonorDonationViewController.swift // hackathon-for-hunger // // Created by ivan lares on 4/28/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import UIKit class DonorDonationViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var tableView: UITableView! private let cellIdentifier = "DonationCell" var foodToDonate: [String]! private let donationPresenter = DonationPresenter(donationService: DonationService()) @IBOutlet weak var addDonationButton: UIButton! var activityIndicator : ActivityIndicatorView! override func viewDidLoad() { addDonationButton.enabled = false foodToDonate = [String]() donationPresenter.attachView(self) tableView.dataSource = self tableView.delegate = self inputTextField.delegate = self activityIndicator = ActivityIndicatorView(inview: self.view, messsage: "Saving") } //MARK: Actions @IBAction func didTapDonate(sender: AnyObject) { self.startLoading() donationPresenter.createDonation(self.foodToDonate) } func checkButtonStatus() { if foodToDonate.count > 0 { addDonationButton.enabled = true } else { addDonationButton.enabled = false } } } extension DonorDonationViewController: UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return foodToDonate.count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! DonationTableViewCell cell.delegate = self cell.label.text = foodToDonate[indexPath.row] return cell } } extension DonorDonationViewController: UITableViewDelegate{ } extension DonorDonationViewController: DonationCellDelegate{ func didTapCancel(cell: DonationTableViewCell){ if let selectedIndex = tableView.indexPathForCell(cell){ foodToDonate.removeAtIndex(selectedIndex.row) tableView.deleteRowsAtIndexPaths([selectedIndex], withRowAnimation: .Fade) checkButtonStatus() } } } extension DonorDonationViewController: UITextFieldDelegate{ func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidEndEditing(textField: UITextField) { guard let food = textField.text else { return } if !food.isBlank{ foodToDonate.append(food) tableView.reloadData() //TODO: update table view correctly textField.text = nil checkButtonStatus() } } } extension DonorDonationViewController: DonationView { func startLoading() { self.activityIndicator.startAnimating() } func finishLoading() { self.activityIndicator.stopAnimating() } func donations(sender: DonationPresenter, didSucceed donation: Donation) { self.finishLoading() self.foodToDonate = [] self.tableView.reloadData() SweetAlert().showAlert("Donation Saved!", subTitle: nil, style: AlertStyle.Success) } func donations(sender: DonationPresenter, didFail error: NSError) { self.finishLoading() SweetAlert().showAlert("Could not save donation!", subTitle: error.localizedDescription, style: AlertStyle.Error) } }
mit
ff6c99ae3764d8db8d2a3fba68d600ef
30.288136
121
0.681473
5.149233
false
false
false
false
myTargetSDK/mytarget-ios
myTargetDemoSwift/myTargetDemo/Views/VideoPlayerView.swift
1
7158
// // VideoPlayerView.swift // myTargetDemo // // Created by Andrey Seredkin on 01/08/2019. // Copyright © 2019 Mail.Ru Group. All rights reserved. // import UIKit import AVFoundation protocol VideoPlayerViewDelegate: AnyObject { func onVideoStarted(url: URL) func onVideoComplete() func onVideoFinished(error: String) } final class VideoPlayerView: UIView { weak var delegate: VideoPlayerViewDelegate? private var position: TimeInterval = 0.0 private var isPaused = false private var _currentTime: TimeInterval = 0.0 var currentTime: TimeInterval { get { guard let player = player else { return _currentTime } return CMTimeGetSeconds(player.currentTime()) } set { _currentTime = newValue guard let player = player else { return } player.seek(to: CMTimeMakeWithSeconds(_currentTime, preferredTimescale: 1)) } } private var _volume: Float = 1.0 var volume: Float { get { guard let player = player else { return _volume } return player.volume } set { _volume = newValue guard let player = player else { return } player.volume = _volume } } private var url: URL? private var asset: AVURLAsset? private var playerItem: AVPlayerItem? private var player: AVPlayer? { get { guard let layer = layer as? AVPlayerLayer else { return nil } return layer.player } set { guard let layer = layer as? AVPlayerLayer else { return } layer.player = newValue } } private static var playerItemContext = 0 private let requiredAssetKeys = ["playable"] private var playerItemDuration: TimeInterval { get { guard let playerItem = playerItem, playerItem.status == .readyToPlay, CMTIME_IS_VALID(playerItem.duration) else { return 0.0 } let duration = CMTimeGetSeconds(playerItem.duration) return duration.isFinite ? duration : 0.0 } } deinit { stop() } override class var layerClass: AnyClass { return AVPlayerLayer.self } // MARK: - public func start(with url: URL, position: TimeInterval) { self.position = position if let player = player, isPaused, let _url = self.url, _url.absoluteString == url.absoluteString { player.play() delegateOnVideoStarted(url: url) return } self.url = url isPaused = false asset = AVURLAsset(url: url) guard let asset = asset else { return } asset.loadValuesAsynchronously(forKeys: requiredAssetKeys) { DispatchQueue.main.async { self.prepareToPlay() } } } func pause() { guard let player = player else { return } player.pause() isPaused = true } func resume() { guard let player = player else { return } player.play() isPaused = false } func stop() { player?.pause() deletePlayerItem() deletePlayer() } func finish() { stop() delegateOnVideoComplete() } // MARK: - private private func prepareToPlay() { guard let asset = asset else { return } requiredAssetKeys.forEach { (key: String) in var error: NSError? let keyStatus = asset.statusOfValue(forKey: key, error: &error) if keyStatus == .failed { stop() delegateOnVideoFinished(error: "Item cannot be played, status failed") } } if !asset.isPlayable { stop() delegateOnVideoFinished(error: "Item cannot be played") return } deletePlayerItem() createPlayerItem() deletePlayer() createPlayer() guard let player = player else { return } player.seek(to: CMTimeMakeWithSeconds(position, preferredTimescale: 1)) player.play() } private func createPlayerItem() { guard let asset = asset else { return } playerItem = AVPlayerItem(asset: asset) guard let playerItem = playerItem else { return } playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.initial, .new], context: &VideoPlayerView.playerItemContext) NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: .AVPlayerItemDidPlayToEndTime, object: playerItem) } private func deletePlayerItem() { guard let playerItem = playerItem else { return } playerItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status)) NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playerItem) self.playerItem = nil } private func createPlayer() { guard let playerItem = playerItem else { return } player = AVPlayer(playerItem: playerItem) guard let player = player else { return } player.volume = volume } private func deletePlayer() { guard let player = player else { return } player.pause() self.player = nil } // MARK: - observers @objc private func playerItemDidReachEnd(notification: Notification) { guard let object = notification.object as? AVPlayerItem, let playerItem = playerItem, object == playerItem else { return } stop() delegateOnVideoComplete() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &VideoPlayerView.playerItemContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } guard keyPath == #keyPath(AVPlayerItem.status) else { return } var status = AVPlayerItem.Status.unknown if let statusNumber = change?[.newKey] as? NSNumber { status = AVPlayerItem.Status(rawValue: statusNumber.intValue)! } playerItemStatusChanged(status) } private func playerItemStatusChanged(_ status: AVPlayerItem.Status) { switch status { case .readyToPlay: let duration = playerItemDuration print("Player item status ---> Ready, duration = \(duration)") if duration == 0 { stop() delegateOnVideoFinished(error: "Player item duration = 0") } else { // Success guard let url = url else { return } delegateOnVideoStarted(url: url) } case .failed: print("Player item status ---> Failed") stop() delegateOnVideoFinished(error: "Player item status is failed") case .unknown: print("Player item status ---> Unknown") @unknown default: break } } // MARK: - delegates private func delegateOnVideoStarted(url: URL) { delegate?.onVideoStarted(url: url) } private func delegateOnVideoComplete() { delegate?.onVideoComplete() } private func delegateOnVideoFinished(error: String) { delegate?.onVideoFinished(error: error) } }
lgpl-3.0
c1f9a54f118750514911521666244355
22.620462
148
0.629174
4.234911
false
false
false
false
almazrafi/Metatron
Sources/ID3v2/FrameStuffs/ID3v2TextInformation.swift
1
4901
// // ID3v2TextInformation.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation open class ID3v2BaseTextInformation: ID3v2FrameStuff { // MARK: Instance Properties public var textEncoding: ID3v2TextEncoding = ID3v2TextEncoding.utf8 public var fields: [String] = [] // MARK: public var isEmpty: Bool { return self.fields.isEmpty } // MARK: Initializers public init() { } public required init(fromData data: [UInt8], version: ID3v2Version) { guard data.count > 1 else { return } guard let textEncoding = ID3v2TextEncoding(rawValue: data[0]) else { return } var offset = 1 var fields: [String] = [] repeat { guard let field = textEncoding.decode([UInt8](data.suffix(from: offset))) else { return } fields.append(field.text) offset += field.endIndex if offset >= data.count { if field.terminated { fields.append("") } break } } while true self.textEncoding = textEncoding self.fields = self.deserialize(fields: fields, version: version) } // MARK: Instance Methods public func toData(version: ID3v2Version) -> [UInt8]? { guard !self.isEmpty else { return nil } let fields = self.serialize(fields: self.fields, version: version) let textEncoding: ID3v2TextEncoding switch version { case ID3v2Version.v2, ID3v2Version.v3: if self.textEncoding == ID3v2TextEncoding.latin1 { textEncoding = ID3v2TextEncoding.latin1 } else { textEncoding = ID3v2TextEncoding.utf16 } case ID3v2Version.v4: textEncoding = self.textEncoding } var data = [textEncoding.rawValue] for i in 0..<(fields.count - 1) { data.append(contentsOf: textEncoding.encode(fields[i], termination: true)) } data.append(contentsOf: textEncoding.encode(fields.last!, termination: false)) return data } public func toData() -> (data: [UInt8], version: ID3v2Version)? { guard let data = self.toData(version: ID3v2Version.v4) else { return nil } return (data: data, version: ID3v2Version.v4) } // MARK: open func deserialize(fields: [String], version: ID3v2Version) -> [String] { return fields } open func serialize(fields: [String], version: ID3v2Version) -> [String] { return fields } } public class ID3v2TextInformation: ID3v2BaseTextInformation { // MARK: Instance Methods public override func deserialize(fields: [String], version: ID3v2Version) -> [String] { return fields } public override func serialize(fields: [String], version: ID3v2Version) -> [String] { return fields } } public class ID3v2TextInformationFormat: ID3v2FrameStuffSubclassFormat { // MARK: Type Properties public static let regular = ID3v2TextInformationFormat() // MARK: Instance Methods public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2TextInformation { return ID3v2TextInformation(fromData: data, version: version) } public func createStuffSubclass(fromOther other: ID3v2TextInformation) -> ID3v2TextInformation { let stuff = ID3v2TextInformation() stuff.textEncoding = other.textEncoding stuff.fields = other.fields return stuff } public func createStuffSubclass() -> ID3v2TextInformation { return ID3v2TextInformation() } }
mit
a010a5c1daf9411b33fd33570602ebf6
27.005714
108
0.640686
4.25434
false
false
false
false
hooman/swift
stdlib/public/core/Array.swift
1
76953
//===--- Array.swift ------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `Array<Element>` is like `ContiguousArray<Element>` when `Element` is not // a reference type or an Objective-C existential. Otherwise, it may use // an `NSArray` bridged from Cocoa for storage. // //===----------------------------------------------------------------------===// /// An ordered, random-access collection. /// /// Arrays are one of the most commonly used data types in an app. You use /// arrays to organize your app's data. Specifically, you use the `Array` type /// to hold elements of a single type, the array's `Element` type. An array /// can store any kind of elements---from integers to strings to classes. /// /// Swift makes it easy to create arrays in your code using an array literal: /// simply surround a comma-separated list of values with square brackets. /// Without any other information, Swift creates an array that includes the /// specified values, automatically inferring the array's `Element` type. For /// example: /// /// // An array of 'Int' elements /// let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15] /// /// // An array of 'String' elements /// let streets = ["Albemarle", "Brandywine", "Chesapeake"] /// /// You can create an empty array by specifying the `Element` type of your /// array in the declaration. For example: /// /// // Shortened forms are preferred /// var emptyDoubles: [Double] = [] /// /// // The full type name is also allowed /// var emptyFloats: Array<Float> = Array() /// /// If you need an array that is preinitialized with a fixed number of default /// values, use the `Array(repeating:count:)` initializer. /// /// var digitCounts = Array(repeating: 0, count: 10) /// print(digitCounts) /// // Prints "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" /// /// Accessing Array Values /// ====================== /// /// When you need to perform an operation on all of an array's elements, use a /// `for`-`in` loop to iterate through the array's contents. /// /// for street in streets { /// print("I don't live on \(street).") /// } /// // Prints "I don't live on Albemarle." /// // Prints "I don't live on Brandywine." /// // Prints "I don't live on Chesapeake." /// /// Use the `isEmpty` property to check quickly whether an array has any /// elements, or use the `count` property to find the number of elements in /// the array. /// /// if oddNumbers.isEmpty { /// print("I don't know any odd numbers.") /// } else { /// print("I know \(oddNumbers.count) odd numbers.") /// } /// // Prints "I know 8 odd numbers." /// /// Use the `first` and `last` properties for safe access to the value of the /// array's first and last elements. If the array is empty, these properties /// are `nil`. /// /// if let firstElement = oddNumbers.first, let lastElement = oddNumbers.last { /// print(firstElement, lastElement, separator: ", ") /// } /// // Prints "1, 15" /// /// print(emptyDoubles.first, emptyDoubles.last, separator: ", ") /// // Prints "nil, nil" /// /// You can access individual array elements through a subscript. The first /// element of a nonempty array is always at index zero. You can subscript an /// array with any integer from zero up to, but not including, the count of /// the array. Using a negative number or an index equal to or greater than /// `count` triggers a runtime error. For example: /// /// print(oddNumbers[0], oddNumbers[3], separator: ", ") /// // Prints "1, 7" /// /// print(emptyDoubles[0]) /// // Triggers runtime error: Index out of range /// /// Adding and Removing Elements /// ============================ /// /// Suppose you need to store a list of the names of students that are signed /// up for a class you're teaching. During the registration period, you need /// to add and remove names as students add and drop the class. /// /// var students = ["Ben", "Ivy", "Jordell"] /// /// To add single elements to the end of an array, use the `append(_:)` method. /// Add multiple elements at the same time by passing another array or a /// sequence of any kind to the `append(contentsOf:)` method. /// /// students.append("Maxime") /// students.append(contentsOf: ["Shakia", "William"]) /// // ["Ben", "Ivy", "Jordell", "Maxime", "Shakia", "William"] /// /// You can add new elements in the middle of an array by using the /// `insert(_:at:)` method for single elements and by using /// `insert(contentsOf:at:)` to insert multiple elements from another /// collection or array literal. The elements at that index and later indices /// are shifted back to make room. /// /// students.insert("Liam", at: 3) /// // ["Ben", "Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"] /// /// To remove elements from an array, use the `remove(at:)`, /// `removeSubrange(_:)`, and `removeLast()` methods. /// /// // Ben's family is moving to another state /// students.remove(at: 0) /// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"] /// /// // William is signing up for a different class /// students.removeLast() /// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia"] /// /// You can replace an existing element with a new value by assigning the new /// value to the subscript. /// /// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// // ["Ivy", "Jordell", "Liam", "Max", "Shakia"] /// /// Growing the Size of an Array /// ---------------------------- /// /// Every array reserves a specific amount of memory to hold its contents. When /// you add elements to an array and that array begins to exceed its reserved /// capacity, the array allocates a larger region of memory and copies its /// elements into the new storage. The new storage is a multiple of the old /// storage's size. This exponential growth strategy means that appending an /// element happens in constant time, averaging the performance of many append /// operations. Append operations that trigger reallocation have a performance /// cost, but they occur less and less often as the array grows larger. /// /// If you know approximately how many elements you will need to store, use the /// `reserveCapacity(_:)` method before appending to the array to avoid /// intermediate reallocations. Use the `capacity` and `count` properties to /// determine how many more elements the array can store without allocating /// larger storage. /// /// For arrays of most `Element` types, this storage is a contiguous block of /// memory. For arrays with an `Element` type that is a class or `@objc` /// protocol type, this storage can be a contiguous block of memory or an /// instance of `NSArray`. Because any arbitrary subclass of `NSArray` can /// become an `Array`, there are no guarantees about representation or /// efficiency in this case. /// /// Modifying Copies of Arrays /// ========================== /// /// Each array has an independent value that includes the values of all of its /// elements. For simple types such as integers and other structures, this /// means that when you change a value in one array, the value of that element /// does not change in any copies of the array. For example: /// /// var numbers = [1, 2, 3, 4, 5] /// var numbersCopy = numbers /// numbers[0] = 100 /// print(numbers) /// // Prints "[100, 2, 3, 4, 5]" /// print(numbersCopy) /// // Prints "[1, 2, 3, 4, 5]" /// /// If the elements in an array are instances of a class, the semantics are the /// same, though they might appear different at first. In this case, the /// values stored in the array are references to objects that live outside the /// array. If you change a reference to an object in one array, only that /// array has a reference to the new object. However, if two arrays contain /// references to the same object, you can observe changes to that object's /// properties from both arrays. For example: /// /// // An integer type with reference semantics /// class IntegerReference { /// var value = 10 /// } /// var firstIntegers = [IntegerReference(), IntegerReference()] /// var secondIntegers = firstIntegers /// /// // Modifications to an instance are visible from either array /// firstIntegers[0].value = 100 /// print(secondIntegers[0].value) /// // Prints "100" /// /// // Replacements, additions, and removals are still visible /// // only in the modified array /// firstIntegers[0] = IntegerReference() /// print(firstIntegers[0].value) /// // Prints "10" /// print(secondIntegers[0].value) /// // Prints "100" /// /// Arrays, like all variable-size collections in the standard library, use /// copy-on-write optimization. Multiple copies of an array share the same /// storage until you modify one of the copies. When that happens, the array /// being modified replaces its storage with a uniquely owned copy of itself, /// which is then modified in place. Optimizations are sometimes applied that /// can reduce the amount of copying. /// /// This means that if an array is sharing storage with other copies, the first /// mutating operation on that array incurs the cost of copying the array. An /// array that is the sole owner of its storage can perform mutating /// operations in place. /// /// In the example below, a `numbers` array is created along with two copies /// that share the same storage. When the original `numbers` array is /// modified, it makes a unique copy of its storage before making the /// modification. Further modifications to `numbers` are made in place, while /// the two copies continue to share the original storage. /// /// var numbers = [1, 2, 3, 4, 5] /// var firstCopy = numbers /// var secondCopy = numbers /// /// // The storage for 'numbers' is copied here /// numbers[0] = 100 /// numbers[1] = 200 /// numbers[2] = 300 /// // 'numbers' is [100, 200, 300, 4, 5] /// // 'firstCopy' and 'secondCopy' are [1, 2, 3, 4, 5] /// /// Bridging Between Array and NSArray /// ================================== /// /// When you need to access APIs that require data in an `NSArray` instance /// instead of `Array`, use the type-cast operator (`as`) to bridge your /// instance. For bridging to be possible, the `Element` type of your array /// must be a class, an `@objc` protocol (a protocol imported from Objective-C /// or marked with the `@objc` attribute), or a type that bridges to a /// Foundation type. /// /// The following example shows how you can bridge an `Array` instance to /// `NSArray` to use the `write(to:atomically:)` method. In this example, the /// `colors` array can be bridged to `NSArray` because the `colors` array's /// `String` elements bridge to `NSString`. The compiler prevents bridging the /// `moreColors` array, on the other hand, because its `Element` type is /// `Optional<String>`, which does *not* bridge to a Foundation type. /// /// let colors = ["periwinkle", "rose", "moss"] /// let moreColors: [String?] = ["ochre", "pine"] /// /// let url = URL(fileURLWithPath: "names.plist") /// (colors as NSArray).write(to: url, atomically: true) /// // true /// /// (moreColors as NSArray).write(to: url, atomically: true) /// // error: cannot convert value of type '[String?]' to type 'NSArray' /// /// Bridging from `Array` to `NSArray` takes O(1) time and O(1) space if the /// array's elements are already instances of a class or an `@objc` protocol; /// otherwise, it takes O(*n*) time and space. /// /// When the destination array's element type is a class or an `@objc` /// protocol, bridging from `NSArray` to `Array` first calls the `copy(with:)` /// (`- copyWithZone:` in Objective-C) method on the array to get an immutable /// copy and then performs additional Swift bookkeeping work that takes O(1) /// time. For instances of `NSArray` that are already immutable, `copy(with:)` /// usually returns the same array in O(1) time; otherwise, the copying /// performance is unspecified. If `copy(with:)` returns the same array, the /// instances of `NSArray` and `Array` share storage using the same /// copy-on-write optimization that is used when two instances of `Array` /// share storage. /// /// When the destination array's element type is a nonclass type that bridges /// to a Foundation type, bridging from `NSArray` to `Array` performs a /// bridging copy of the elements to contiguous storage in O(*n*) time. For /// example, bridging from `NSArray` to `Array<Int>` performs such a copy. No /// further bridging is required when accessing elements of the `Array` /// instance. /// /// - Note: The `ContiguousArray` and `ArraySlice` types are not bridged; /// instances of those types always have a contiguous block of memory as /// their storage. @frozen public struct Array<Element>: _DestructorSafeContainer { #if _runtime(_ObjC) @usableFromInline internal typealias _Buffer = _ArrayBuffer<Element> #else @usableFromInline internal typealias _Buffer = _ContiguousArrayBuffer<Element> #endif @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } } //===--- private helpers---------------------------------------------------===// extension Array { /// Returns `true` if the array is native and does not need a deferred /// type check. May be hoisted by the optimizer, which means its /// results may be stale by the time they are used if there is an /// inout violation in user code. @inlinable @_semantics("array.props.isNativeTypeChecked") public // @testable func _hoistableIsNativeTypeChecked() -> Bool { return _buffer.arrayPropertyIsNativeTypeChecked } @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.immutableCount } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.immutableCapacity } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _buffer = _buffer._consumeAndCreateNew() } } /// Marks the end of an Array mutation. /// /// After a call to `_endMutation` the buffer must not be mutated until a call /// to `_makeMutableAndUnique`. @_alwaysEmitIntoClient @_semantics("array.end_mutation") internal mutating func _endMutation() { _buffer.endCOWMutation() } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// This function is not used anymore, but must stay in the library for ABI /// compatibility. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _ = _checkSubscript(index, wasNativeTypeChecked: true) } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @_semantics("array.check_subscript") public // @testable func _checkSubscript( _ index: Int, wasNativeTypeChecked: Bool ) -> _DependenceToken { #if _runtime(_ObjC) _buffer._checkInoutAndNativeTypeCheckedBounds( index, wasNativeTypeChecked: wasNativeTypeChecked) #else _buffer._checkValidSubscript(index) #endif return _DependenceToken() } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be uniquely referenced and native. @_alwaysEmitIntoClient @_semantics("array.check_subscript") internal func _checkSubscript_mutating(_ index: Int) { _buffer._checkValidSubscriptMutating(index) } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "Array index is out of range") _precondition(index >= startIndex, "Negative Array index is out of range") } @_semantics("array.get_element") @inlinable // FIXME(inline-always) @inline(__always) public // @testable func _getElement( _ index: Int, wasNativeTypeChecked: Bool, matchingSubscriptCheck: _DependenceToken ) -> Element { #if _runtime(_ObjC) return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked) #else return _buffer.getElement(index) #endif } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.firstElementAddress + index } } extension Array: _ArrayProtocol { /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 10 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { @inlinable // FIXME(inline-always) @inline(__always) get { return _buffer.owner } } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } } extension Array: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<Array> /// The position of the first element in a nonempty array. /// /// For an instance of `Array`, `startIndex` is always zero. If the array /// is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return 0 } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Int { @inlinable get { return _getCount() } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array or uses a /// bridged `NSArray` instance as its storage, in which case writing is /// O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { // This call may be hoisted or eliminated by the optimizer. If // there is an inout violation, this value may be stale so needs to be // checked again below. let wasNativeTypeChecked = _hoistableIsNativeTypeChecked() // Make sure the index is in range and wasNativeTypeChecked is // still valid. let token = _checkSubscript( index, wasNativeTypeChecked: wasNativeTypeChecked) return _getElement( index, wasNativeTypeChecked: wasNativeTypeChecked, matchingSubscriptCheck: token) } _modify { _makeMutableAndUnique() // makes the array native, too _checkSubscript_mutating(index) let address = _buffer.mutableFirstElementAddress + index yield &address.pointee _endMutation(); } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } } extension Array: ExpressibleByArrayLiteral { // Optimized implementation for Array /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler /// when you use an array literal. Instead, create a new array by using an /// array literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding /// only strings. /// /// let ingredients = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self = elements } } extension Array: RangeReplaceableCollection { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init.empty") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImages(withNames names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImages(withNames: colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self = Array( _buffer: _Buffer( _buffer: s._copyToContiguousArray()._buffer, shiftedToStartIndex: 0)) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = Array._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } _endMutation() } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct an Array of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct Array with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = Array._allocateBufferUninitialized(minimumCapacity: count) _buffer.mutableCount = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// an Array of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (Array, UnsafeMutablePointer<Element>) { let result = Array(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } /// Returns an Array of `count` uninitialized elements using the /// given `storage`, and a pointer to uninitialized memory for the /// first element. /// /// - Precondition: `storage is _ContiguousArrayStorage`. @inlinable @_semantics("array.uninitialized") internal static func _adoptStorage( _ storage: __owned _ContiguousArrayStorage<Element>, count: Int ) -> (Array, UnsafeMutablePointer<Element>) { let innerBuffer = _ContiguousArrayBuffer<Element>( count: count, storage: storage) return ( Array( _buffer: _Buffer(_buffer: innerBuffer, shiftedToStartIndex: 0)), innerBuffer.firstElementAddress) } /// Entry point for aborting literal construction: deallocates /// an Array containing only uninitialized elements. @inlinable internal mutating func _deallocateUninitialized() { // Set the count to zero and just release as normal. // Somewhat of a hack. _buffer.mutableCount = 0 } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// Calling the `reserveCapacity(_:)` method on an array with bridged storage /// triggers a copy to contiguous storage even if the existing storage /// has room to store `minimumCapacity` elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { _reserveCapacityImpl(minimumCapacity: minimumCapacity, growForAppend: false) _endMutation() } /// Reserves enough space to store `minimumCapacity` elements. /// If a new buffer needs to be allocated and `growForAppend` is true, /// the new capacity is calculated using `_growArrayCapacity`, but at least /// kept at `minimumCapacity`. @_alwaysEmitIntoClient internal mutating func _reserveCapacityImpl( minimumCapacity: Int, growForAppend: Bool ) { let isUnique = _buffer.beginCOWMutation() if _slowPath(!isUnique || _buffer.mutableCapacity < minimumCapacity) { _createNewBuffer(bufferIsUnique: isUnique, minimumCapacity: Swift.max(minimumCapacity, _buffer.count), growForAppend: growForAppend) } _internalInvariant(_buffer.mutableCapacity >= minimumCapacity) _internalInvariant(_buffer.mutableCapacity == 0 || _buffer.isUniquelyReferenced()) } /// Creates a new buffer, replacing the current buffer. /// /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely /// referenced by this array and the elements are moved - instead of copied - /// to the new buffer. /// The `minimumCapacity` is the lower bound for the new capacity. /// If `growForAppend` is true, the new capacity is calculated using /// `_growArrayCapacity`, but at least kept at `minimumCapacity`. @_alwaysEmitIntoClient internal mutating func _createNewBuffer( bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool ) { _internalInvariant(!bufferIsUnique || _buffer.isUniquelyReferenced()) _buffer = _buffer._consumeAndCreateNew(bufferIsUnique: bufferIsUnique, minimumCapacity: minimumCapacity, growForAppend: growForAppend) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount + 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate(&newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _createNewBuffer(bufferIsUnique: false, minimumCapacity: count + 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. let capacity = _buffer.mutableCapacity _internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount + 1 > capacity) { _createNewBuffer(bufferIsUnique: capacity > 0, minimumCapacity: oldCount + 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: __owned Element ) { _internalInvariant(_buffer.isMutableAndUniquelyReferenced()) _internalInvariant(_buffer.mutableCapacity >= _buffer.mutableCount + 1) _buffer.mutableCount = oldCount + 1 (_buffer.mutableFirstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: __owned Element) { // Separating uniqueness check and capacity check allows hoisting the // uniqueness check out of a loop. _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _buffer.mutableCount _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) _endMutation() } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element { defer { _endMutation() } let newElementsCount = newElements.underestimatedCount _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) let oldCount = _buffer.mutableCount let startNewElements = _buffer.mutableFirstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: _buffer.mutableCapacity - oldCount) var (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate // This check prevents a data race writing to _swiftEmptyArrayStorage if writtenCount > 0 { _buffer.mutableCount = _buffer.mutableCount + writtenCount } if _slowPath(writtenUpTo == buf.endIndex) { // A shortcut for appending an Array: If newElements is an Array then it's // guaranteed that buf.initialize(from: newElements) already appended all // elements. It reduces code size, because the following code // can be removed by the optimizer by constant folding this check in a // generic specialization. if S.self == [Element].self { _internalInvariant(remainder.next() == nil) return } // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode var newCount = _buffer.mutableCount var nextItem = remainder.next() while nextItem != nil { _reserveCapacityAssumingUniqueBuffer(oldCount: newCount) let currentCapacity = _buffer.mutableCapacity let base = _buffer.mutableFirstElementAddress // fill while there is another item and spare capacity while let next = nextItem, newCount < currentCapacity { (base + newCount).initialize(to: next) newCount += 1 nextItem = remainder.next() } _buffer.mutableCount = newCount } } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) _endMutation() } @inlinable @_semantics("array.mutate_unknown") public mutating func _customRemoveLast() -> Element? { _makeMutableAndUnique() let newCount = _buffer.mutableCount - 1 _precondition(newCount >= 0, "Can't removeLast from an empty Array") let pointer = (_buffer.mutableFirstElementAddress + newCount) let element = pointer.move() _buffer.mutableCount = newCount _endMutation() return element } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the array. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable @discardableResult @_semantics("array.mutate_unknown") public mutating func remove(at index: Int) -> Element { _makeMutableAndUnique() let currentCount = _buffer.mutableCount _precondition(index < currentCount, "Index out of range") _precondition(index >= 0, "Index out of range") let newCount = currentCount - 1 let pointer = (_buffer.mutableFirstElementAddress + index) let result = pointer.move() pointer.moveInitialize(from: pointer + 1, count: newCount - index) _buffer.mutableCount = newCount _endMutation() return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: __owned Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable") public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeBufferPointer { (bufferPointer) -> R in return try body(bufferPointer) } } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(self) } } // Implementations of + and += for same-type arrays. This combined // with the operator declarations for these operators designating this // type as a place to prefer this operator help the expression type // checker speed up cases where there is a large number of uses of the // operator in the same expression. extension Array { @inlinable public static func + (lhs: Array, rhs: Array) -> Array { var lhs = lhs lhs.append(contentsOf: rhs) return lhs } @inlinable public static func += (lhs: inout Array, rhs: Array) { lhs.append(contentsOf: rhs) } } extension Array: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } extension Array: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription() } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { // Always show sugared representation for Arrays. return _makeCollectionDescription() } } extension Array { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension Array { /// Implementation for Array(unsafeUninitializedCapacity:initializingWith:) /// and ContiguousArray(unsafeUninitializedCapacity:initializingWith:) @inlinable internal init( _unsafeUninitializedCapacity: Int, initializingWith initializer: ( _ buffer: inout UnsafeMutableBufferPointer<Element>, _ initializedCount: inout Int) throws -> Void ) rethrows { var firstElementAddress: UnsafeMutablePointer<Element> (self, firstElementAddress) = Array._allocateUninitialized(_unsafeUninitializedCapacity) var initializedCount = 0 var buffer = UnsafeMutableBufferPointer<Element>( start: firstElementAddress, count: _unsafeUninitializedCapacity) defer { // Update self.count even if initializer throws an error. _precondition( initializedCount <= _unsafeUninitializedCapacity, "Initialized count set to greater than specified capacity." ) _precondition( buffer.baseAddress == firstElementAddress, "Can't reassign buffer in Array(unsafeUninitializedCapacity:initializingWith:)" ) self._buffer.mutableCount = initializedCount _endMutation() } try initializer(&buffer, &initializedCount) } /// Creates an array with the specified capacity, then calls the given /// closure with a buffer covering the array's uninitialized memory. /// /// Inside the closure, set the `initializedCount` parameter to the number of /// elements that are initialized by the closure. The memory in the range /// `buffer[0..<initializedCount]` must be initialized at the end of the /// closure's execution, and the memory in the range /// `buffer[initializedCount...]` must be uninitialized. This postcondition /// must hold even if the `initializer` closure throws an error. /// /// - Note: While the resulting array may have a capacity larger than the /// requested amount, the buffer passed to the closure will cover exactly /// the requested number of elements. /// /// - Parameters: /// - unsafeUninitializedCapacity: The number of elements to allocate /// space for in the new array. /// - initializer: A closure that initializes elements and sets the count /// of the new array. /// - Parameters: /// - buffer: A buffer covering uninitialized memory with room for the /// specified number of elements. /// - initializedCount: The count of initialized elements in the array, /// which begins as zero. Set `initializedCount` to the number of /// elements you initialize. @_alwaysEmitIntoClient @inlinable public init( unsafeUninitializedCapacity: Int, initializingWith initializer: ( _ buffer: inout UnsafeMutableBufferPointer<Element>, _ initializedCount: inout Int) throws -> Void ) rethrows { self = try Array( _unsafeUninitializedCapacity: unsafeUninitializedCapacity, initializingWith: initializer) } /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If no such storage exists, it is created. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inlinable // FIXME(inline-always) @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _makeMutableAndUnique() let count = _buffer.mutableCount // Create an UnsafeBufferPointer that we can pass to body let pointer = _buffer.mutableFirstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "Array withUnsafeMutableBufferPointer: replacing the buffer is not allowed") _endMutation() _fixLifetime(self) } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension Array { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: __owned C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= self._buffer.startIndex, "Array replace: subrange start is negative") _precondition(subrange.upperBound <= _buffer.endIndex, "Array replace: subrange extends past the end") let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount _reserveCapacityImpl(minimumCapacity: self.count + growth, growForAppend: true) _buffer.replaceSubrange(subrange, with: insertCount, elementsOf: newElements) _endMutation() } } extension Array: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } _internalInvariant(lhs.startIndex == 0 && rhs.startIndex == 0) _internalInvariant(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount) // We know that lhs.count == rhs.count, compare element wise. for idx in 0..<lhsCount { if lhs[idx] != rhs[idx] { return false } } return true } } extension Array: Hashable where Element: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension Array { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int32`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers: [Int32] = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } } #if INTERNAL_CHECKS_ENABLED extension Array { // This allows us to test the `_copyContents` implementation in // `_ArrayBuffer`. (It's like `_copyToContiguousArray` but it always makes a // copy.) @_alwaysEmitIntoClient public func _copyToNewArray() -> [Element] { Array(unsafeUninitializedCapacity: self.count) { buffer, count in var (it, c) = self._buffer._copyContents(initializing: buffer) _precondition(it.next() == nil) count = c } } } #endif #if _runtime(_ObjC) // We isolate the bridging of the Cocoa Array -> Swift Array here so that // in the future, we can eagerly bridge the Cocoa array. We need this function // to do the bridging in an ABI safe way. Even though this looks useless, // DO NOT DELETE! @usableFromInline internal func _bridgeCocoaArray<T>(_ _immutableCocoaArray: AnyObject) -> Array<T> { return Array(_buffer: _ArrayBuffer(nsArray: _immutableCocoaArray)) } extension Array { @inlinable public // @SPI(Foundation) func _bridgeToObjectiveCImpl() -> AnyObject { return _buffer._asCocoaArray() } /// Tries to downcast the source `NSArray` as our native buffer type. /// If it succeeds, creates a new `Array` around it and returns that. /// Returns `nil` otherwise. // Note: this function exists here so that Foundation doesn't have // to know Array's implementation details. @inlinable public static func _bridgeFromObjectiveCAdoptingNativeStorageOf( _ source: AnyObject ) -> Array? { // If source is deferred, we indirect to get its native storage let maybeNative = (source as? __SwiftDeferredNSArray)?._nativeStorage ?? source return (maybeNative as? _ContiguousArrayStorage<Element>).map { Array(_ContiguousArrayBuffer($0)) } } /// Private initializer used for bridging. /// /// Only use this initializer when both conditions are true: /// /// * it is statically known that the given `NSArray` is immutable; /// * `Element` is bridged verbatim to Objective-C (i.e., /// is a reference type). @inlinable public init(_immutableCocoaArray: AnyObject) { self = _bridgeCocoaArray(_immutableCocoaArray) } } #endif extension Array: _HasCustomAnyHashableRepresentation where Element: Hashable { public __consuming func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(_box: _ArrayAnyHashableBox(self)) } } internal protocol _ArrayAnyHashableProtocol: _AnyHashableBox { var count: Int { get } subscript(index: Int) -> AnyHashable { get } } internal struct _ArrayAnyHashableBox<Element: Hashable> : _ArrayAnyHashableProtocol { internal let _value: [Element] internal init(_ value: [Element]) { self._value = value } internal var _base: Any { return _value } internal var count: Int { return _value.count } internal subscript(index: Int) -> AnyHashable { return _value[index] as AnyHashable } func _isEqual(to other: _AnyHashableBox) -> Bool? { guard let other = other as? _ArrayAnyHashableProtocol else { return nil } guard _value.count == other.count else { return false } for i in 0 ..< _value.count { if self[i] != other[i] { return false } } return true } var _hashValue: Int { var hasher = Hasher() _hash(into: &hasher) return hasher.finalize() } func _hash(into hasher: inout Hasher) { hasher.combine(_value.count) // discriminator for i in 0 ..< _value.count { hasher.combine(self[i]) } } func _rawHashValue(_seed: Int) -> Int { var hasher = Hasher(_seed: _seed) self._hash(into: &hasher) return hasher._finalize() } internal func _unbox<T: Hashable>() -> T? { return _value as? T } internal func _downCastConditional<T>( into result: UnsafeMutablePointer<T> ) -> Bool { guard let value = _value as? T else { return false } result.initialize(to: value) return true } } extension Array: Sendable, UnsafeSendable where Element: Sendable { }
apache-2.0
b1272d3739eac25d75a9deb751218ea2
37.645404
101
0.661113
4.371761
false
false
false
false
AliSoftware/SwiftGen
Sources/SwiftGenKit/Parsers/AnyCodable.swift
1
4589
// // SwiftGen // Copyright © 2020 SwiftGen // MIT Licence // // Original credits to Ian Keen (https://gist.github.com/IanKeen/df3bed29e2613ead94aa3b16967b9d14) import Foundation // swiftlint:disable cyclomatic_complexity function_body_length public struct AnyCodable: Codable { public let value: Any? public init(_ value: Any?) { self.value = value } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self.value = nil } else if let value = try? container.decode([String: AnyCodable].self) { self.value = value.compactMapValues({ $0.value }) } else if let value = try? container.decode([AnyCodable].self) { self.value = value.compactMap({ $0.value }) } else if let value = try? container.decode(Bool.self) { self.value = value } else if let value = try? container.decode(String.self) { self.value = value } else if let value = try? container.decode(Date.self) { self.value = value } else if let value = try? container.decode(Int.self) { self.value = value } else if let value = try? container.decode(Int8.self) { self.value = value } else if let value = try? container.decode(Int16.self) { self.value = value } else if let value = try? container.decode(Int32.self) { self.value = value } else if let value = try? container.decode(Int64.self) { self.value = value } else if let value = try? container.decode(UInt.self) { self.value = value } else if let value = try? container.decode(UInt8.self) { self.value = value } else if let value = try? container.decode(UInt16.self) { self.value = value } else if let value = try? container.decode(UInt32.self) { self.value = value } else if let value = try? container.decode(UInt64.self) { self.value = value } else if let value = try? container.decode(Double.self) { self.value = value } else if let value = try? container.decode(Float.self) { self.value = value } else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "Unable to decode value" ) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch value { case nil: try container.encodeNil() case let value as [String: AnyCodable]: try container.encode(value) case let value as [String: Any]: try container.encode(value.mapValues(AnyCodable.init)) case let value as [AnyCodable]: try container.encode(value) case let value as [Any]: try container.encode(value.map(AnyCodable.init)) case let value as Bool: try container.encode(value) case let value as String: try container.encode(value) case let value as Date: try container.encode(value) case let value as Int: try container.encode(value) case let value as Int8: try container.encode(value) case let value as Int16: try container.encode(value) case let value as Int32: try container.encode(value) case let value as Int64: try container.encode(value) case let value as UInt: try container.encode(value) case let value as UInt8: try container.encode(value) case let value as UInt16: try container.encode(value) case let value as UInt32: try container.encode(value) case let value as UInt64: try container.encode(value) case let value as Double: try container.encode(value) case let value as Float: try container.encode(value) default: throw EncodingError.invalidValue( value ?? "<nil>", .init(codingPath: container.codingPath, debugDescription: "Unable to encode value") ) } } } // swiftlint:enable cyclomatic_complexity function_body_length extension KeyedDecodingContainer { public func decode(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any] { let anyCodable = try decode(AnyCodable.self, forKey: key) guard let value = anyCodable.value as? [String: Any] else { let type = Swift.type(of: anyCodable.value) throw DecodingError.typeMismatch( type, .init(codingPath: self.codingPath, debugDescription: "Expected [String: Any], found \(type)") ) } return value } } extension KeyedEncodingContainer { public mutating func encode(_ value: [String: Any], forKey key: K) throws { try encode(AnyCodable(value), forKey: key) } }
mit
0d38df799f865a63ed3497d4cdcefb8a
32.489051
101
0.660418
3.921368
false
false
false
false
hanquochan/Charts
Tests/Charts/ChartUtilsTests.swift
1
1905
import XCTest @testable import Charts class ChartUtilsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDecimalWithNaN() { let number = Double.nan let actual = ChartUtils.decimals(number) let expected = 0 XCTAssertEqual(expected, actual) } func testDecimalWithInfinite() { let number = Double.infinity let actual = ChartUtils.decimals(number) let expected = 0 XCTAssertEqual(expected, actual) } func testDecimalWithZero() { let number = 0.0 let actual = ChartUtils.decimals(number) let expected = 0 XCTAssertEqual(expected, actual) } func testDecimalWithMaxValue() { let number = Double.greatestFiniteMagnitude let actual = ChartUtils.decimals(number) let expected = 0 XCTAssertEqual(expected, actual) } func testDecimalWithMinValue() { let number = Double.leastNormalMagnitude let actual = ChartUtils.decimals(number) let expected = 310 // Don't think this is supposed to be this value maybe 0? XCTAssertEqual(expected, actual) } func testDecimalWithNormalValue() { let number = 13.123123 let actual = ChartUtils.decimals(number) let expected = 1 // Don't think this is supposed to be this value maybe 6? XCTAssertEqual(expected, actual) } }
apache-2.0
6df9351ccd8114a572b7c0329df813c7
24.4
111
0.579528
5.537791
false
true
false
false
oisdk/SwiftSequence
Sources/Zip.swift
1
2943
/// :nodoc: public struct NilPaddedZipGenerator<G0: GeneratorType, G1: GeneratorType> : GeneratorType { private var (g0, g1): (G0?, G1?) public mutating func next() -> (G0.Element?, G1.Element?)? { let (e0,e1) = (g0?.next(),g1?.next()) switch (e0,e1) { case (nil,nil): return nil case ( _,nil): g1 = nil case (nil, _): g0 = nil default: break } return (e0,e1) } } /// :nodoc: public struct NilPaddedZip<S0: SequenceType, S1: SequenceType> : LazySequenceType { private let (s0, s1): (S0, S1) /// :nodoc: public func generate() -> NilPaddedZipGenerator<S0.Generator, S1.Generator> { return NilPaddedZipGenerator(g0: s0.generate(), g1: s1.generate()) } } /// A sequence of pairs built out of two underlying sequences, where the elements of the /// ith pair are optional ith elements of each underlying sequence. If one sequence is /// shorter than the other, pairs will continue to be returned after it is exhausted, but /// with its elements replaced by nil. /// ```swift /// zipWithPadding([1, 2, 3], [1, 2]) /// /// (1?, 1?), (2?, 2?), (3?, nil) /// ``` @warn_unused_result public func zipWithPadding<S0: SequenceType, S1: SequenceType>(s0: S0, _ s1: S1) -> NilPaddedZip<S0, S1> { return NilPaddedZip(s0: s0, s1: s1) } /// :nodoc: public struct PaddedZipGenerator<G0: GeneratorType, G1: GeneratorType> : GeneratorType { typealias E0 = G0.Element typealias E1 = G1.Element private var g: NilPaddedZipGenerator<G0, G1> private let (p0, p1): (E0, E1) public mutating func next() -> (E0, E1)? { guard let (e0,e1) = g.next() else { return nil } return (e0 ?? p0, e1 ?? p1) } } /// :nodoc: public struct PaddedZip<S0: SequenceType, S1: SequenceType> : LazySequenceType { private let (s0, s1): (S0, S1) private let (p0, p1): (S0.Generator.Element, S1.Generator.Element) /// :nodoc: public func generate() -> PaddedZipGenerator<S0.Generator, S1.Generator> { return PaddedZipGenerator( g: NilPaddedZipGenerator( g0: s0.generate(), g1: s1.generate() ), p0: p0, p1: p1 ) } } /// A sequence of pairs built out of two underlying sequences, where the elements of the /// ith pair are the ith elements of each underlying sequence. If one sequence is /// shorter than the other, pairs will continue to be returned after it is exhausted, but /// with its elements replaced by its respective pad. /// - Parameter pad0: the element to pad `s0` with after it is exhausted /// - Parameter pad1: the element to pad `s1` with after it is exhausted /// ```swift /// zipWithPadding([1, 2, 3], [1, 2], pad0: 100, pad1: 900) /// /// (1, 1), (2, 2), (3, 900) /// ``` @warn_unused_result public func zipWithPadding< S0: SequenceType, S1: SequenceType >(s0: S0, _ s1: S1, pad0: S0.Generator.Element, pad1: S1.Generator.Element) -> PaddedZip<S0, S1> { return PaddedZip(s0: s0, s1: s1, p0: pad0, p1: pad1) }
mit
a7d039b2bc237afa72830683bba4f392
31.7
91
0.647638
3.10443
false
false
false
false
malcommac/SwiftSimplify
Sources/SwiftSimplify/Point2DRepresentable.swift
1
3167
// // SwiftSimplify.swift // Simplify // // Created by Daniele Margutti on 28/06/2019. // Copyright (c) 2019 Daniele Margutti. All rights reserved // Original work by https://mourner.github.io/simplify-js/ // // Web: http://www.danielemargutti.com // Mail: [email protected] // Twitter: http://www.twitter.com/danielemargutti // GitHub: http://www.github.com/malcommac // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import CoreLocation public protocol Point2DRepresentable { var xValue: Float { get } var yValue: Float { get } var cgPoint: CGPoint { get } func distanceFrom(_ otherPoint: Self) -> Float func distanceToSegment(_ p1: Self, _ p2: Self) -> Float func equalsTo(_ compare: Self) -> Bool } public extension Point2DRepresentable { func equalsTo(_ compare: Self) -> Bool { xValue == compare.xValue && yValue == compare.yValue } func distanceFrom(_ otherPoint: Self) -> Float { let dx = xValue - otherPoint.xValue let dy = yValue - otherPoint.yValue return (dx * dx) + (dy * dy) } func distanceToSegment(_ p1: Self, _ p2: Self) -> Float { var x = p1.xValue var y = p1.yValue var dx = p2.xValue - x var dy = p2.yValue - y if dx != 0 || dy != 0 { let t = ((xValue - x) * dx + (yValue - y) * dy) / (dx * dx + dy * dy) if t > 1 { x = p2.xValue y = p2.yValue } else if t > 0 { x += dx * t y += dy * t } } dx = xValue - x dy = yValue - y return dx * dx + dy * dy } } extension CLLocationCoordinate2D: Point2DRepresentable { public var xValue: Float { Float(latitude) } public var yValue: Float { Float(longitude) } public var cgPoint: CGPoint { CGPoint(x: latitude, y: longitude) } } extension CGPoint: Point2DRepresentable { public var xValue: Float { Float(x) } public var yValue: Float { Float(y) } public var cgPoint: CGPoint { self } }
mit
bf34cadf2dea162b313ab76b9f2b044b
31.649485
81
0.631828
4.097025
false
false
false
false
mattjgalloway/emoncms-ios
EmonCMSiOSTests/EmonCMSAPITests.swift
1
6372
// // EmonCMSiOSTests.swift // EmonCMSiOSTests // // Created by Matt Galloway on 15/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Quick import Nimble import RxSwift import RxTest @testable import EmonCMSiOS class EmonCMSAPITests: QuickSpec { override func spec() { var disposeBag: DisposeBag! var scheduler: TestScheduler! var requestProvider: MockHTTPRequestProvider! var api: EmonCMSAPI! var account: Account! func call<T>(api: Observable<T>, observer: TestableObserver<T>, expect: @escaping () -> Void) { let sharedResult = api.shareReplay(1) sharedResult .subscribe(observer) .addDisposableTo(disposeBag) waitUntil { done in sharedResult .subscribe( onError: { error in fail(error.localizedDescription) done() }, onCompleted: { expect() done() }) .addDisposableTo(disposeBag) } } beforeEach { disposeBag = DisposeBag() scheduler = TestScheduler(initialClock: 0) requestProvider = MockHTTPRequestProvider() api = EmonCMSAPI(requestProvider: requestProvider) account = Account(uuid: UUID(), url: "http://test", apikey: "ilikecats") } describe("feedList") { it("should return feeds") { let observer = scheduler.createObserver([Feed].self) let result = api.feedList(account).shareReplay(1) call(api: result, observer: observer) { expect(observer.events.count).to(equal(2)) expect(observer.events[0].value.element).notTo(beNil()) expect(observer.events[0].value.element!.count).to(equal(2)) } scheduler.start() } } describe("feedFields") { it("should fetch all fields for a given feed") { let observer = scheduler.createObserver(Feed.self) let result = api.feedFields(account, id: "1") call(api: result, observer: observer) { expect(observer.events.count).to(equal(2)) expect(observer.events[0].value.element).notTo(beNil()) } scheduler.start() } } describe("feedField") { it("should fetch the given field for the feed") { let observer = scheduler.createObserver(String.self) let result = api.feedField(account, id: "1", fieldName: "name") call(api: result, observer: observer) { expect(observer.events.count).to(equal(2)) expect(observer.events[0].value.element).notTo(beNil()) expect(observer.events[0].value.element).to(equal("use")) } scheduler.start() } } describe("feedData") { it("should fetch the data for the feed") { let observer = scheduler.createObserver([DataPoint].self) let result = api.feedData(account, id: "1", at: Date()-100, until: Date(), interval: 10) call(api: result, observer: observer) { expect(observer.events.count).to(equal(2)) expect(observer.events[0].value.element).notTo(beNil()) expect(observer.events[0].value.element!.count).to(equal(10)) } scheduler.start() } } describe("feedDataDaily") { it("should fetch the data for the feed") { let observer = scheduler.createObserver([DataPoint].self) let result = api.feedDataDaily(account, id: "1", at: Date()-100, until: Date()) call(api: result, observer: observer) { expect(observer.events.count).to(equal(2)) expect(observer.events[0].value.element).notTo(beNil()) expect(observer.events[0].value.element!.count).to(equal(3)) } scheduler.start() } } describe("feedValue") { it("should fetch the value for the feed") { let observer = scheduler.createObserver(Double.self) let result = api.feedValue(account, id: "1") call(api: result, observer: observer) { expect(observer.events.count).to(equal(2)) expect(observer.events[0].value.element).notTo(beNil()) expect(observer.events[0].value.element!).to(equal(100)) } scheduler.start() } it("should fetch the value for the feeds") { let observer = scheduler.createObserver([String:Double].self) let result = api.feedValue(account, ids: ["1", "2", "3"]) call(api: result, observer: observer) { expect(observer.events.count).to(equal(2)) expect(observer.events[0].value.element).notTo(beNil()) expect(observer.events[0].value.element!.count).to(equal(3)) expect(observer.events[0].value.element!).to(equal(["1":100,"2":200,"3":300])) } scheduler.start() } } describe("extractAPIDetailsFromURLString") { it("should work for a correct url") { let url = "https://emoncms.org/app?readkey=1a101b101c101d101e101f101a101b10#myelectric" let result = EmonCMSAPI.extractAPIDetailsFromURLString(url) expect(result).notTo(beNil()) expect(result!.host).to(equal("https://emoncms.org")) expect(result!.apikey).to(equal("1a101b101c101d101e101f101a101b10")) } it("should work for a correct url where emoncms is not at the root") { let url = "https://emoncms.org/notatroot/app?readkey=1a101b101c101d101e101f101a101b10#myelectric" let result = EmonCMSAPI.extractAPIDetailsFromURLString(url) expect(result).notTo(beNil()) expect(result!.host).to(equal("https://emoncms.org/notatroot")) expect(result!.apikey).to(equal("1a101b101c101d101e101f101a101b10")) } it("should work for a correct url where /app is in the path") { let url = "https://emoncms.org/something/app/app?readkey=1a101b101c101d101e101f101a101b10#myelectric" let result = EmonCMSAPI.extractAPIDetailsFromURLString(url) expect(result).notTo(beNil()) expect(result!.host).to(equal("https://emoncms.org/something/app")) expect(result!.apikey).to(equal("1a101b101c101d101e101f101a101b10")) } it("should fail when the url is malformed") { let url = "https://www.google.com" let result = EmonCMSAPI.extractAPIDetailsFromURLString(url) expect(result).to(beNil()) } } } }
mit
4b8c701e59f0f2844e67878a8970962d
31.015075
109
0.621096
3.891875
false
false
false
false
alex-alex/S2Geometry
Sources/S2Edge.swift
1
492
// // S2Edge.swift // S2Geometry // // Created by Alex Studnicka on 7/1/16. // Copyright © 2016 Alex Studnicka. MIT License. // /** An abstract directed edge from one S2Point to another S2Point. */ public struct S2Edge: Equatable { public let start: S2Point public let end: S2Point public init(start: S2Point, end: S2Point) { self.start = start self.end = end } } public func ==(lhs: S2Edge, rhs: S2Edge) -> Bool { return lhs.start == rhs.start && lhs.end == rhs.end }
mit
26352185f07de9534f499652b513db39
17.884615
63
0.663951
2.83815
false
false
false
false
rxwei/CoreTensor
Sources/RankedTensor/Shape.swift
1
1825
// // Shape.swift // RankedTensor // // Copyright 2016-2017 DLVM Team. // // 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. // public typealias Shape1D = (UInt) public typealias Shape2D = (UInt, UInt) public typealias Shape3D = (UInt, UInt, UInt) public typealias Shape4D = (UInt, UInt, UInt, UInt) internal func arrayToShape1D(_ array: [Int]) -> Shape1D { var array = array return withUnsafePointer(to: &array[0]) { ptr in ptr.withMemoryRebound(to: Shape1D.self, capacity: 1) { ptr in return ptr.pointee } } } internal func arrayToShape2D(_ array: [Int]) -> Shape2D { var array = array return withUnsafePointer(to: &array[0]) { ptr in ptr.withMemoryRebound(to: Shape2D.self, capacity: 1) { ptr in return ptr.pointee } } } internal func arrayToShape3D(_ array: [Int]) -> Shape3D { var array = array return withUnsafePointer(to: &array[0]) { ptr in ptr.withMemoryRebound(to: Shape3D.self, capacity: 1) { ptr in return ptr.pointee } } } internal func arrayToShape4D(_ array: [Int]) -> Shape4D { var array = array return withUnsafePointer(to: &array[0]) { ptr in ptr.withMemoryRebound(to: Shape4D.self, capacity: 1) { ptr in return ptr.pointee } } }
apache-2.0
bc29e8f29974ae04ef8936db67ddc4f3
29.932203
76
0.659178
3.672032
false
false
false
false
ZekeSnider/Jared
Jared/MessageRequest.swift
1
1659
// // MessageRequest.swift // Jared // // Created by Zeke Snider on 12/28/19. // Copyright © 2019 Zeke Snider. All rights reserved. // import Foundation import JaredFramework // Struct that defines what parameters are accepted in requests public struct MessageRequest: Decodable { public var body: MessageBody? public var recipient: RecipientEntity public var attachments: [Attachment]? enum CodingKeys : String, CodingKey { case body case recipient case attachments } enum ParameterError: Error { case runtimeError(String) } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.attachments = try? container.decode([Attachment].self, forKey: .attachments) self.body = try? container.decode(TextBody.self, forKey: .body) if let person = try? container.decode(Person.self, forKey: .recipient) { self.recipient = person } else if let group = try? container.decode(Group.self, forKey: .recipient) { self.recipient = group } else if let abstractRecipient = try? container.decode(AbstractRecipient.self, forKey: .recipient) { self.recipient = abstractRecipient } else { throw ParameterError.runtimeError("the recipient parameter is incorrectly formatted") } // One of attachments or body must not be nil guard (attachments != nil || body != nil) else { throw ParameterError.runtimeError("the body parameter is incorrectly formatted") } } }
apache-2.0
194551d539b688d9893655097b68ff32
32.836735
109
0.649578
4.657303
false
false
false
false
PD-Jell/Swift_study
SwiftStudy/UIKIt/UIKitViewController.swift
1
1596
// // UIKitViewController.swift // SwiftStudy // // Created by dongwoo on 9/2/21. // Copyright © 2021 Jell PD. All rights reserved. // import UIKit class UIKitViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet var collectionView: UICollectionView! var menuArray: NSArray = [] override func viewDidLoad() { super.viewDidLoad() print("hi") menuArray = NSArray.init(object: "Rounded Popup") } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let mainCollectionViewCell : UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ui_main_collection_view_cell", for: indexPath) let label : UILabel = mainCollectionViewCell.viewWithTag(2) as! UILabel; label.text = (menuArray.object(at: indexPath.row) as! String); return mainCollectionViewCell; } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return menuArray.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { switch(indexPath.row) { case 0: let vc = self.storyboard?.instantiateViewController(identifier: "ui_popup_round") as! UIPopupRoundViewController vc.modalPresentationStyle = .overCurrentContext present(vc, animated: false, completion: nil) default: return } } }
mit
190d7aa93e2a33ea3f5bb5ee175b73c1
33.673913
163
0.684639
5.246711
false
false
false
false
LeLuckyVint/MessageKit
Sources/Views/Cells/MessageCollectionViewCell.swift
1
6738
/* MIT License Copyright (c) 2017 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit open class MessageCollectionViewCell<ContentView: UIView>: UICollectionViewCell, CollectionViewReusable { open class func reuseIdentifier() -> String { return "messagekit.cell.base-cell" } // MARK: - Properties open var messageContainerView: MessageContainerView = { let messageContainerView = MessageContainerView() messageContainerView.clipsToBounds = true messageContainerView.layer.masksToBounds = true return messageContainerView }() open var avatarView: AvatarView = AvatarView() open var cellTopLabel: MessageLabel = { let topLabel = MessageLabel() topLabel.enabledDetectors = [] return topLabel }() open var messageContentView: ContentView = { let contentView = ContentView() contentView.clipsToBounds = true contentView.isUserInteractionEnabled = true return contentView }() open var cellBottomLabel: MessageLabel = { let bottomLabel = MessageLabel() bottomLabel.enabledDetectors = [] return bottomLabel }() open weak var delegate: MessageCellDelegate? var messageTapGesture: UITapGestureRecognizer? // MARK: - Initializer public override init(frame: CGRect) { super.init(frame: frame) setupSubviews() setupGestureRecognizers() contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Methods internal func setupSubviews() { contentView.addSubview(cellTopLabel) contentView.addSubview(messageContainerView) messageContainerView.addSubview(messageContentView) contentView.addSubview(avatarView) contentView.addSubview(cellBottomLabel) } open override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) guard let attributes = layoutAttributes as? MessagesCollectionViewLayoutAttributes else { return } avatarView.frame = attributes.avatarFrame messageContainerView.frame = attributes.messageContainerFrame messageContentView.frame = messageContainerView.bounds cellTopLabel.frame = attributes.cellTopLabelFrame cellTopLabel.textInsets = attributes.cellTopLabelInsets cellBottomLabel.frame = attributes.cellBottomLabelFrame cellBottomLabel.textInsets = attributes.cellBottomLabelInsets } open override func prepareForReuse() { cellTopLabel.text = nil cellTopLabel.attributedText = nil cellBottomLabel.text = nil cellBottomLabel.attributedText = nil } open func configure(with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) { // Check if delegate has already been set to reduce number of assignments if delegate == nil, let cellDelegate = messagesCollectionView.messageCellDelegate { delegate = cellDelegate } if let displayDelegate = messagesCollectionView.messagesDisplayDelegate { let messageColor = displayDelegate.backgroundColor(for: message, at: indexPath, in: messagesCollectionView) let messageStyle = displayDelegate.messageStyle(for: message, at: indexPath, in: messagesCollectionView) messageContainerView.backgroundColor = messageColor messageContainerView.style = messageStyle } // Make sure we set all data source properties after configuring display delegate properties // The MessageLabel class probably has a stateful issue if let dataSource = messagesCollectionView.messagesDataSource { let avatar = dataSource.avatar(for: message, at: indexPath, in: messagesCollectionView) let topLabelText = dataSource.cellTopLabelAttributedText(for: message, at: indexPath) let bottomLabelText = dataSource.cellBottomLabelAttributedText(for: message, at: indexPath) avatarView.set(avatar: avatar) cellTopLabel.attributedText = topLabelText cellBottomLabel.attributedText = bottomLabelText } } func setupGestureRecognizers() { let avatarTapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapAvatar)) avatarView.addGestureRecognizer(avatarTapGesture) avatarView.isUserInteractionEnabled = true let messageTapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapMessage)) messageContainerView.addGestureRecognizer(messageTapGesture) messageContainerView.isUserInteractionEnabled = true self.messageTapGesture = messageTapGesture let topLabelTapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapTopLabel)) cellTopLabel.addGestureRecognizer(topLabelTapGesture) cellTopLabel.isUserInteractionEnabled = true let bottomlabelTapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapBottomLabel)) cellBottomLabel.addGestureRecognizer(bottomlabelTapGesture) cellBottomLabel.isUserInteractionEnabled = true } // MARK: - Delegate Methods @objc func didTapAvatar() { delegate?.didTapAvatar(in: self) } @objc func didTapMessage() { delegate?.didTapMessage(in: self) } @objc func didTapTopLabel() { delegate?.didTapTopLabel(in: self) } @objc func didTapBottomLabel() { delegate?.didTapBottomLabel(in: self) } }
mit
dbacf806b9bd4ddd07ebf58882ade081
35.619565
129
0.723063
5.671717
false
false
false
false
DannyvanSwieten/SwiftSignals
Gui/Window.swift
1
935
// // Window.swift // SwiftAudio // // Created by Danny van Swieten on 1/12/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import AppKit enum GraphicsBackEnd { case Metal case OpenGl case CoreGraphics } class Window { var window: NSWindow? var mainContentView = MainContentView() var metal: MetalViewController? init(title: String, xPos: CGFloat, yPos: CGFloat, width: CGFloat, height: CGFloat) { let rect = CGRectMake(xPos, yPos, width, height) window = NSWindow(contentRect: rect, styleMask: NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask, backing: NSBackingStoreType.Buffered, `defer`: false) window!.title = title metal = MetalViewController() window!.contentView? = metal!.view } func addMainContentView(content: Widget) { mainContentView.content = content } }
gpl-3.0
2f64fcbeadf17791fd47b9a09d7f8cb0
24.243243
181
0.668094
4.226244
false
false
false
false
JQHee/JQProgressHUD
Source/JQProgressHUDTool.swift
2
4917
// // JQProgressHUDTool.swift // JQProgressHUD // // Created by HJQ on 2017/7/1. // Copyright © 2017年 HJQ. All rights reserved. // import UIKit open class JQProgressHUDTool: NSObject { @discardableResult public class func jq_showNormalHUD(view: UIView? = UIApplication.shared.windows.last, msg: String? = "", isNeedmask: Bool? = false, isUserInteractionEnabled: Bool? = false, animation: Bool? = false) -> JQProgressHUD { let hud: JQProgressHUD = JQProgressHUD.showHUD(addTo: view!, animation: animation) hud.isNeedMask = isNeedmask! hud.detailLabel.text = msg! let activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView(style: .white) activityIndicatorView.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) activityIndicatorView.startAnimating() hud.indicatorView = activityIndicatorView hud.isUserInteractionEnabled = isUserInteractionEnabled! return hud } @discardableResult public class func jq_showCustomHUD(view: UIView? = UIApplication.shared.windows.last, msg: String? = "", isNeedmask: Bool? = false, isUserInteractionEnabled: Bool? = false, animation: Bool? = false) -> JQProgressHUD { let hud: JQProgressHUD = JQProgressHUD.showHUD(addTo: view!, animation: animation!) hud.isNeedMask = isNeedmask! hud.detailLabel.text = msg! let indicatorView: JQIndicatorView = JQIndicatorView.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30)) indicatorView.color = UIColor.white hud.indicatorView = indicatorView hud.isUserInteractionEnabled = isUserInteractionEnabled! return hud } @discardableResult public class func jq_showCircularHUD(view: UIView? = UIApplication.shared.windows.last, msg: String? = "",progress: CGFloat? = 0, isNeedmask: Bool? = false, isUserInteractionEnabled: Bool? = false, animation: Bool? = false) -> JQProgressHUD { var hud: JQProgressHUD hud = JQProgressHUD.showHUD(addTo: view!, animation: animation!) hud.isNeedMask = isNeedmask! hud.detailLabel.text = msg! let circularindicator = JQCircularIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) circularindicator.annularColor = UIColor.white circularindicator.textSize = 8 circularindicator.progress = progress! hud.indicatorView = circularindicator hud.isUserInteractionEnabled = isUserInteractionEnabled! return hud } @discardableResult public class func jq_showOvalHUD(view: UIView? = UIApplication.shared.windows.last, msg: String? = "", isNeedmask: Bool? = false, isUserInteractionEnabled: Bool? = false, animation: Bool? = false) -> JQProgressHUD { var hud: JQProgressHUD hud = JQProgressHUD.showHUD(addTo: view!, animation: animation!) hud.isNeedMask = isNeedmask! hud.detailLabel.text = msg! let indicatorView = JQOvalIndicatorView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) indicatorView.color = UIColor.white hud.indicatorView = indicatorView hud.isIndicatorViewLeft = true hud.containerViewSize = CGSize.init(width: 120, height: 35) hud.isUserInteractionEnabled = isUserInteractionEnabled! return hud } @discardableResult public class func jq_showImageHUD(view: UIView? = UIApplication.shared.windows.last, msg: String? = "",imageName: String? = "", isNeedmask: Bool? = false, isUserInteractionEnabled: Bool? = false, animation: Bool? = false) -> JQProgressHUD { let hud: JQProgressHUD = JQProgressHUD.showHUD(addTo: view!) hud.isNeedMask = isNeedmask! hud.detailLabel.text = msg! hud.duration = 3.0 let imageView: UIImageView = UIImageView.init() imageView.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) imageView.contentMode = UIView.ContentMode.center imageView.image = UIImage.init(named: imageName ?? "") hud.indicatorView = imageView hud.containerViewBGcolor = UIColor.orange hud.isUserInteractionEnabled = isUserInteractionEnabled! return hud } @discardableResult public class func jq_showToastHUD(view: UIView? = UIApplication.shared.windows.last, msg: String? = "",duration: TimeInterval? = 3.0, isUserInteractionEnabled: Bool? = false, animation: Bool? = false) -> JQProgressHUD { let hud: JQProgressHUD = JQProgressHUD.showToastHUD(addTo: view!, animation: animation!) hud.duration = duration! hud.toastLabel.text = msg hud.isUserInteractionEnabled = isUserInteractionEnabled! return hud } public class func jq_hideHUD(view: UIView? = UIApplication.shared.windows.last) { let _ = JQProgressHUD.hideHUD(fromView: view!) } }
apache-2.0
24c73184d17d4551be0fda49c1d2ba65
46.708738
246
0.678877
4.562674
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/Supporting Files/UIComponents/TypingIndicator/TypingIndicator.swift
1
5928
/* MIT License Copyright (c) 2017-2018 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit /// A `UIView` subclass that holds 3 dots which can be animated open class TypingIndicator: UIView { // MARK: - Properties /// The offset that each dot will transform by during the bounce animation open var bounceOffset: CGFloat = 2.5 /// A convenience accessor for the `backgroundColor` of each dot open var dotColor: UIColor = UIColor.lightGray { didSet { dots.forEach { $0.backgroundColor = dotColor } } } /// A flag that determines if the bounce animation is added in `startAnimating()` open var isBounceEnabled: Bool = false /// A flag that determines if the opacity animation is added in `startAnimating()` open var isFadeEnabled: Bool = true /// A flag indicating the animation state public private(set) var isAnimating: Bool = false /// Keys for each animation layer private struct AnimationKeys { static let offset = "typingIndicator.offset" static let bounce = "typingIndicator.bounce" static let opacity = "typingIndicator.opacity" } /// The `CABasicAnimation` applied when `isBounceEnabled` is TRUE to move the dot to the correct /// initial offset open var initialOffsetAnimationLayer: CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform.translation.y") animation.byValue = -bounceOffset animation.duration = 0.5 animation.isRemovedOnCompletion = true return animation } /// The `CABasicAnimation` applied when `isBounceEnabled` is TRUE open var bounceAnimationLayer: CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform.translation.y") animation.toValue = -bounceOffset animation.fromValue = bounceOffset animation.duration = 0.5 animation.repeatCount = .infinity animation.autoreverses = true return animation } /// The `CABasicAnimation` applied when `isFadeEnabled` is TRUE open var opacityAnimationLayer: CABasicAnimation { let animation = CABasicAnimation(keyPath: "opacity") animation.fromValue = 1 animation.toValue = 0.5 animation.duration = 0.5 animation.repeatCount = .infinity animation.autoreverses = true return animation } // MARK: - Subviews public let stackView = UIStackView() public let dots: [BubbleCircle] = { return [BubbleCircle(), BubbleCircle(), BubbleCircle()] }() // MARK: - Initialization public override init(frame: CGRect) { super.init(frame: frame) setupView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } /// Sets up the view private func setupView() { dots.forEach { $0.backgroundColor = dotColor $0.heightAnchor.constraint(equalTo: $0.widthAnchor).isActive = true stackView.addArrangedSubview($0) } stackView.axis = .horizontal stackView.alignment = .center stackView.distribution = .fillEqually addSubview(stackView) } // MARK: - Layout open override func layoutSubviews() { super.layoutSubviews() stackView.frame = bounds stackView.spacing = bounds.width > 0 ? 5 : 0 } // MARK: - Animation API /// Sets the state of the `TypingIndicator` to animating and applies animation layers open func startAnimating() { defer { isAnimating = true } guard !isAnimating else { return } var delay: TimeInterval = 0 for dot in dots { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in guard let `self` = self else { return } if self.isBounceEnabled { dot.layer.add(self.initialOffsetAnimationLayer, forKey: AnimationKeys.offset) let bounceLayer = self.bounceAnimationLayer bounceLayer.timeOffset = delay + 0.33 dot.layer.add(bounceLayer, forKey: AnimationKeys.bounce) } if self.isFadeEnabled { dot.layer.add(self.opacityAnimationLayer, forKey: AnimationKeys.opacity) } } delay += 0.33 } } /// Sets the state of the `TypingIndicator` to not animating and removes animation layers open func stopAnimating() { defer { isAnimating = false } guard isAnimating else { return } dots.forEach { $0.layer.removeAnimation(forKey: AnimationKeys.bounce) $0.layer.removeAnimation(forKey: AnimationKeys.opacity) } } }
gpl-3.0
967b8d3eefea450ab61434acc74c2a22
34.927273
100
0.649291
5.079692
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/BluetoothBridge.swift
1
3478
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for Bluetooth purposes Auto-generated implementation of IBluetooth specification. */ public class BluetoothBridge : BaseCommunicationBridge, IBluetooth, APIBridge { /** API Delegate. */ private var delegate : IBluetooth? = nil /** Constructor with delegate. @param delegate The delegate implementing platform specific functions. */ public init(delegate : IBluetooth?) { self.delegate = delegate } /** Get the delegate implementation. @return IBluetooth delegate that manages platform specific functions.. */ public final func getDelegate() -> IBluetooth? { return self.delegate } /** Set the delegate implementation. @param delegate The delegate implementing platform specific functions. */ public final func setDelegate(delegate : IBluetooth) { self.delegate = delegate; } /** Invokes the given method specified in the API request object. @param request APIRequest object containing method name and parameters. @return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions. */ public override func invoke(request : APIRequest) -> APIResponse? { let response : APIResponse = APIResponse() var responseCode : Int32 = 200 var responseMessage : String = "OK" let responseJSON : String? = "null" switch request.getMethodName()! { default: // 404 - response null. responseCode = 404 responseMessage = "BluetoothBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15." } response.setResponse(responseJSON!) response.setStatusCode(responseCode) response.setStatusMessage(responseMessage) return response } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
3968a98e0d0091df6d8b553f2ee0834a
34.835052
188
0.624856
5.172619
false
false
false
false
brentsimmons/Evergreen
Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift
1
869
// // SidebarCellAppearance.swift // NetNewsWire // // Created by Brent Simmons on 11/24/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import AppKit struct SidebarCellAppearance: Equatable { let imageSize: CGSize let imageMarginRight: CGFloat = 4.0 let unreadCountMarginLeft: CGFloat = 10.0 let textFieldFontSize: CGFloat let textFieldFont: NSFont init(rowSizeStyle: NSTableView.RowSizeStyle) { switch rowSizeStyle { case .small: imageSize = CGSize(width: 16, height: 16) textFieldFontSize = 11 case .large: imageSize = CGSize(width: 22, height: 22) if #available(macOS 11.0, *) { textFieldFontSize = 15 } else { textFieldFontSize = 13 } default: imageSize = CGSize(width: 19, height: 19) textFieldFontSize = 13 } self.textFieldFont = NSFont.systemFont(ofSize: textFieldFontSize) } }
mit
4e9ff81d79bd277bcdc0426b6b887eb7
21.25641
67
0.709677
3.528455
false
false
false
false
cuappdev/tcat-ios
TCAT/Cells/FavoritesCollectionViewCell.swift
1
1845
// // FavoritesCollectionViewCell.swift // TCAT // // Created by Lucy Xu on 11/4/19. // Copyright © 2019 cuappdev. All rights reserved. // import UIKit class FavoritesCollectionViewCell: UICollectionViewCell { private let heartImageView = UIImageView() private let nameLabel = UILabel() private let minusImageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) nameLabel.font = .systemFont(ofSize: 12, weight: .regular) nameLabel.textColor = .black nameLabel.textAlignment = .center nameLabel.numberOfLines = 2 nameLabel.lineBreakMode = .byTruncatingTail contentView.addSubview(nameLabel) contentView.addSubview(heartImageView) minusImageView.image = UIImage(named: "minus") contentView.addSubview(minusImageView) setupConstraints() } private func setupConstraints() { heartImageView.snp.makeConstraints { make in make.centerX.top.equalToSuperview() make.size.equalTo(56) } minusImageView.snp.makeConstraints { make in make.centerX.equalTo(heartImageView).offset(24) make.centerY.equalTo(heartImageView).offset(-16) make.size.equalTo(22) } nameLabel.snp.makeConstraints { make in make.left.right.equalToSuperview() make.top.equalTo(heartImageView.snp.bottom).offset(11) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(for place: Place, isEditing: Bool) { nameLabel.text = place.name let heartImage = isEditing ? "fadedHeart" : "blueHeart" heartImageView.image = UIImage(named: heartImage) minusImageView.isHidden = !isEditing } }
mit
2b7905e060193d43a5dedf5615a0fb61
27.8125
66
0.653471
4.633166
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Models/CommonModel.swift
1
4091
// // CommonModel.swift // ifanr // // Created by sys on 16/7/28. // Copyright © 2016年 ifanrOrg. All rights reserved. // import Foundation /** * 作者信息 */ struct AuthorInfoModel { var job: String! var name: String! var avatar: String! var description: String! init(dict: NSDictionary) { self.job = dict["job"] as? String ?? "" self.name = dict["name"] as? String ?? "" self.avatar = dict["avatar"] as? String ?? "" self.description = dict["description"] as? String ?? "" } } /** 发布类型: 在计算cell高度是需要分类进行计算(目前只发现这几种) */ enum PostType { case post case data case dasheng } /*! * @brief 通用的数据模型 */ struct CommonModel: Initable { /// id var ID: String! /// 标题 var title: String! /// 作者 var author: String! /// 时间 var pubDate: String! /// 发布时间 var post_modified: String! /// 图片 var image: String! /// cwb_image_url var cwb_image_url: String! /// 内容 var content: String! /// 摘录 var excerpt: String! /// 引文 var introduce: String! /// 网页版 var link: String! /// 评论数 var comments: String! /// 分类 var category: String! /// 分类网页 var category_link: String! /// tag var tags: String! /// 喜欢数 var like: Int! var is_ad: Int! /// 作者信息 var authorInfoModel: AuthorInfoModel! /// 发布类型 var post_type: PostType! = .post //MARK: --------------------------- Home -------------------------- /// 大声作者 var dasheng_author: String! = "" /// 数读 var number: String! = "" var subfix: String! = "" //MARK: --------------------------- AppSo -------------------------- var app_icon_url: String! init(dict: NSDictionary) { initCommonData(dict) initHomeData(dict) initAppSoData(dict) } } extension CommonModel { mutating func initCommonData(_ dict: NSDictionary) { let idStr: NSInteger = dict["ID"] as? NSInteger ?? 0 self.ID = "\(idStr)" self.title = dict["title"] as? String ?? "" self.author = dict["author"] as? String ?? "" self.pubDate = dict["pubDate"] as? String ?? "" self.post_modified = dict["post_modified"] as? String ?? "" self.image = dict["image"] as? String ?? "" self.cwb_image_url = dict["cwb_image_url"] as? String ?? "" self.content = dict["content"] as? String ?? "" self.excerpt = dict["excerpt"] as? String ?? "" self.introduce = dict["introduce"] as? String ?? "" self.link = dict["link"] as? String ?? "" self.comments = dict["comments"] as? String ?? "" self.category = dict["category"] as? String ?? "" self.category_link = dict["category_link"] as? String ?? "" self.tags = dict["tags"] as? String ?? "" self.like = dict["like"] as? Int ?? 0 self.is_ad = dict["is_ad"] as? Int ?? 0 if let item: NSDictionary = (dict["author_info"] as? NSDictionary) { self.authorInfoModel = AuthorInfoModel(dict: item) } } mutating func initHomeData(_ dict: NSDictionary) { if let type = dict["post_type"] as? String { if type == "post" { self.post_type = .post } else if type == "dasheng" { self.post_type = .dasheng self.dasheng_author = dict["dasheng_author"] as? String ?? "" self.category = "大声" } else if type == "data" { self.post_type = .data self.category = "数读" self.number = dict["number"] as? String ?? "" self.subfix = dict["subfix"] as? String ?? "" } } } mutating func initAppSoData(_ dict: NSDictionary) { self.app_icon_url = dict["app_icon_url"] as? String ?? "" } }
mit
5320a4a60f40c22b54beb4cc928e9d01
26.125
77
0.511777
3.730659
false
false
false
false
grpc/grpc-swift
Sources/Examples/HelloWorld/Client/HelloWorldClient.swift
1
2271
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if compiler(>=5.6) import ArgumentParser import GRPC import HelloWorldModel import NIOCore import NIOPosix @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @main struct HelloWorld: AsyncParsableCommand { @Option(help: "The port to connect to") var port: Int = 1234 @Argument(help: "The name to greet") var name: String? func run() async throws { // Setup an `EventLoopGroup` for the connection to run on. // // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) // Make sure the group is shutdown when we're done with it. defer { try! group.syncShutdownGracefully() } // Configure the channel, we're not using TLS so the connection is `insecure`. let channel = try GRPCChannelPool.with( target: .host("localhost", port: self.port), transportSecurity: .plaintext, eventLoopGroup: group ) // Close the connection when we're done with it. defer { try! channel.close().wait() } // Provide the connection to the generated client. let greeter = Helloworld_GreeterAsyncClient(channel: channel) // Form the request with the name, if one was provided. let request = Helloworld_HelloRequest.with { $0.name = self.name ?? "" } do { let greeting = try await greeter.sayHello(request) print("Greeter received: \(greeting.message)") } catch { print("Greeter failed: \(error)") } } } #else @main enum HelloWorld { static func main() { fatalError("This example requires swift >= 5.6") } } #endif // compiler(>=5.6)
apache-2.0
a6add4b5b8d5d332158e259c20b308f8
28.115385
82
0.685601
4.055357
false
false
false
false
austinzheng/swift
test/expr/cast/as_coerce.swift
9
3934
// RUN: %target-typecheck-verify-swift -enable-objc-interop // Test the use of 'as' for type coercion (which requires no checking). @objc protocol P1 { func foo() } class A : P1 { @objc func foo() { } } @objc class B : A { func bar() { } } func doFoo() {} func test_coercion(_ a: A, b: B) { // Coercion to a protocol type let x = a as P1 x.foo() // Coercion to a superclass type let y = b as A y.foo() } class C : B { } class D : C { } func prefer_coercion(_ c: inout C) { let d = c as! D c = d } // Coerce literals var i32 = 1 as Int32 var i8 = -1 as Int8 // Coerce to a superclass with generic parameter inference class C1<T> { func f(_ x: T) { } } class C2<T> : C1<Int> { } var c2 = C2<()>() var c1 = c2 as C1 c1.f(5) @objc protocol P {} class CC : P {} let cc: Any = CC() if cc is P { doFoo() } if let p = cc as? P { doFoo() _ = p } // Test that 'as?' coercion fails. let strImplicitOpt: String! = nil _ = strImplicitOpt as? String // expected-warning{{conditional downcast from 'String?' to 'String' does nothing}}{{19-30=}} class C3 {} class C4 : C3 {} class C5 {} var c: AnyObject = C3() if let castX = c as! C4? {} // expected-error {{cannot downcast from 'AnyObject' to a more optional type 'C4?'}} // Only suggest replacing 'as' with 'as!' if it would fix the error. C3() as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{6-8=as!}} C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}} // Diagnostic shouldn't include @lvalue in type of c3. var c3 = C3() c3 as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{4-6=as!}} // <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions 1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}} 1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} ["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}} ([1, 2, 1.0], 1) as ([String], Int) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} [[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} (1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type 'Double' to type 'Int' in coercion}} (1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} (1, 1.0, "a", [1, 23]) as (Int, Double, String, [String]) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} _ = [1] as! [String] // expected-warning{{cast from '[Int]' to unrelated type '[String]' always fails}} _ = [(1, (1, 1))] as! [(Int, (String, Int))] // expected-warning{{cast from '[(Int, (Int, Int))]' to unrelated type '[(Int, (String, Int))]' always fails}} // <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type _ = "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{13-24=}} // <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its func f(_ x : String) {} f("what" as Any as String) // expected-error {{'Any' is not convertible to 'String'; did you mean to use 'as!' to force downcast?}} {{17-19=as!}} f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} // <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests let s : AnyObject = C3() s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'; did you mean to use 'as!' to force downcast?}} {{3-5=as!}}
apache-2.0
64732db464bdabc31bf4fcde8e150dab
36.466667
155
0.655567
3.157303
false
false
false
false
sjtu-meow/iOS
Meow/SearchViewController.swift
1
3158
// // SearchViewController.swift // Meow // // Created by 林树子 on 2017/7/4. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit import TagListView class NoCancelButtonSearchBar: UISearchBar { override func setShowsCancelButton(_ showsCancelButton: Bool, animated: Bool) { super.setShowsCancelButton(false, animated: false); } } class NoCancelButtonSearchController: UISearchController { private let noCancelButtonSearchBar = NoCancelButtonSearchBar() override var searchBar: UISearchBar { return noCancelButtonSearchBar } } class SearchViewController: UIViewController { var searchController: NoCancelButtonSearchController! @IBOutlet weak var historyTagListView: TagListView! @IBAction func clearHistory(_ sender: Any) { SearchHistorySource.clearHistory() updateTags() } override func viewDidLoad() { super.viewDidLoad() searchController = NoCancelButtonSearchController() searchController.searchBar.delegate = self searchController.hidesNavigationBarDuringPresentation = false searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.placeholder = "搜索.." searchController.searchBar.showsCancelButton = false self.navigationItem.titleView = searchController.searchBar self.definesPresentationContext = true searchController.definesPresentationContext = true historyTagListView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated); //searchController.isActive = true; var result = searchController.searchBar.becomeFirstResponder() updateTags() } } // //extension SearchViewController: UISearchControllerDelegate { // func didPresentSearchController(searchController: UISearchController) { // searchController.searchBar.becomeFirstResponder() // } //} extension SearchViewController { func addTags(_ tags: Set<String>) { for tag in tags { historyTagListView.addTag(tag) } } func updateTags() { let history = SearchHistorySource.getHistory() historyTagListView.removeAllTags() addTags(history) } } extension SearchViewController: TagListViewDelegate { func tagPressed(_ title: String, tagView: TagView, sender: TagListView) { searchController.searchBar.text = title searchController.searchBar.becomeFirstResponder() } } extension SearchViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let queryKeyword = searchController.searchBar.text else { return } SearchHistorySource.addHistory(historyEntry: queryKeyword) let vc = R.storyboard.main.searchResultViewController()! vc.configure(keyword: queryKeyword) // TODO self.navigationController?.pushViewController(vc, animated: true) } }
apache-2.0
166e9628aa616d325990dce67c55009d
26.973214
83
0.688477
5.574733
false
false
false
false
unsignedapps/FileSelectionController
FileSelectionController/FileSelectionView.swift
1
1273
// // FileSelectionView.swift // FileSelectionController // // Created by Robert Amos on 10/11/2015. // Copyright © 2015 Unsigned Apps. All rights reserved. // import UIKit class FileSelectionView: UIView { fileprivate var didLoadInitialConstraints = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.translatesAutoresizingMaskIntoConstraints = false } override func updateConstraints() { super.updateConstraints(); if !self.didLoadInitialConstraints { self.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": self])) self.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view]|", options: [], metrics: nil, views: ["view": self])) self.didLoadInitialConstraints = true; } } } @IBDesignable extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 layer.allowsEdgeAntialiasing = newValue > 0 } } }
mit
13a4563f7f6db19af877d0c13fb60652
27.266667
156
0.637579
5.007874
false
false
false
false
mflint/ios-tldr-viewer
tldr-viewer/Platform.swift
1
1599
// // CommandPlatform.swift // tldr-viewer // // Created by Matthew Flint on 01/01/2016. // Copyright © 2016 Green Light. All rights reserved. // import Foundation struct Platform: Codable { var name: String var displayName: String var sortOrder: Int private static var platforms = [ "common": Platform(name: "common", displayName: Localizations.CommandList.CommandPlatform.Common, sortOrder: 0), "osx": Platform(name: "osx", displayName: Localizations.CommandList.CommandPlatform.Osx, sortOrder: 1), "linux": Platform(name: "linux", displayName: Localizations.CommandList.CommandPlatform.Linux, sortOrder: 2), "sunos": Platform(name: "sunos", displayName: Localizations.CommandList.CommandPlatform.Solaris, sortOrder: 3), "windows": Platform(name: "windows", displayName: Localizations.CommandList.CommandPlatform.Windows, sortOrder: 4) ] private init(name: String, displayName: String, sortOrder: Int) { self.name = name self.displayName = displayName self.sortOrder = sortOrder } static func get(name: String) -> Platform { var platform = Platform.platforms[name] if (platform == nil) { platform = platforms[name, default: Platform(name: name, displayName: name.capitalized, sortOrder: platforms.count)] Platform.platforms[name] = platform } return platform! } } extension Platform: Comparable { static func < (lhs: Platform, rhs: Platform) -> Bool { return lhs.sortOrder < rhs.sortOrder } }
mit
76e2ea9c8498aced4cbc87938ae3befb
34.511111
128
0.667084
4.307278
false
false
false
false
muukii/DataSources
Sources/DataSourcesDemo/SingleSectionCollectionViewController.swift
1
3191
// // CollectionViewController.swift // DataSourcesDemo // // Created by muukii on 8/8/17. // Copyright © 2017 muukii. All rights reserved. // import UIKit import DataSources import EasyPeasy import RxSwift import RxCocoa final class SingleSectionCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.sectionInset = .zero layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.register(Cell.self, forCellWithReuseIdentifier: "Cell") collectionView.backgroundColor = .white return collectionView }() private lazy var dataSource: SectionDataController<ModelA, CollectionViewAdapter> = .init( adapter: .init(collectionView: self.collectionView), displayingSection: 0 ) private let add = UIBarButtonItem(title: "Add", style: .plain, target: nil, action: nil) private let remove = UIBarButtonItem(title: "Remove", style: .plain, target: nil, action: nil) private let addRemove = UIBarButtonItem(title: "AddRemove", style: .plain, target: nil, action: nil) private let shuffle = UIBarButtonItem(title: "Shuffle", style: .plain, target: nil, action: nil) private let viewModel = ViewModel() private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) collectionView <- Edges() navigationItem.rightBarButtonItems = [add, remove, addRemove, shuffle] add.rx.tap .bind(onNext: viewModel.add) .disposed(by: disposeBag) remove.rx.tap .bind(onNext: viewModel.remove) .disposed(by: disposeBag) addRemove.rx.tap .bind(onNext: viewModel.addRemove) .disposed(by: disposeBag) shuffle.rx.tap .bind(onNext: viewModel.shuffle) .disposed(by: disposeBag) collectionView.delegate = self collectionView.dataSource = self viewModel.section0 .asDriver() .drive(onNext: { [weak self] items in print("Begin update") self?.dataSource.update(items: items, updateMode: .partial(animated: true), completion: { print("Throttled Complete") }) }) .disposed(by: disposeBag) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.numberOfItems() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell let m = dataSource.item(at: indexPath)! cell.label.text = m.title return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width / 6, height: 50) } }
mit
9bd25e341f21689cb3b6d68f3d1e3b19
30.584158
158
0.722884
4.768311
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableViewDataSources/TodoTableViewDataSource.swift
1
2008
// // TodoTableViewDataSource.swift // Habitica // // Created by Phillip Thelen on 07.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class TodoTableViewDataSource: TaskTableViewDataSource { let dateFormatter = DateFormatter() init(predicate: NSPredicate) { super.init(predicate: predicate, taskType: TaskType.todo) dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none } override func configure(cell: TaskTableViewCell, indexPath: IndexPath, task: TaskProtocol) { if let todocell = cell as? ToDoTableViewCell { todocell.taskDetailLine.dateFormatter = dateFormatter todocell.checkboxTouched = {[weak self] in if !task.isValid { return } self?.scoreTask(task: task, direction: task.completed ? .down : .up, soundEffect: .todoCompleted) } todocell.checklistItemTouched = {[weak self] checklistItem in if !task.isValid { return } self?.disposable.add(self?.repository.score(checklistItem: checklistItem, task: task).observeCompleted {}) } todocell.checklistIndicatorTouched = {[weak self] in if !task.isValid { return } self?.expandSelectedCell(indexPath: indexPath) } } super.configure(cell: cell, indexPath: indexPath, task: task) } override func predicates(filterType: Int) -> [NSPredicate] { var predicates = super.predicates(filterType: filterType) switch filterType { case 0: predicates.append(NSPredicate(format: "completed == false")) case 1: predicates.append(NSPredicate(format: "completed == false && duedate != nil")) case 2: predicates.append(NSPredicate(format: "completed == true")) default: break } return predicates } }
gpl-3.0
10c12de127236688f88efff203210fa2
34.839286
122
0.618834
4.895122
false
false
false
false
overtake/TelegramSwift
packages/TGUIKit/Sources/ImageButton.swift
1
8175
// // ImageButton.swift // TGUIKit // // Created by keepcoder on 26/09/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa public enum ButtonHoverPolicy { case none case enlarge(value: CGFloat) } public enum ButtonBackgroundCornerRadius { case none case appSpecific case half } public enum ImageButtonAnimationPolicy { case animateContents case replaceScale } open class ImageButton: Button { internal private(set) var imageView:ImageView = ImageView() internal let additionBackgroundView: View = View() private var additionStateBackground:[ControlState:NSColor] = [:] private var cornerRadius:[ControlState : ButtonBackgroundCornerRadius] = [:] private var hoverAdditionPolicy:[ControlState : ButtonHoverPolicy] = [:] private var additionBackgroundMultiplier:[ControlState: CGFloat] = [:] private var images:[ControlState:CGImage] = [:] private var backgroundImage:[ControlState:CGImage] = [:] public func removeImage(for state:ControlState) { images.removeValue(forKey: state) apply(state: self.controlState) } public func setImageContentGravity(_ gravity: CALayerContentsGravity) { imageView.contentGravity = gravity } public func set(image:CGImage, for state:ControlState) -> Void { if images[state] != image { images[state] = image apply(state: self.controlState) } } open override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties() } override func prepare() { super.prepare() imageView.animates = true additionBackgroundView.isEventLess = true // imageView.isEventLess = true self.addSubview(additionBackgroundView) self.addSubview(imageView) } public func set(additionBackgroundColor:NSColor, for state:ControlState) -> Void { additionStateBackground[state] = additionBackgroundColor apply(state: self.controlState) } public func set(additionBackgroundMultiplier: CGFloat, for state:ControlState) -> Void { self.additionBackgroundMultiplier[state] = additionBackgroundMultiplier apply(state: self.controlState) } public func set(cornerRadius: ButtonBackgroundCornerRadius, for state:ControlState) -> Void { self.cornerRadius[state] = cornerRadius apply(state: self.controlState) } public func set(hoverAdditionPolicy: ButtonHoverPolicy, for state:ControlState) -> Void { self.hoverAdditionPolicy[state] = hoverAdditionPolicy apply(state: self.controlState) } public override var animates: Bool { didSet { imageView.animates = animates } } private var previousState: ControlState? override public func apply(state: ControlState) { let previous = self.previousState let state:ControlState = self.isSelected ? .Highlight : state super.apply(state: state) self.previousState = state let updated: CGImage? if let image = images[state], isEnabled { updated = image } else if state == .Highlight && autohighlight, isEnabled, let image = images[.Normal] { updated = style.highlight(image: image) } else if state == .Hover && highlightHovered, isEnabled, let image = images[.Normal] { updated = style.highlight(image: image) } else { updated = images[.Normal] } if imageView.image != updated { self.imageView.image = updated } // if state != previousState { self.imageView.animator().alphaValue = isEnabled ? 1 : 0.8 if let policy = self.hoverAdditionPolicy[state], previous != state { switch policy { case .none: break case let .enlarge(value): let current = additionBackgroundView.layer?.presentation()?.value(forKeyPath: "transform.scale") as? CGFloat ?? 1.0 additionBackgroundView.layer?.animateScaleSpring(from: current, to: value, duration: 0.35, removeOnCompletion: false) } } if let color = self.additionStateBackground[state] ?? self.additionStateBackground[.Normal] { additionBackgroundView.backgroundColor = color } else { additionBackgroundView.backgroundColor = .clear } updateLayout() if let cornerRadius = self.cornerRadius[state] { switch cornerRadius { case .none: self.layer?.cornerRadius = 0 self.additionBackgroundView.layer?.cornerRadius = 0 case .appSpecific: self.layer?.cornerRadius = .cornerRadius self.additionBackgroundView.layer?.cornerRadius = .cornerRadius case .half: self.layer?.cornerRadius = max(frame.width, frame.height) / 2 self.additionBackgroundView.layer?.cornerRadius = max(additionBackgroundView.frame.width, additionBackgroundView.frame.height) / 2 } } //} } public func applyAnimation(from: CGImage, to: CGImage, animation: ImageButtonAnimationPolicy) { switch animation { case .animateContents: self.imageView.image = to case .replaceScale: let imageView = self.imageView imageView.image = from let newImageView = ImageView() self.imageView = newImageView newImageView.image = to newImageView.sizeToFit() addSubview(newImageView) newImageView.center() imageView.layer?.animateScaleCenter(from: 1, to: 0.1, duration: 0.25, removeOnCompletion: false, completion: { [weak imageView] _ in imageView?.removeFromSuperview() }) imageView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false) newImageView.layer?.animateScaleCenter(from: 0.1, to: 1, duration: 0.25, removeOnCompletion: true) } } public func disableActions() { animates = false self.layer?.disableActions() layer?.removeAllAnimations() imageView.animates = false imageView.layer?.disableActions() } open override func setFrameOrigin(_ newOrigin: NSPoint) { super.setFrameOrigin(newOrigin) } @discardableResult override public func sizeToFit(_ addition: NSSize = NSZeroSize, _ maxSize:NSSize = NSZeroSize, thatFit:Bool = false) -> Bool { _ = super.sizeToFit(addition, maxSize, thatFit: thatFit) if let image = images[.Normal] { var size = image.backingSize if maxSize.width > 0 || maxSize.height > 0 { size = maxSize } size.width += addition.width size.height += addition.height self.setFrameSize(size) } return true } public override func updateLayout() { if let image = self.imageView.image { switch imageView.contentGravity { case .resize, .resizeAspectFill: imageView.setFrameSize(frame.size) default: imageView.setFrameSize(image.backingSize) } } imageView.center() if let multiplier = additionBackgroundMultiplier[controlState] { additionBackgroundView.setFrameSize(NSMakeSize(floorToScreenPixels(backingScaleFactor, frame.width * multiplier), floorToScreenPixels(backingScaleFactor, frame.height * multiplier))) } else { additionBackgroundView.setFrameSize(frame.size) } additionBackgroundView.center() } }
gpl-2.0
7201e522e8d2cb2841d6b9ab5cab5aae
33.635593
194
0.605823
5.311241
false
false
false
false
sishenyihuba/Weibo
Weibo/00-Main(主要)/VisitorView/VisitorView.swift
1
1136
// // VisitorView.swift // Weibo // // Created by daixianglong on 2017/1/9. // Copyright © 2017年 Dale. All rights reserved. // import UIKit class VisitorView: UIView { @IBOutlet weak var rotateImageView: UIImageView! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var registerBtn: UIButton! @IBOutlet weak var loginBtn: UIButton! class func createVisitorView() -> VisitorView { return NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).first as! VisitorView } func setupVisitorViewInfo(imageName:String,title:String) { iconImageView.image = UIImage(named: imageName) titleLabel.text = title rotateImageView.hidden = true } func addRotateAnim() { let anim = CABasicAnimation(keyPath: "transform.rotation.z") anim.duration = 5 anim.fromValue = 0 anim.toValue = 2 * M_PI anim.repeatCount = MAXFLOAT anim.removedOnCompletion = false rotateImageView.layer.addAnimation(anim, forKey: nil) } }
mit
d0d78034d568a6b2d792bb2b736496a3
26.634146
112
0.662842
4.46063
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Site Creation/WebAddress/AddressCell.swift
2
3534
import UIKit import WordPressKit final class AddressCell: UITableViewCell, ModelSettableCell { static var estimatedSize: CGSize { return CGSize(width: 320, height: 45) } private struct TextStyleAttributes { static let defaults: [NSAttributedString.Key: Any] = [.font: WPStyleGuide.fontForTextStyle(.body, fontWeight: .regular), .foregroundColor: UIColor.textSubtle] static let customName: [NSAttributedString.Key: Any] = [.font: WPStyleGuide.fontForTextStyle(.body, fontWeight: .regular), .foregroundColor: UIColor.text] } var borders = [UIView]() @IBOutlet weak var title: UILabel! var model: DomainSuggestion? { didSet { title.attributedText = AddressCell.processName(model?.domainName) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { selectedBackgroundView?.backgroundColor = .clear accessibilityTraits = .button accessibilityHint = NSLocalizedString("Selects this domain to use for your site.", comment: "Accessibility hint for a domain in the Site Creation domains list.") } override func awakeFromNib() { super.awakeFromNib() styleCheckmark() } override func setSelected(_ selected: Bool, animated: Bool) { accessoryType = selected ? .checkmark : .none } private func styleCheckmark() { tintColor = .primary(.shade40) } override func prepareForReuse() { title.attributedText = nil borders.forEach({ $0.removeFromSuperview() }) borders = [] } public func addBorder(isFirstCell: Bool = false, isLastCell: Bool = false) { if isFirstCell { let border = addTopBorder(withColor: .divider) borders.append(border) } if isLastCell { let border = addBottomBorder(withColor: .divider) borders.append(border) } else { let border = addBottomBorder(withColor: .divider, leadingMargin: 20) borders.append(border) } } public static func processName(_ domainName: String?) -> NSAttributedString? { guard let name = domainName, let customName = name.components(separatedBy: ".").first else { return nil } let completeDomainName = NSMutableAttributedString(string: name, attributes: TextStyleAttributes.defaults) let rangeOfCustomName = NSRange(location: 0, length: customName.count) completeDomainName.setAttributes(TextStyleAttributes.customName, range: rangeOfCustomName) return completeDomainName } } extension AddressCell { override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory { preferredContentSizeDidChange() } } func preferredContentSizeDidChange() { title.attributedText = AddressCell.processName(model?.domainName) } }
gpl-2.0
a1a58ff1934ab9b8cb019a76f7444231
34.34
130
0.63837
5.636364
false
false
false
false
Shivam0911/IOS-Training-Projects
MyntraLookLike/MyntraLookLike/VehicleCollectionCell.swift
1
837
// // VehicleCollectionCell.swift // MyntraLookLike // // Created by MAC on 16/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class VehicleCollectionCell: UICollectionViewCell { //MARK: Outlets of VehicleCollectionCell //============================ @IBOutlet weak var VehicleImageOutlet: UIImageView! @IBOutlet weak var favButton: UIButton! var sectionTag : Int = 0 override func awakeFromNib() { super.awakeFromNib() favButton.backgroundColor = UIColor.clear self.VehicleImageOutlet.contentMode = .scaleAspectFill } override func prepareForReuse() { self.VehicleImageOutlet.contentMode = .scaleAspectFill favButton.isSelected = false } }
mit
ad8ec26cea23bd8a491b785706ff3ff2
19.9
62
0.608852
5.192547
false
false
false
false
eure/ReceptionApp
iOS/ReceptionApp/Screens/ConfirmAppointmentViewController.swift
1
4786
// // ConfirmViewController.swift // ReceptionApp // // Created by Hiroshi Kimura on 8/25/15. // Copyright © 2016 eureka, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit // MARK: - ConfirmAppointmentViewController final class ConfirmAppointmentViewController: BaseConfirmViewController { // MARK: Internal @IBOutlet private(set) dynamic weak var contactToView: UIView! @IBOutlet private(set) dynamic weak var nameView: UIView! @IBOutlet private(set) dynamic weak var companyNameView: UIView! @IBOutlet private(set) dynamic weak var countview: UIView! var transaction: AppointmentTransaction? // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Configuration.Color.backgroundColor self.contactToView.backgroundColor = Configuration.Color.backgroundColor self.nameView.backgroundColor = Configuration.Color.backgroundColor self.companyNameView.backgroundColor = Configuration.Color.backgroundColor self.countview.backgroundColor = Configuration.Color.backgroundColor self.icons.forEach { $0.tintColor = Configuration.Color.imageTintColor } self.contactToLabel.attributedText = NSAttributedString.baseAttributedString( self.transaction?.user.nameJa ?? "", color: Configuration.Color.textColor, size: 32 ) if let visitor = self.transaction?.visitor { let size: CGFloat = 32 self.nameLabel.attributedText = NSAttributedString.baseAttributedString( visitor.name ?? "", color: Configuration.Color.textColor, size: size ) self.companyLabel.attributedText = NSAttributedString.baseAttributedString( visitor.companyName, color: Configuration.Color.textColor, size: size ) self.countLabel.attributedText = NSAttributedString.baseAttributedString( "\(visitor.numberOfPersons)人", color: Configuration.Color.textColor, size: size ) } self.messageLabel.font = Configuration.Font.baseBoldFont(size: 18) self.messageLabel.text = "ConfirmAppointmentViewController.label.confirm".l10n self.messageLabel.textColor = Configuration.Color.textColor } // MARK: BaseConfirmViewController override dynamic func handleSubmitButton(sender: AnyObject) { guard let transaction = self.transaction else { return } super.handleSubmitButton(sender) let controller = CompletionViewController.viewControllerFromStoryboard() Container.VisitorService.sendVisitor(transaction: transaction) { _ in } self.navigationController?.pushViewController(controller, animated: true) } // MARK: Private @IBOutlet private dynamic weak var contactToIconImageView: UIImageView! @IBOutlet private dynamic weak var nameIconImageView: UIImageView! @IBOutlet private dynamic weak var companyNameIconImageView: UIImageView! @IBOutlet private dynamic weak var countIconImageView: UIImageView! @IBOutlet private dynamic weak var contactToLabel: UILabel! @IBOutlet private dynamic weak var nameLabel: UILabel! @IBOutlet private dynamic weak var companyLabel: UILabel! @IBOutlet private dynamic weak var countLabel: UILabel! @IBOutlet private dynamic var icons: [UIImageView]! @IBOutlet private dynamic var labels: [UILabel]! }
mit
b46632f8a8b35a36dd4d00a7dac80e2a
38.204918
87
0.687853
5.320356
false
true
false
false
mrommel/MiRoRecipeBook
MiRoRecipeBook/MiRoRecipeBook/Presentation/App/MenuTableViewController.swift
1
3862
// // MenuTableViewController.swift // MiRo.RecipeBook // // Created by Michael Rommel on 22.11.16. // Copyright © 2016 MiRo Soft. All rights reserved. // import UIKit import SideMenu enum ScreenType { case recipes case ingredients case categories case settings } struct MenuItem { var image: String! var name: String! var screenType: ScreenType! } class MenuTableViewController: UITableViewController { var menuItems: [MenuItem] = [] var appWireframe: AppWireframe? override func viewDidLoad() { super.viewDidLoad() menuItems.append(MenuItem(image: "menu-recipe.png", name: "Recipes".localized, screenType:ScreenType.recipes)) menuItems.append(MenuItem(image: "menu-ingredients.png", name: "Ingredients".localized, screenType:ScreenType.ingredients)) menuItems.append(MenuItem(image: "menu-category.png", name: "Categories".localized, screenType:ScreenType.categories)) menuItems.append(MenuItem(image: "menu-settings.png", name: "Settings".localized, screenType:ScreenType.settings)) self.title = "RecipeBook".localized } func createViewController(forScreenType screenType: ScreenType) -> UIViewController? { switch screenType { case .recipes: return AppDelegate.shared?.appDependecies?.recipesWireframe?.getRecipesInterface() case .ingredients: return AppDelegate.shared?.appDependecies?.ingredientsWireframe?.getIngredientsInterface() case .categories: return AppDelegate.shared?.appDependecies?.categoriesWireframe?.getCategoriesInterface() case .settings: return AppDelegate.shared?.appDependecies?.settingsWireframe?.getSettingsInterface() } } } // MARK: UITableViewDelegate methods extension MenuTableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let targetViewController = self.createViewController(forScreenType: menuItems[indexPath.row].screenType) self.appWireframe?.showDetail(for: targetViewController) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIImageView(frame: CGRect(x:0, y: 0,width: tableView.frame.size.width, height: 180)) headerView.backgroundColor = UIColor.white headerView.image = UIImage(named: "Logo") headerView.contentMode = .scaleAspectFit return headerView } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = UIView(frame: CGRect(x:0,y: 0,width: tableView.frame.size.width,height: 1)) footerView.backgroundColor = UIColor.white return footerView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 180.0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 1.0 } } // MARK: UITableViewDataSource methods extension MenuTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as UITableViewCell cell.imageView?.image = UIImage.init(named: menuItems[indexPath.row].image) cell.textLabel?.text = menuItems[indexPath.row].name return cell } }
gpl-3.0
ec1c44e6aa84c21a82ae1bd042957c9f
32
131
0.702668
4.918471
false
false
false
false
hanjoes/drift-doc
Drift/Tests/DriftRuntimeTests/TestMarkupConversion.swift
1
11251
import XCTest @testable import DriftRuntime class TestMarkupConversion: XCTestCase { /// ------------------------------------------------ func testMarkupConversionParameter() throws { let file = """ /** * Noop. * * @param param some parameter. */ public static func noop(param: Int) { } """ let expected = """ /// /// Noop. /// /// - Parameter param: some parameter. /// public static func noop(param: Int) { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } /// ------------------------------------------------ func testMarkupConversionReturns() throws { let file = """ /** * Noop. * * @return returning nothing. */ public static func noop(param: Int) -> Void { } """ let expected = """ /// /// Noop. /// /// - Returns: returning nothing. /// public static func noop(param: Int) -> Void { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } /// ------------------------------------------------ func testMarkupConversionThrows() throws { let file = """ /** * Noop. * * @throws some exception */ public static func noop(param: Int) throws -> Void { } """ let expected = """ /// /// Noop. /// /// - Throws: some exception /// public static func noop(param: Int) throws -> Void { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } /// ------------------------------------------------ func testMarkupMixedSections() throws { let file = """ /** * Noop. * * @return void * @exception some exception * @param param dorky parameter * @param param dorky parameter brother * @throws exception2 */ public static func noop(param: Int) throws -> Void { } """ let expected = """ /// /// Noop. /// /// - Parameter param: dorky parameter /// - Parameter param: dorky parameter brother /// - Throws: some exception /// - Throws: exception2 /// - Returns: void /// public static func noop(param: Int) throws -> Void { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } /// ------------------------------------------------ func testMarkupAuthorAndParameter() throws { let file = """ /** * Noop. * * @return void * @throws some exception * @author hanjoes * @param param dorky parameter * @param param dorky parameter brother * @throws exception2 */ public static func noop(param: Int) throws -> Void { } """ let expected = """ /// /// Noop. /// /// - Author: hanjoes /// - Parameter param: dorky parameter /// - Parameter param: dorky parameter brother /// - Throws: some exception /// - Throws: exception2 /// - Returns: void /// public static func noop(param: Int) throws -> Void { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } /// ------------------------------------------------ func testMixedInlineAndDedicatedCallouts() throws { let file = """ /** * Noop. * Comment line1. * * * @version 3.14159 * @return void * @throws some exception * @author hanjoes * @param param dorky parameter {@link ParameterType#type} * @param param dorky parameter brother * @since epoch * @throws exception2 * @see some other code */ public static func noop(param: Int) throws -> Void { } """ let expected = """ /// /// Noop. /// Comment line1. /// /// /// - Version: 3.14159 /// - Author: hanjoes /// - Since: epoch /// - SeeAlso: some other code /// - Parameter param: dorky parameter _ParameterType#type_ /// - Parameter param: dorky parameter brother /// - Throws: some exception /// - Throws: exception2 /// - Returns: void /// public static func noop(param: Int) throws -> Void { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } /// ------------------------------------------------ func testMixedCalloutsWithCodeVoiceEmbedded() throws { let file = """ /** * Noop. * Comment line1. {@code some code} is working! * * * @version 3.14159 * @serial "json" encoded * @deprecated this API should not be used * @return void * @throws some exception {@code TestException} should {@literal never be thrown.} * @author hanjoes */ public static func noop(param: Int) throws -> Void { } """ let expected = """ /// /// Noop. /// Comment line1. `some code` is working! /// /// /// - Version: 3.14159 /// "json" encoded /// this API should not be used /// - Author: hanjoes /// - Throws: some exception `TestException` should `never be thrown.` /// - Returns: void /// public static func noop(param: Int) throws -> Void { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } /// ------------------------------------------------ func testMoreThanOneCommentBlock() throws { let file = """ /** * Noop. * Comment line1. {@code some code} is working! * * * @version 3.14159 * @serial "json" encoded * @deprecated this API should not be used * @return void * @throws some exception {@code TestException} should {@literal never be thrown.} * @author hanjoes */ public static func noop(param: Int) throws -> Void { } /** * Noop. * * @return void * @throws some exception * @author hanjoes * @param param dorky parameter * @param param dorky parameter brother * @throws exception2 */ public static func noop(param: Int) throws -> Void { } """ let expected = """ /// /// Noop. /// Comment line1. `some code` is working! /// /// /// - Version: 3.14159 /// "json" encoded /// this API should not be used /// - Author: hanjoes /// - Throws: some exception `TestException` should `never be thrown.` /// - Returns: void /// public static func noop(param: Int) throws -> Void { } /// /// Noop. /// /// - Author: hanjoes /// - Parameter param: dorky parameter /// - Parameter param: dorky parameter brother /// - Throws: some exception /// - Throws: exception2 /// - Returns: void /// public static func noop(param: Int) throws -> Void { } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } func testOneLineJavadoc() throws { let file = """ /** The type of a {@link org.antlr.v4.runtime.atn.LexerSkipAction} action. */ """ let expected = """ /// The type of a _org.antlr.v4.runtime.atn.LexerSkipAction_ action. """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } func testIndentedJavadoc() throws { let file = """ /** * The type of a {@link org.antlr.v4.runtime.atn.LexerSkipAction} action. */ """ let expected = """ /// /// The type of a _org.antlr.v4.runtime.atn.LexerSkipAction_ action. /// """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } func testCanProcessTrippleSlash() throws { let file = """ /// This UUID indicates an extension of {@link #ADDED_PRECEDENCE_TRANSITIONS} /// for the addition of lexer actions encoded as a sequence of /// {@link org.antlr.v4.runtime.atn.LexerAction} instances. private static let ADDED_LEXER_ACTIONS: UUID = UUID(uuidString: "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E")! /** * This list contains all of the currently supported UUIDs, ordered by when * the feature first appeared in this branch. */ private static let SUPPORTED_UUIDS: Array<UUID> = { var suuid = Array<UUID>() suuid.append(ATNDeserializer.BASE_SERIALIZED_UUID) suuid.append(ATNDeserializer.ADDED_PRECEDENCE_TRANSITIONS) suuid.append(ATNDeserializer.ADDED_LEXER_ACTIONS) suuid.append(ATNDeserializer.ADDED_UNICODE_SMP) return suuid }() /// Determines if a particular serialized representation of an ATN supports /// a particular feature, identified by the {@link java.util.UUID} used for serializing /// the ATN at the time the feature was first introduced. /// /// - parameter feature: The {@link java.util.UUID} marking the first time the feature was /// supported in the serialized ATN. /// - parameter actualUuid: The {@link java.util.UUID} of the actual serialized ATN which is /// currently being deserialized. /// - returns: {@code true} if the {@code actualUuid} value represents a /// serialized ATN at or after the feature identified by {@code feature} was /// introduced; otherwise, {@code false}. internal func isFeatureSupported(_ feature: UUID, _ actualUuid: UUID) -> Bool { let featureIndex: Int = ATNDeserializer.SUPPORTED_UUIDS.index(of: feature)! if featureIndex < 0 { return false } return ATNDeserializer.SUPPORTED_UUIDS.index(of: actualUuid)! >= featureIndex } """ let expected = """ /// /// This UUID indicates an extension of _#ADDED_PRECEDENCE_TRANSITIONS_ /// for the addition of lexer actions encoded as a sequence of /// _org.antlr.v4.runtime.atn.LexerAction_ instances. /// private static let ADDED_LEXER_ACTIONS: UUID = UUID(uuidString: "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E")! /// /// This list contains all of the currently supported UUIDs, ordered by when /// the feature first appeared in this branch. /// private static let SUPPORTED_UUIDS: Array<UUID> = { var suuid = Array<UUID>() suuid.append(ATNDeserializer.BASE_SERIALIZED_UUID) suuid.append(ATNDeserializer.ADDED_PRECEDENCE_TRANSITIONS) suuid.append(ATNDeserializer.ADDED_LEXER_ACTIONS) suuid.append(ATNDeserializer.ADDED_UNICODE_SMP) return suuid }() /// /// Determines if a particular serialized representation of an ATN supports /// a particular feature, identified by the _java.util.UUID_ used for serializing /// the ATN at the time the feature was first introduced. /// /// - parameter feature: The _java.util.UUID_ marking the first time the feature was /// supported in the serialized ATN. /// - parameter actualUuid: The _java.util.UUID_ of the actual serialized ATN which is /// currently being deserialized. /// - returns: `true` if the `actualUuid` value represents a /// serialized ATN at or after the feature identified by `feature` was /// introduced; otherwise, `false`. /// internal func isFeatureSupported(_ feature: UUID, _ actualUuid: UUID) -> Bool { let featureIndex: Int = ATNDeserializer.SUPPORTED_UUIDS.index(of: feature)! if featureIndex < 0 { return false } return ATNDeserializer.SUPPORTED_UUIDS.index(of: actualUuid)! >= featureIndex } """ let actual = try DriftConverter.rewrite(content: file) XCTAssertEqual(expected, actual) } }
mit
4977e343f7e012bd503e997f8fff5ff1
25.535377
109
0.603591
3.880993
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/YTime/view/YTimeJobTableViewCell.swift
2
1160
// // YTimeJobTableViewCell.swift // byuSuite // // Created by Eric Romrell on 5/17/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import UIKit class YTimeJobTableViewCell: UITableViewCell { //MARK: Outlets @IBOutlet private weak var jobLabel: UILabel! @IBOutlet private weak var weekHoursLabel: UILabel! @IBOutlet private weak var periodHoursLabel: UILabel! @IBOutlet private weak var punchView: PunchView! @IBOutlet private weak var errorLabel: UILabel! //MARK: Public properties var delegate: YTimePunchDelegate? { get { return punchView.delegate } set { punchView.delegate = newValue } } var job: YTimeJob? { didSet { if let job = job { jobLabel.text = job.jobCodeDescription weekHoursLabel.text = job.weeklySubtotal periodHoursLabel.text = job.periodSubtotal punchView.job = job //If they aren't allowed to report time from a mobile device, disable the buttons and display the error message if !job.validAccount { punchView.isEnabled = false errorLabel.text = job.message } else { punchView.isEnabled = true errorLabel.text = nil } } } } }
apache-2.0
8dc91521487efa9132c6cafcf814b71e
25.953488
115
0.716135
3.633229
false
false
false
false
tomlokhorst/swift-cancellationtoken
Tests/CancellationTokenTests/CancellationTokenTests.swift
1
2662
// // CancellationTokenTests.swift // CancellationTokenTests // // Created by Tom Lokhorst on 2014-10-31. // // import XCTest import CancellationToken class CancellationTokenTests: XCTestCase { func testDefault() { let source = CancellationTokenSource() let token = source.token XCTAssertFalse(token.isCancellationRequested, "Default should be false") } func testCancel() { let source = CancellationTokenSource() let token = source.token source.cancel() XCTAssert(token.isCancellationRequested, "Token should be cancelled") } func testDelayedCancel() { let expectation = self.expectation(description: "Cancel not registered") let source = CancellationTokenSource() let token = source.token DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { source.cancel() } DispatchQueue.main.asyncAfter(deadline: .now() + 0.02) { if token.isCancellationRequested { expectation.fulfill() } } waitForExpectations(timeout: 0.03, handler: nil) } func testCancelWithDelay() { let expectation = self.expectation(description: "Cancel not registered") let source = CancellationTokenSource() let token = source.token source.cancelAfter(timeInterval: 0.01) XCTAssertFalse(token.isCancellationRequested, "Cancel should still be false") DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { if token.isCancellationRequested { expectation.fulfill() } } waitForExpectations(timeout: 0.02, handler: nil) } func testRegisterBefore() { let expectation = self.expectation(description: "Cancel not registered") let source = CancellationTokenSource() let token = source.token token.register { expectation.fulfill() } source.cancelAfter(timeInterval: 0.01) waitForExpectations(timeout: 0.2, handler: nil) } func testRegisterAfter() { let source = CancellationTokenSource() let token = source.token var didCancel = false source.cancel() token.register { didCancel = true } XCTAssertTrue(didCancel) } func testRegisterDuring() { let source = CancellationTokenSource() let token = source.token var didCancel = false token.register { token.register { didCancel = true } } source.cancel() XCTAssertTrue(didCancel) } func testDeinitSource() { var source: CancellationTokenSource? = CancellationTokenSource() let token = source!.token var didCancel = false token.register { didCancel = true } source = nil XCTAssertTrue(didCancel) } }
mit
a79fcfeeb03f2e9e2750d04b5b3938fc
19.796875
81
0.675808
4.653846
false
true
false
false
apple/swift-corelibs-foundation
Sources/Foundation/EnergyFormatter.swift
2
6961
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // extension EnergyFormatter { public enum Unit: Int { case joule = 11 case kilojoule = 14 case calorie = 1793 // chemistry "calories", abbr "cal" case kilocalorie = 1794 // kilocalories in general, abbr “kcal”, or “C” in some locales (e.g. US) when usesFoodEnergy is set to YES // Map Unit to UnitEnergy class to aid with conversions fileprivate var unitEnergy: UnitEnergy { switch self { case .joule: return .joules case .kilojoule: return .kilojoules case .calorie: return .calories case .kilocalorie: return .kilocalories } } // Reuse symbols defined in UnitEnergy, except for kilocalories, which is defined as "kCal" fileprivate var symbol: String { switch self { case .kilocalorie: return "kcal" default: return unitEnergy.symbol } } // Return singular, full string representation of the energy unit fileprivate var singularString: String { switch self { case .joule: return "joule" case .kilojoule: return "kilojoule" case .calorie: return "calorie" case .kilocalorie: return "kilocalorie" } } // Return plural, full string representation of the energy unit fileprivate var pluralString: String { return "\(self.singularString)s" } } } open class EnergyFormatter: Formatter { public override init() { numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal unitStyle = .medium isForFoodEnergyUse = false super.init() } public required init?(coder: NSCoder) { numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal unitStyle = .medium isForFoodEnergyUse = false super.init() } /*@NSCopying*/ open var numberFormatter: NumberFormatter! // default is NumberFormatter with NumberFormatter.Style.decimal open var unitStyle: UnitStyle // default is NSFormattingUnitStyleMedium open var isForFoodEnergyUse: Bool // default is NO; if it is set to YES, EnergyFormatter.Unit.kilocalorie may be “C” instead of “kcal" // Format a combination of a number and an unit to a localized string. open func string(fromValue value: Double, unit: Unit) -> String { guard let formattedValue = numberFormatter.string(from:NSNumber(value: value)) else { fatalError("Cannot format \(value) as string") } let separator = unitStyle == .short ? "" : " " return "\(formattedValue)\(separator)\(unitString(fromValue: value, unit: unit))" } // Format a number in joules to a localized string with the locale-appropriate unit and an appropriate scale (e.g. 10.3J = 2.46cal in the US locale). open func string(fromJoules numberInJoules: Double) -> String { //Convert to the locale-appropriate unit var unitFromJoules: EnergyFormatter.Unit = .joule _ = self.unitString(fromJoules: numberInJoules, usedUnit: &unitFromJoules) //Map the unit to UnitLength type for conversion later let unitEnergyFromJoules = unitFromJoules.unitEnergy //Create a measurement object based on the value in joules let joulesMeasurement = Measurement<UnitEnergy>(value:numberInJoules, unit: .joules) //Convert the object to the locale-appropriate unit determined above let unitMeasurement = joulesMeasurement.converted(to: unitEnergyFromJoules) //Extract the number from the measurement let numberInUnit = unitMeasurement.value return string(fromValue: numberInUnit, unit: unitFromJoules) } // Return a localized string of the given unit, and if the unit is singular or plural is based on the given number. open func unitString(fromValue value: Double, unit: Unit) -> String { //Special case when isForFoodEnergyUse is true if isForFoodEnergyUse && unit == .kilocalorie { if unitStyle == .short { return "C" } else if unitStyle == .medium { return "Cal" } else { return "Calories" } } if unitStyle == .short || unitStyle == .medium { return unit.symbol } else if value == 1.0 { return unit.singularString } else { return unit.pluralString } } // Return the locale-appropriate unit, the same unit used by -stringFromJoules:. open func unitString(fromJoules numberInJoules: Double, usedUnit unitp: UnsafeMutablePointer<Unit>?) -> String { //Convert to the locale-appropriate unit let unitFromJoules: Unit if self.usesCalories { if numberInJoules > 0 && numberInJoules <= 4184 { unitFromJoules = .calorie } else { unitFromJoules = .kilocalorie } } else { if numberInJoules > 0 && numberInJoules <= 1000 { unitFromJoules = .joule } else { unitFromJoules = .kilojoule } } unitp?.pointee = unitFromJoules //Map the unit to UnitEnergy type for conversion later let unitEnergyFromJoules = unitFromJoules.unitEnergy //Create a measurement object based on the value in joules let joulesMeasurement = Measurement<UnitEnergy>(value:numberInJoules, unit: .joules) //Convert the object to the locale-appropriate unit determined above let unitMeasurement = joulesMeasurement.converted(to: unitEnergyFromJoules) //Extract the number from the measurement let numberInUnit = unitMeasurement.value //Return the appropriate representation of the unit based on the selected unit style return unitString(fromValue: numberInUnit, unit: unitFromJoules) } /// Regions that use calories private static let caloriesRegions: Set<String> = ["en_US", "en_US_POSIX", "haw_US", "es_US", "chr_US", "en_GB", "kw_GB", "cy_GB", "gv_GB"] /// Whether the region uses calories private var usesCalories: Bool { return EnergyFormatter.caloriesRegions.contains(numberFormatter.locale.identifier) } }
apache-2.0
2fb862816de5b977675b2252a02d2998
36.551351
153
0.621419
4.570395
false
false
false
false
blinksh/blink
SSHTests/SSHPortForwardTests.swift
1
20336
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2021 Blink Mobile Shell Project // // This file is part of Blink. // // Blink 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. // // Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import XCTest import Combine import Dispatch import Network @testable import SSH extension SSHTests { func testForwardPort() throws { let expectConnection = self.expectation(description: "Connected") let expectListenerClosed = self.expectation(description: "Listener Closed") var connection: SSHClient? var lis: SSHPortForwardListener? let urlSession = URLSession(configuration: URLSessionConfiguration.default) SSHClient .dialWithTestConfig() .map() { conn -> SSHPortForwardListener in print("Received Connection") connection = conn lis = SSHPortForwardListener( on: 8080, toDestination: "www.guimp.com", on: 80, using: conn ) return lis! } .flatMap { $0.connect() } .sink( receiveCompletion: { completion in switch completion { case .finished: expectListenerClosed.fulfill() case .failure(let error): XCTFail("\(error)") } }, receiveValue: { event in switch event { case .starting: print("Listener Starting") case .ready: expectConnection.fulfill() case .error(let error): XCTFail("\(error)") default: break } }).store(in: &cancellableBag) wait(for: [expectConnection], timeout: 15) let expectResponse = self.expectation(description: "Response received") var request = URLRequest(url: URL(string: "http://127.0.0.1:8080")!) request.addValue("www.guimp.com", forHTTPHeaderField: "Host") // Launch a request on the port urlSession .dataTaskPublisher(for: request) .assertNoFailure() .sink { element in guard let httpResponse = element.response as? HTTPURLResponse else { XCTFail("Bad server response") return } XCTAssert(httpResponse.statusCode == 200, "Wrong status code \(httpResponse.statusCode)") expectResponse.fulfill() }.store(in: &cancellableBag) wait(for: [expectResponse], timeout: 5) // A second request should succeed because URLSession keeps the connection // open in the pool, even if we got a result. expectResponse will only be called once (one stream only) let expectResponse2 = self.expectation(description: "Response received") // Launch a request on the port urlSession .dataTaskPublisher(for: request) .assertNoFailure() .sink { element in guard let httpResponse = element.response as? HTTPURLResponse else { XCTFail("Bad server response") return } XCTAssert(httpResponse.statusCode == 200, "Wrong status code \(httpResponse.statusCode)") expectResponse2.fulfill() }.store(in: &cancellableBag) wait(for: [expectResponse2], timeout: 5) let expectResponse3 = self.expectation(description: "Response received") // Launch a request on the port URLSession.shared .dataTaskPublisher(for: request) .assertNoFailure() .sink { element in guard let httpResponse = element.response as? HTTPURLResponse else { XCTFail("Bad server response") return } XCTAssert(httpResponse.statusCode == 200, "Wrong status code \(httpResponse.statusCode)") expectResponse3.fulfill() }.store(in: &cancellableBag) wait(for: [expectResponse3], timeout: 5) XCTAssertTrue(lis!.connections.count == 2, "Stream was not renewed the second time.") // Close the Tunnel and all open connections. lis!.close() wait(for: [expectListenerClosed], timeout: 5) } func testListenerPort() throws { self.continueAfterFailure = false var expectConnection = self.expectation(description: "Connected") var connection: SSHClient? var lis: SSHPortForwardListener? SSHClient.dialWithTestConfig() .tryMap() { conn -> SSHPortForwardListener in print("Received Connection") connection = conn lis = SSHPortForwardListener( on: 8080, toDestination: "www.guimp.com", on: 80, using: conn ) return lis! }.flatMap { $0.connect() } .compactMap { event -> AnyPublisher<Void, Error>? in switch event { case .starting: print("Listener Starting") return nil case .ready: print("Listener Ready") expectConnection.fulfill() return nil default: return nil } }.assertNoFailure() .sink {_ in }.store(in: &cancellableBag) wait(for: [expectConnection], timeout: 15) // A second listener should fail when started on same port. let expectFailure = self.expectation(description: "Connected") let lis2 = SSHPortForwardListener(on: 8080, toDestination: "www.google.com", on: 80, using: connection!) lis2.connect().tryMap { event in print("Listener sent \(event)") }.sink (receiveCompletion: {completion in switch completion { case .failure(let error): print("\(error)") expectFailure.fulfill() case .finished: XCTFail("Listener should not have started") } }, receiveValue: {}).store(in: &cancellableBag) wait(for: [expectFailure], timeout: 15) } func testReverseForwardPort() throws { // We test it by doing the same as the forward, but on the other side. // So instead of a URLRequest, execute a command on the "server" // calling the routed port. // curl -o /dev/null -s -w "%{http_code}\n" http://localhost self.continueAfterFailure = false let expectForward = self.expectation(description: "Forward ready") let expectStream = self.expectation(description: "Stream received") var connection: SSHClient? var client: SSHPortForwardClient? SSHClient.dial(Credentials.password.host, with: .testConfig) .tryMap() { conn -> SSHPortForwardClient in print("Received Connection") connection = conn client = SSHPortForwardClient(forward: "www.guimp.com", onPort: 80, toRemotePort: 8080, using: conn) return client! }.flatMap { c -> AnyPublisher<Void, Error> in expectForward.fulfill() return c.ready() }.flatMap { client!.connect() } .assertNoFailure() .sink { event in print("Received \(event)") switch event { case .ready: break case .error(let error): XCTFail("\(error)") default: break } }.store(in: &cancellableBag) wait(for: [expectForward], timeout: 15) var cmd: SSH.Stream? // We put a small delay as sometimes if it happens too close, the machine won't be able to resolve it. let curl = "sleep 1 && curl -o /dev/null -H \"Host: www.guimp.com\" -s -w \"%{http_code}\n\" localhost:8080" let cancelRequest = connection!.requestExec(command: curl) .flatMap { stream -> AnyPublisher<DispatchData, Error> in cmd = stream return stream.read(max: SSIZE_MAX) } .assertNoFailure() .sink { buf in let output = String(data: buf as AnyObject as! Data, encoding: .utf8) // Output may be 000 in case the channel did not succeed. XCTAssert(output == "200\n") expectStream.fulfill() } wait(for: [expectStream], timeout: 15) // Closing up stuff. Sometimes there may be a callback or error of some kind because we got rid of some object. client!.close() } func testProxyCommand() throws { // Connect to the proxy on the exposed port. let configProxy = SSHClientConfig(user: Credentials.none.user, port: Credentials.port, authMethods: []) // The proxy connects to itself on default port, so this should go through. let config = SSHClientConfig(user: Credentials.none.user, proxyJump: "\(Credentials.none.host):\(Credentials.port)", //proxyCommand: "ssh -W %h:%p localhost", authMethods: []) let expectConnection = self.expectation(description: "Connected") let expectExecFinished = self.expectation(description: "Exec finished") let expectConnClosed = self.expectation(description: "Main connection closing the proxy") let expectThreadExit = self.expectation(description: "Exit thread") // The callback could be async scheduled, because it will anyway have to // figure out things with the socket. But we have to retain it somehow. var proxyCancellable: AnyCancellable? let execProxyCommand: SSHClient.ExecProxyCommandCallback = { (command, sockIn, sockOut) in // Needs to start a tunnel to the destination, which // should be specified at the command. // The tunnel is then mapped to the socket. // If running a command, we would just map stdio and run the command. let t = Thread(block: { // We should be parsing the command, but assume it is ok let destination = Credentials.none.host let destinationPort = 22 var stream: SSH.Stream? let output = DispatchOutputStream(stream: sockOut) let input = DispatchInputStream(stream: sockIn) var connection: SSHClient? proxyCancellable = SSHClient.dial(Credentials.none.host, with: configProxy) .flatMap() { conn -> AnyPublisher<SSH.Stream, Error> in connection = conn return conn.requestForward(to: destination, port: Int32(destinationPort), from: "localhost", localPort: 22) }.sink(receiveCompletion: { completion in switch completion { case .finished: break case .failure(let error as SSHError): XCTFail(error.description) // Closing the socket should also close the other connection case .failure(let error): XCTFail("Unknown error - \(error)") } }, receiveValue: { s in stream = s s.handleCompletion = { expectConnClosed.fulfill() } // Uncomment if you want to delay the other connection. // Interesting to see how the other one will just try again the Connect. //RunLoop.current.run(until: Date(timeIntervalSinceNow: 2)) s.connect(stdout: output, stdin: input) }) self.wait(for: [expectExecFinished], timeout: 10) // Now we await here for the main connection to close. // Closing the main connection should close the proxy as well. self.wait(for: [expectConnClosed], timeout: 5) expectThreadExit.fulfill() }) t.start() } var connection: SSHClient? let testCommand = "echo hello" var output: DispatchData? var cancellable = SSHClient.dial("localhost", with: config, withProxy: execProxyCommand) .flatMap() { conn -> AnyPublisher<SSH.Stream, Error> in connection = conn return conn.requestExec(command: testCommand) } .flatMap { $0.read(max: 6) } .sink(receiveCompletion: { completion in switch completion { case .finished: expectConnection.fulfill() case .failure(let error as SSHError): XCTFail(error.description) case .failure(let error): XCTFail("Unknown error - \(error)") } }, receiveValue: { buf in output = buf }) wait(for: [expectConnection], timeout: 15) expectExecFinished.fulfill() // Properly wrapping things up, simulating what an app would do. // Just closing the main connection should close the proxy. connection = nil wait(for: [expectThreadExit], timeout: 15) XCTAssertTrue(output?.count == 6, "Not received all bytes for 'hello\n'") } func testProxyCommandConnFailure() throws { // The proxy will not be able to authenticate, and this should trigger // an error during connection, because we won't be able to establish it. var config = SSHClientConfig(user: "carlos", proxyJump: "localhost", //proxyCommand: "ssh -W %h:%p localhost", authMethods: [AuthPassword(with: "")]) let expectFailure = self.expectation(description: "Connection should fail") // The callback could be async scheduled, because it will anyway have to // figure out things with the socket. But we have to retain it somehow. var proxyCancellable: AnyCancellable? let execProxyCommand: SSHClient.ExecProxyCommandCallback = { (command, sockIn, sockOut) in let t = Thread(block: { // Wait and close the socket. Note that if a connection // fails, that is what a CLI would do. RunLoop.current.run(until: Date(timeIntervalSinceNow: 2)) close(sockIn) close(sockOut) }) t.start() } var connection: SSHClient? var cancellable = SSHClient.dial("localhost", with: config, withProxy: execProxyCommand) .sink(receiveCompletion: { completion in switch completion { case .finished: XCTFail("Connection should not have succeeded with no proxy socket") case .failure(let error as SSHError): print("Correctly received error: \(error)") expectFailure.fulfill() case .failure(let error): XCTFail("Unknown error - \(error)") } }, receiveValue: { _ in }) wait(for: [expectFailure], timeout: 500) } // TODO Come back to this after adding TCP Keep Alive packets // The other side of the stream will be happy to think everything works // when the other side is idle. // https://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html // https://stackoverflow.com/questions/34615807/nsstream-delegate-not-firing-errors func testProxyCommandStreamFailure() throws { throw XCTSkip("Suspect issue with NSInputStream. Not receiving EOF events.") // Killing the proxy should close the connection, and if handling // the stream properly, it should be closed as well. And that in a // chain should make everything else receive a close as well, probably // at the session level. // This test may be necessary to see how the flow of errors would work. let config = SSHClientConfig(user: Credentials.regularUser, port: Credentials.port, proxyJump: "localhost", proxyCommand: "ssh -W %h:%p localhost", authMethods: [AuthPassword(with: Credentials.regularUserPassword)], loggingVerbosity: .debug) let destination = "localhost" let destinationPort = 22 let configProxy = SSHClientConfig.testConfig let expectConnection = self.expectation(description: "Connected") let expectExecFinished = self.expectation(description: "Exec finished") let expectConnFailure = self.expectation(description: "Main connection received failure") let expectThreadExit = self.expectation(description: "Exit thread") let expectEOF = self.expectation(description: "EOF") var proxyCancellable: AnyCancellable? let execProxyCommand: SSHClient.ExecProxyCommandCallback = { (command, sockIn, sockOut) in // Needs to start a tunnel to the destination, which // should be specified at the command. // The tunnel is then mapped to the socket. // If running a command, we would just map stdio and run the command. let t = Thread(block: { var stream: SSH.Stream? var output: DispatchOutputStream? = DispatchOutputStream(stream: dup(sockOut)) var input: DispatchInputStream? = DispatchInputStream(stream: dup(sockIn)) var connection: SSHClient? proxyCancellable = SSHClient.dial(destination, with: configProxy) .flatMap() { conn -> AnyPublisher<SSH.Stream, Error> in connection = conn return conn.requestForward(to: destination, port: Int32(destinationPort), from: destination, localPort: 22) }.sink(receiveCompletion: { completion in switch completion { case .finished: break case .failure(let error as SSHError): XCTFail(error.description) // Closing the socket should also close the other connection case .failure(let error): XCTFail("Unknown error - \(error)") } }, receiveValue: { s in stream = s s.handleCompletion = { print("Complete") } s.handleFailure = { error in print("Failed") } s.connect(stdout: output!, stdin: input!) }) self.wait(for: [expectExecFinished], timeout: 5) connection?.rloop.run(until: Date(timeIntervalSinceNow: 2)) // output?.close() // input?.close() // Close the channel stream?.cancel() stream?.sendEOF().assertNoFailure().sink { _ in expectEOF.fulfill() } .store(in: &self.cancellableBag) // self.wait(for: [expectEOF], timeout: 500) stream?.cancel() stream = nil connection = nil close(sockIn) close(sockOut) self.wait(for: [expectConnFailure], timeout: 500) //expectThreadExit.fulfill() }) t.start() } var connection: SSHClient? let testCommand = "du /" var output: DispatchData? var stream: SSH.Stream? let buffer = MemoryBuffer(fast: true) var cancellable = SSHClient.dial("localhost", with: config, withProxy: execProxyCommand) .flatMap() { conn -> AnyPublisher<SSH.Stream, Error> in connection = conn return conn.requestExec(command: testCommand) }.assertNoFailure() .sink { s in stream = s s.handleFailure = { error in print("Captured error on Main SSH \(error)") expectConnFailure.fulfill() } s.handleCompletion = { print("Main connection Completed") } expectExecFinished.fulfill() // We expect this will not return, but want to capture an error s.connect(stdout: buffer) } wait(for: [expectThreadExit], timeout: 500) } }
gpl-3.0
fa5d148341a130e04b750269fdca2dbd
36.245421
119
0.607789
4.789449
false
false
false
false
Verchen/Swift-Project
JinRong/JinRong/Classes/LoginRegist(登录注册)/Controller/ForgetVC.swift
1
3153
// // ForgetVC.swift // JinRong // // Created by 乔伟成 on 2017/7/26. // Copyright © 2017年 乔伟成. All rights reserved. // import UIKit import Alamofire import ObjectMapper import PKHUD class ForgetVC: BaseController { var phoneField = UITextField() var pwdField = UITextField() var repatField = UITextField() override func viewDidLoad() { super.viewDidLoad() title = "找回密码" setupUI() } func setupUI() -> Void { let width = UIScreen.main.bounds.width phoneField.frame = CGRect(x: 10, y: 20, width: width - 20, height: 35) phoneField.placeholder = "请输入手机号" phoneField.keyboardType = .phonePad view.addSubview(phoneField) let line1 = UIView(frame: CGRect.init(x: 10, y: phoneField.frame.maxY, width: width - 20, height: 0.5)) line1.backgroundColor = UIColor.lightGray view.addSubview(line1) pwdField.frame = CGRect(x: 10, y: phoneField.frame.maxY + 5, width: width - 20, height: 35) pwdField.placeholder = "请输入新密码" view.addSubview(pwdField) let line2 = UIView(frame: CGRect.init(x: 10, y: pwdField.frame.maxY, width: width - 20, height: 0.5)) line2.backgroundColor = UIColor.lightGray view.addSubview(line2) repatField.frame = CGRect(x: 10, y: pwdField.frame.maxY + 5, width: width - 20, height: 35) repatField.placeholder = "请再次输入密码" view.addSubview(repatField) let commit = UIButton(type: .custom) commit.setTitle("提交", for: .normal) commit.backgroundColor = UIColor.theme commit.layer.cornerRadius = 5 commit.frame = CGRect(x: 10, y: repatField.frame.maxY + 20, width: width - 20, height: 45) commit.addTarget(self, action: #selector(UpdatePasswordVC.commitClick), for: .touchUpInside) view.addSubview(commit) } func commitClick() -> Void { guard phoneField.hasText && pwdField.hasText && repatField.hasText else { return } if phoneField.text?.isPhone == false { HUD.flash(.labeledError(title: "无效手机号", subtitle: nil), delay: 1) return } let param: Parameters = [ "tel":phoneField.text ?? "", "newPass":pwdField.text ?? "", "confirmPass":repatField.text ?? "", "access_token":UserDefaults.standard.object(forKey: TokenKey) ?? "", "timestamp":Date.timeIntervalBetween1970AndReferenceDate ] Alamofire.request(URL_PwdForget, method: .post, parameters: param).responseJSON { (response) in guard let jsonDic = response.value as? NSDictionary else{ return } if jsonDic["code"] as? Int == 0 { HUD.flash(.labeledError(title: jsonDic["message"] as? String, subtitle: nil), delay: 1) return } self.navigationController?.popViewController(animated: true) } } }
mit
8612d7fbee2d4dceb4c28cfdfb1add07
33.2
111
0.589669
4.098535
false
false
false
false
mthistle/HockeyTweetSwift
HockeyTweetSwift/Models/Teams.swift
1
3040
// // Teams.swift // HockeyTweetSwift // // Created by Mark Thistle on 2014-07-13. // Copyright (c) 2014 Test. All rights reserved. // import Foundation class Teams: NSObject { var teamTLA = [ "NJD", "NYI", "NYR", "PHI", "PIT", "BOS", "BUF", "MTL", "OTT", "TOR", "ATL", "CAR", "FLA", "TBL", "WSH", "CHI", "CBJ", "DET", "NSH", "STL", "CGY", "COL", "EDM", "MIN", "VAN", "ANA", "DAL", "LAK", "PHX", "SJS"] var teamNames = [ "New Jersey Devils", "New York Islanders", "New York Rangers", "Philadelphia Flyers", "Pittsburgh Penguins", "Boston Bruins", "Buffalo Sabres", "Montreal Canadiens", "Ottawa Senators", "Toronto Maple Leafs", "Atlanta Thrashers", "Carolina Hurricanes", "Florida Panthers", "Tampa Bay Lightning", "Washington Capitals", "Chicago Blackhawks", "Columbus Blue Jackets", "Detroit Red Wings", "Nashville Predators", "St Louis Blues", "Calgary Flames", "Colorado Avalanche", "Edmonton Oilers", "Minnesota Wild", "Vancouver Canucks", "Anaheim Ducks", "Dallas Stars", "Los Angeles Kings", "Phoenix Coyotes", "San Jose Sharks"] // Initialize an empty dictionary so we have a starting point from which to // add values in the init call. var rosters = [String: Array<String>]() override init() { teamNames = sorted(teamNames, { s1, s2 in return s1 < s2 }) teamTLA = sorted(teamTLA, { s1, s2 in return s1 < s2 }) // TODO: Ok, need to convert from NS to Swift here // var rostersLoaded = true // if let path: String = NSBundle.mainBundle().pathForResource("players", ofType: "plist") { // let teams = NSDictionary(contentsOfFile: path) // //rosters = rostersFromTeams(teams["players"] as NSDictionary) // } else { // rostersLoaded = false // } // if !rostersLoaded { for team in teamTLA { rosters[team] = ["--"] } //} super.init() } func playersOnTeam(team: String) -> Array<String>! { //if let players: NSDictionary = rosters["players"] as? NSDictionary { // let ns_team: NSString = NSString(string: team) //for teamPlayers in players.objectForKey(ns_team) { //} //return nil //} return nil } func rostersFromTeams(teams: NSDictionary) -> Dictionary<String, Array<String>>! { var tmprosters: Dictionary<String, Array<String>> for team in teamTLA { } return nil } }
mit
5bc8b8da1970ec0387c1f386ca8c1b0b
24.771186
107
0.488816
3.828715
false
false
false
false
mnespor/AzureNotificationHubClient
Pod/Classes/TokenProvider.swift
1
1649
// // TokenProvider.swift // Pods // // Created by Matthew Nespor on 4/10/16. // // import Foundation class TokenProvider { internal var defaultTimeToExpireInMinutes = 20 private let endpoint: NSURL private let sharedAccessKey: String? private let sharedAccessKeyName: String? private let sharedSecret: String? private let sharedSecretIssuer: String? private let stsHostName: NSURL init?(connectionDictionary: [String: String]) { guard let endpoint = TokenProvider.tryUrl(connectionDictionary["endpoint"]) where endpoint.host != nil else { return nil } self.endpoint = endpoint guard let stsHostName = TokenProvider.tryUrl(connectionDictionary["stsendpoint"]) else { return nil } self.stsHostName = stsHostName self.sharedAccessKey = connectionDictionary["sharedaccesskey"] self.sharedAccessKeyName = connectionDictionary["sharedaccesskeyname"] self.sharedSecret = connectionDictionary["sharedsecretvalue"] self.sharedSecretIssuer = connectionDictionary["sharedsecretissuer"] if (sharedAccessKey == nil || sharedAccessKeyName == nil) && sharedSecret == nil { print("Security information is missing in connectionString.") return nil } } private static func tryUrl(string: String?) -> NSURL? { // swiftlint:disable opening_brace guard let string = string, url = NSURL(string: string) else { return nil } // swiftlint:enable opening_brace return url } }
apache-2.0
dc9db61ad43250f9b16e2dd49821ea11
27.431034
96
0.646452
4.864307
false
false
false
false
rugheid/Swift-MathEagle
MathEagle/Linear Algebra/Vector.swift
1
33689
// // Vector.swift // SwiftMath // // Created by Rugen Heidbuchel on 30/12/14. // Copyright (c) 2014 Jorestha Solutions. All rights reserved. // import Foundation import Accelerate /** A generic class representing a vector with the given type. */ open class Vector <T: MatrixCompatible> : ExpressibleByArrayLiteral, Equatable, Sequence, CustomStringConvertible { /** Returns a list of all elements of the vector. */ open var elements = [T]() /** Creates an empty vector. elements will be [], length will be 0. */ public init() {} /** Creates a vector with the given elements. - parameter elements: An array containing the elements of the vector. */ public init(_ elements: [T]) { self.elements = elements } /** Creates a vector from an array literal. */ public required init(arrayLiteral elements: T...) { self.elements = elements } /** Creates a vector with the given length using the given generator. The generator takes an Int representing the index of the element. These indices start at 0 and go to length - 1. - parameter length: The number of elements the vector should have. - parameter generator: The generator used to generate the elements. */ public init(length: Int, generator: (Int) -> T) { self.elements = (0..<length).map{ generator($0) } } /** Creates a vector of the given length filled with the given element. - parameter element: The element to fill the vector with. */ public convenience init(filledWith element: T, length: Int) { self.init(length: length, generator: { _ in element }) } /** Creates a random vector with the given length. The elements in the vector are generated with the random function of the vector's type T. - parameter length: The number of elements the vector should have. */ public convenience init(randomWithLength length: Int) { self.init(T.randomArray(length)) } /** Creates a random vector with the given length. The elements in the vector are generated with the randomIn function of the vector's type T. This means the generated values will lie within the given range. - parameter length: The number of elements the vector should have. - parameter range: The range in which the random generated elements may lie. */ public convenience init(randomWithLength length: Int, range: Range<T.RandomRangeType>) { self.init(length: length, generator: { _ in T.random(range) }) } /** Creates a random vector with the given length. The elements in the vector are generated with the randomIn function of the vector's type T. This means the generated values will lie within the given range. - parameter length: The number of elements the vector should have. - parameter range: The range in which the random generated elements may lie. */ public convenience init(randomWithLength length: Int, range: ClosedRange<T.RandomRangeType>) { self.init(length: length, generator: { _ in T.random(range) }) } /** Creates a random vector with the given length. The elements in the vector are generated with the randomIn function of the vector's type T. This means the generated values will lie within the given range. - parameter length: The number of elements the vector should have. - parameter range: The range in which the random generated elements may lie. */ public convenience init(randomWithLength length: Int, range: CountableRange<T.RandomCountableRangeType>) { self.init(length: length, generator: { _ in T.random(range) }) } /** Creates a random vector with the given length. The elements in the vector are generated with the randomIn function of the vector's type T. This means the generated values will lie within the given range. - parameter length: The number of elements the vector should have. - parameter range: The range in which the random generated elements may lie. */ public convenience init(randomWithLength length: Int, range: CountableClosedRange<T.RandomCountableRangeType>) { self.init(length: length, generator: { _ in T.random(range) }) } // MARK: Subscript Methods /** Returns or sets the element at the given index. - parameter index: The index of the element to get/set. */ open subscript(index: Int) -> T { get { if index < 0 || index >= self.length { NSException(name: NSExceptionName(rawValue: "Index out of bounds"), reason: "The index \(index) is out of bounds.", userInfo: nil).raise() } return self.elements[index] } set(newValue) { if index < -1 || index > self.length { NSException(name: NSExceptionName(rawValue: "Index out of bounds"), reason: "The index \(index) is out of bounds.", userInfo: nil).raise() } } } /** Returns the subvector at the given index range. - parameter indexRange: A range representing the indices of the subvector. */ open subscript(indexRange: CountableRange<Int>) -> Vector<T> { if indexRange.lowerBound < 0 { NSException(name: NSExceptionName(rawValue: "Lower index out of bounds"), reason: "The range's startIndex \(indexRange.lowerBound) is out of bounds.", userInfo: nil).raise() } if indexRange.upperBound >= self.length { NSException(name: NSExceptionName(rawValue: "Upper index out of bounds"), reason: "The range's endIndex is out of bounds.", userInfo: nil).raise() } var returnElements = [T]() for i in indexRange { returnElements.append(self.elements[i]) } return Vector(returnElements) } /** Returns the subvector at the given index range. - parameter indexRange: A range representing the indices of the subvector. */ open subscript(indexRange: CountableClosedRange<Int>) -> Vector<T> { if indexRange.lowerBound < 0 { NSException(name: NSExceptionName(rawValue: "Lower index out of bounds"), reason: "The range's startIndex \(indexRange.lowerBound) is out of bounds.", userInfo: nil).raise() } if indexRange.upperBound >= self.length { NSException(name: NSExceptionName(rawValue: "Upper index out of bounds"), reason: "The range's endIndex is out of bounds.", userInfo: nil).raise() } var returnElements = [T]() for i in indexRange { returnElements.append(self.elements[i]) } return Vector(returnElements) } // MARK: Sequence Type Adoption /** Returns a generator for the vector. */ open func makeIterator() -> VectorGenerator<T> { return VectorGenerator(vector: self) } // MARK: Basic Properties /** Returns a copy of the vector. */ open var copy: Vector<T> { return Vector(self.elements) } /** Returns a description of the vector. :example: [1, 2, 3] */ open var description: String { return self.elements.description } /** Returns the length, the number of elements. */ open var length: Int { return self.elements.count } /** Returns the 2-norm. This means sqrt(element_0^2 + element_1^2 + ... + element_n^2). */ open var norm: T.RealPowerType { if self.length == 0 { NSException(name: NSExceptionName(rawValue: "No elements"), reason: "A vector with no elements has no norm.", userInfo: nil).raise() } var sum = self.elements[0]*self.elements[0] for i in 1 ..< self.length { let element = self.elements[i] sum = sum + element*element } return root(sum, order: 2) } /** Returns the conjugate of the vector. This means every complex value a + bi is replaced by its conjugate a - bi. Non-complex values are left untouched. */ open var conjugate: Vector<T> { return vmap(self){ $0.conjugate } } // var maxElement: T { // // // } /** Returns whether the vector is empty. This means it doesn't contain any elements, so it's length equals zero. */ open var isEmpty: Bool { return self.length == 0 } /** Returns whether the vector contains only zeros. */ open var isZero: Bool { for element in self { if element != 0 { return false } } return true } // MARK: Operator Functions /** Returns the dot product with the given vector. This is the product of self as a row vector with the given vector as a column vector. The given vector has to be of the same type and length. - parameter vector: The vector to multiply with. - returns: A scalar of the same type as the two vectors. */ open func dotProduct(_ vector: Vector<T>) -> T { return vectorDotProduct(self, vector) } /** Returns the direct product with the given vector. This product is the product of self as a column vector with the given vector as a row vector. The two vectors need to be of the same type and length. - parameter vector: The vector to multiply with. - returns: A square matrix of the same type as the two vectors with size equal to the vector's length. */ open func directProduct(_ vector: Vector<T>) -> Matrix<T> { return vectorDirectProduct(self, vector) } } // MARK: Vector Equality /** Returns whether two vectors are equal. This means the vector's are of the same length and all elements at corresponding indices are equal. */ public func == <T: MatrixCompatible> (left: Vector<T>, right: Vector<T>) -> Bool { if left.length != right.length { return false } for i in 0 ..< left.length { if left[i] != right[i] { return false } } return true } // MARK: Vector Addition /** Returns the sum of the two given vectors. Both given vectors are left untouched. :exception: An exception is thrown when the two vectors are not of equal length. */ public func + <T: MatrixCompatible> (left: Vector<T>, right: Vector<T>) -> Vector<T> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The left vector's length (\(left.length)) is not equal to the right vector's length (\(right.length))", userInfo: nil).raise() } return vcombine(left, right){ $0 + $1 } } /** Returns the sum of the two given vectors. Both given vectors are left untouched. :exception: An exception is thrown when the two vectors are not of equal length. */ public func + (left: Vector<Float>, right: Vector<Float>) -> Vector<Float> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The left vector's length (\(left.length)) is not equal to the right vector's length (\(right.length))", userInfo: nil).raise() } // var elements = [Float](count: left.length, repeatedValue: 0) // // vDSP_vadd(left.elements, 1, right.elements, 1, &elements, 1, vDSP_Length(left.length)) // // return Vector(elements) var elements = right.elements cblas_saxpy(Int32(left.length), 1.0, left.elements, 1, &elements, 1) return Vector(elements) // var elements = right.elements // // catlas_saxpby(Int32(left.length), 1.0, left.elements, 1, 1.0, &elements, 1) // // return Vector(elements) } /** Returns the sum of the two given vectors. Both given vectors are left untouched. :exception: An exception is thrown when the two vectors are not of equal length. */ public func + (left: Vector<Double>, right: Vector<Double>) -> Vector<Double> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The left vector's length (\(left.length)) is not equal to the right vector's length (\(right.length))", userInfo: nil).raise() } // var elements = [Double](count: left.length, repeatedValue: 0) // // vDSP_vaddD(left.elements, 1, right.elements, 1, &elements, 1, vDSP_Length(left.length)) // // return Vector(elements) var elements = right.elements cblas_daxpy(Int32(left.length), 1.0, left.elements, 1, &elements, 1) return Vector(elements) // var elements = right.elements // // catlas_daxpby(Int32(left.length), 1.0, left.elements, 1, 1.0, &elements, 1) // // return Vector(elements) } //func + (left: Vector<Complex>, right: Vector<Complex>) -> Vector<Complex> { // // var elements = map(Array(count: left.length, repeatedValue: Complex(0, 0))){ DSPDoubleSplitComplex($0) } // // let l = map(left.elements){ $0.DSPDoubleSplitComplexValue } // let r = map(right.elements){ $0.DSPDoubleSplitComplexValue } // // vDSP_zvaddD(l, 1, r, 1, &elements, 1, vDSP_Length(left.length)) // // return Vector(map(elements){ Complex($0) }) //} // MARK: Vector Negation /** Returns the negation of the given vector. The given vector is left untouched. */ public prefix func - <T: MatrixCompatible> (vector: Vector<T>) -> Vector<T> { return vmap(vector){ -$0 } } /** Returns the negation of the given vector. The given vector is left untouched. */ public prefix func - (vector: Vector<Float>) -> Vector<Float> { // var elements = [Float](count: vector.length, repeatedValue: 0) // // vDSP_vneg(vector.elements, 1, &elements, 1, vDSP_Length(vector.length)) // // return Vector(elements) let returnVector = vector.copy cblas_sscal(Int32(vector.length), -1.0, &(returnVector.elements), 1) return returnVector } /** Returns the negation of the given vector. The given vector is left untouched. */ public prefix func - (vector: Vector<Double>) -> Vector<Double> { // var elements = [Double](count: vector.length, repeatedValue: 0) // // vDSP_vnegD(vector.elements, 1, &elements, 1, vDSP_Length(vector.length)) // // return Vector(elements) let returnVector = vector.copy cblas_dscal(Int32(vector.length), -1.0, &(returnVector.elements), 1) return returnVector } //prefix func - (vector: Vector<Complex>) -> Vector<Complex> { // // var elements = map(Array(count: vector.length, repeatedValue: Complex(0, 0))){ DSPDoubleSplitComplex($0) } // let v = map(vector.elements){ $0.DSPDoubleSplitComplexValue } // // vDSP_zvnegD(v, 1, &elements, 1, vDSP_Length(vector.length)) // // return Vector(map(elements){ Complex($0) }) //} // MARK: Vector Subtraction /** Returns the difference of the two given vectors. :exception: An exception is thrown when the two vectors are not of equal length. */ public func - <T: MatrixCompatible> (left: Vector<T>, right: Vector<T>) -> Vector<T> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The left vector's length (\(left.length)) is not equal to the right vector's length (\(right.length))", userInfo: nil).raise() } return vcombine(left, right){ $0 - $1 } } /** Returns the difference of the two given vectors. :exception: An exception is thrown when the two vectors are not of equal length. */ public func - (left: Vector<Float>, right: Vector<Float>) -> Vector<Float> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The left vector's length (\(left.length)) is not equal to the right vector's length (\(right.length))", userInfo: nil).raise() } // var elements = [Float](count: left.length, repeatedValue: 0) // // vDSP_vsub(right.elements, 1, left.elements, 1, &elements, 1, vDSP_Length(left.length)) // // return Vector(elements) var elements = left.elements cblas_saxpy(Int32(left.length), -1.0, right.elements, 1, &elements, 1) return Vector(elements) // var elements = Array(right.elements) // // catlas_saxpby(Int32(left.length), 1.0, left.elements, 1, -1.0, &elements, 1) // // return Vector(elements) } /** Returns the difference of the two given vectors. :exception: An exception is thrown when the two vectors are not of equal length. */ public func - (left: Vector<Double>, right: Vector<Double>) -> Vector<Double> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The left vector's length (\(left.length)) is not equal to the right vector's length (\(right.length))", userInfo: nil).raise() } // var elements = [Double](count: left.length, repeatedValue: 0) // // vDSP_vsubD(right.elements, 1, left.elements, 1, &elements, 1, vDSP_Length(left.length)) // // return Vector(elements) // var elements = Array(left.elements) // // cblas_daxpy(Int32(left.length), -1.0, right.elements, 1, &elements, 1) // // return Vector(elements) var elements = right.elements catlas_daxpby(Int32(left.length), 1.0, left.elements, 1, -1.0, &elements, 1) return Vector(elements) } // MARK: Vector Scalar Multiplication and Division /** Returns the product of the given scalar and the given vector. This means every element in the given vector is multiplied with the given scalar. The given vector is left untouched. */ public func * <T: MatrixCompatible> (scalar: T, vector: Vector<T>) -> Vector<T> { var elements = vector.elements for i in 0 ..< vector.length { elements[i] = elements[i] * scalar } return Vector(elements) } /** Returns the product of the given scalar and the given vector. This means every element in the given vector is multiplied with the given scalar. The given vector is left untouched. */ public func * (scalar: Float, vector: Vector<Float>) -> Vector<Float> { // var elements = [Float](count: vector.length, repeatedValue: 0) // // vDSP_vsmul(vector.elements, 1, [scalar], &elements, 1, vDSP_Length(vector.length)) // // return Vector(elements) var elements = vector.elements cblas_sscal(Int32(vector.length), scalar, &elements, 1) return Vector(elements) } /** Returns the product of the given scalar and the given vector. This means every element in the given vector is multiplied with the given scalar. The given vector is left untouched. */ public func * (scalar: Double, vector: Vector<Double>) -> Vector<Double> { // var elements = [Double](count: vector.length, repeatedValue: 0) // // vDSP_vsmulD(vector.elements, 1, [scalar], &elements, 1, vDSP_Length(vector.length)) // // return Vector(elements) var elements = vector.elements cblas_dscal(Int32(vector.length), scalar, &elements, 1) return Vector(elements) } /** Returns the product of the given scalar and the given vector. This means every element in the given vector is multiplied with the given scalar. The given vector is left untouched. */ public func * <T: MatrixCompatible> (vector: Vector<T>, scalar: T) -> Vector<T> { return scalar * vector } /** Returns the product of the given scalar and the given vector. This means every element in the given vector is multiplied with the given scalar. The given vector is left untouched. */ public func * (vector: Vector<Float>, scalar: Float) -> Vector<Float> { return scalar * vector } /** Returns the product of the given scalar and the given vector. This means every element in the given vector is multiplied with the given scalar. The given vector is left untouched. */ public func * (vector: Vector<Double>, scalar: Double) -> Vector<Double> { return scalar * vector } /** Returns the division of the given vector by the given scalar. This means every element in the given vector is divided by the given scalar. The given vector is left untouched. */ public func / <T: MatrixCompatible> (vector: Vector<T>, scalar: T) -> Vector<T> { var elements = vector.elements for i in 0 ..< vector.length { elements[i] = elements[i] / scalar } return Vector(elements) } /** Returns the division of the given vector by the given scalar. This means every element in the given vector is divided by the given scalar. The given vector is left untouched. */ public func / (vector: Vector<Float>, scalar: Float) -> Vector<Float> { var elements = [Float](repeating: 0, count: vector.length) vDSP_vsdiv(vector.elements, 1, [scalar], &elements, 1, vDSP_Length(vector.length)) return Vector(elements) // var elements = vector.copy.elements // // cblas_sscal(Int32(vector.length), 1/scalar, &elements, 1) // // return Vector(elements) } /** Returns the division of the given vector by the given scalar. This means every element in the given vector is divided by the given scalar. The given vector is left untouched. */ public func / (vector: Vector<Double>, scalar: Double) -> Vector<Double> { var elements = [Double](repeating: 0, count: vector.length) vDSP_vsdivD(vector.elements, 1, [scalar], &elements, 1, vDSP_Length(vector.length)) return Vector(elements) // var elements = vector.copy.elements // // cblas_dscal(Int32(vector.length), 1/scalar, &elements, 1) // // return Vector(elements) } // MARK: Vector Dot Product /** Returns the dot product of the two given vectors. This is equal to left[0]*right[0] + ... + left[n]*right[n] for two vectors of length n+1. :exception: An exception will be thrown when the two vectors are not of equal length. */ public func vectorDotProduct <T: MatrixCompatible> (_ left: Vector<T>, _ right: Vector<T>) -> T { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The two given vectors have uneqaul lengths.", userInfo: nil).raise() } return sum(vcombine(left, right){ $0 * $1 }) } /** Returns the dot product of the two given vectors. This is equal to left[0]*right[0] + ... + left[n]*right[n] for two vectors of length n+1. :exception: An exception will be thrown when the two vectors are not of equal length. */ public func vectorDotProduct(_ left: Vector<Float>, _ right: Vector<Float>) -> Float { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The two given vectors have uneqaul lengths.", userInfo: nil).raise() } var result: Float = 0 vDSP_dotpr(left.elements, 1, right.elements, 1, &result, vDSP_Length(left.length)) return result } /** Returns the dot product of the two given vectors. This is equal to left[0]*right[0] + ... + left[n]*right[n] for two vectors of length n+1. :exception: An exception will be thrown when the two vectors are not of equal length. */ public func vectorDotProduct(_ left: Vector<Double>, _ right: Vector<Double>) -> Double { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The two given vectors have uneqaul lengths.", userInfo: nil).raise() } var result: Double = 0 vDSP_dotprD(left.elements, 1, right.elements, 1, &result, vDSP_Length(left.length)) return result } // MARK: Vector Direct Product /** Returns the direct product of the two given vectors. This is the product of left as a column vector and right as a row vector. The result is a square matrix with size equal to the length of the two vectors. :exception: An exception will be thrown when the two given vectors are not of equal length. */ public func * <T: MatrixCompatible> (left: Vector<T>, right: Vector<T>) -> Matrix<T> { return vectorDirectProduct(left, right) } /** Returns the direct product of the two given vectors. This is the product of left as a column vector and right as a row vector. The result is a square matrix with size equal to the length of the two vectors. :exception: An exception will be thrown when the two given vectors are not of equal length. */ public func * (left: Vector<Float>, right: Vector<Float>) -> Matrix<Float> { return vectorDirectProduct(left, right) } /** Returns the direct product of the two given vectors. This is the product of left as a column vector and right as a row vector. The result is a square matrix with size equal to the length of the two vectors. :exception: An exception will be thrown when the two given vectors are not of equal length. */ public func * (left: Vector<Double>, right: Vector<Double>) -> Matrix<Double> { return vectorDirectProduct(left, right) } /** Returns the direct product of the two given vectors. This is the product of left as a column vector and right as a row vector. The result is a square matrix with size equal to the length of the two vectors. :exception: An exception will be thrown when the two given vectors are not of equal length. */ public func vectorDirectProduct <T: MatrixCompatible> (_ left: Vector<T>, _ right: Vector<T>) -> Matrix<T> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The lengths of the two vectors are not equal.", userInfo: nil).raise() } return Matrix(elementsList: left.elements, columns: 1) * Matrix(elementsList: right.elements, rows: 1) } /** Returns the direct product of the two given vectors. This is the product of left as a column vector and right as a row vector. The result is a square matrix with size equal to the length of the two vectors. :exception: An exception will be thrown when the two given vectors are not of equal length. */ public func vectorDirectProduct(_ left: Vector<Float>, _ right: Vector<Float>) -> Matrix<Float> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The lengths of the two vectors are not equal.", userInfo: nil).raise() } if left.length == 0 { return Matrix<Float>() } var elements = [Float](repeating: 0, count: left.length*left.length) cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(left.length), Int32(left.length), 1, 1, left.elements, 1, right.elements, Int32(left.length), 1, &elements, Int32(left.length)) return Matrix(elementsList: elements, rows: left.length) } /** Returns the direct product of the two given vectors. This is the product of left as a column vector and right as a row vector. The result is a square matrix with size equal to the length of the two vectors. :exception: An exception will be thrown when the two given vectors are not of equal length. */ public func vectorDirectProduct(_ left: Vector<Double>, _ right: Vector<Double>) -> Matrix<Double> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The lengths of the two vectors are not equal.", userInfo: nil).raise() } if left.length == 0 { return Matrix<Double>() } var elements = [Double](repeating: 0, count: left.length*left.length) cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(left.length), Int32(left.length), 1, 1, left.elements, 1, right.elements, Int32(left.length), 1, &elements, Int32(left.length)) return Matrix(elementsList: elements, rows: left.length) } // MARK: Vector Functional Methods /** Returns a new vector created by using the given transform on every element of the given vector. - parameter vector: The vector to map. - parameter transform: The function used to transform the elements in the given vector. */ public func vmap <T: MatrixCompatible, U: MatrixCompatible> (_ vector: Vector<T>, transform: (T) -> U) -> Vector<U> { return Vector(vector.elements.map(transform)) } /** Returns a single value created by reducing the given vector with the given combine function. First the combine function is called on the given initial value and the first element of the given vector. The yielded value is then used to combine with the second element of the given vector, and so on. - parameter vector: The vector to reduce. - parameter initial: The initial vector to use in the reduction proces. - parameter combine: The function used to combine two values and reduce the vector. */ public func vreduce <T: MatrixCompatible, U> (_ vector: Vector<T>, initial: U, combine: (U, T) -> U) -> U { return vector.elements.reduce(initial, combine) } /** Returns a new vector created by combining the two given vectors element by element. This means the two first elements are combined to form the first element of the new vector. The two second elements are combined to form the second element of the new vector, and so on. - parameter left: The first vector in the combination. The elements from this vector will be passed as first element in the combine function. - parameter right: The second vector in the combination. The elements from this vector will be passed as second element in the combine function. - parameter combine: The function used to combine according elements from the two vectors. :exception: An exception will be thrown when the two given vectors are not of equal length. */ public func vcombine <T: MatrixCompatible, U: MatrixCompatible, V: MatrixCompatible> (_ left: Vector<T>, _ right: Vector<U>, combine: (T, U) -> V) -> Vector<V> { if left.length != right.length { NSException(name: NSExceptionName(rawValue: "Unequal lengths"), reason: "The lengths of the two vectors are not equal.", userInfo: nil).raise() } var vectorElements = [V]() for i in 0 ..< left.length { vectorElements.append(combine(left[i], right[i])) } return Vector(vectorElements) } // MARK: Vector Sorting /** Sorts the given vector in place. - parameter vector: The vector to sort in place. - parameter ascending: True means the vector should be sorted in ascending order, otherwise it's sorted in descending order. */ public func vsort <T: MatrixCompatible> (_ vector: inout Vector<T>, ascending: Bool = true) { vector.elements.sort { ascending ? $0 < $1 : $0 > $1 } } // MARK: - Additional Structs // MARK: - VectorGenerator /** A struct representing a vector generator. This is used to iterate over the vector. */ public struct VectorGenerator <T: MatrixCompatible> : IteratorProtocol { /** The generator of the elements array of the vector. */ fileprivate var generator: IndexingIterator<Array<T>> /** Creates a new generator with the given vector. - parameter vector: The vector the generator should iterate over. */ public init(vector: Vector<T>) { self.generator = vector.elements.makeIterator() } /** Returns the next element in the vector if there is any. Otherwise nil is returned. */ public mutating func next() -> T? { return self.generator.next() } }
mit
aef61e4d60382a453e794be2d236462e
29.35045
207
0.622429
4.242947
false
false
false
false
bazelbuild/tulsi
src/Tulsi/Announcement.swift
1
2707
// Copyright 2022 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Provides a model for announcements shown in the announcement banner. struct Announcement: Codable { var id: String var bannerMessage: String var cliMessage: String var link: String? var shouldAppearAtTopOfCLIOutput: Bool enum CodingKeys: String, CodingKey { case id = "announcementId" case bannerMessage case cliMessage case link case shouldAppearAtTopOfCLIOutput } // MARK: - Instance methods func createBanner() -> AnnouncementBanner { return AnnouncementBanner(announcement: self) } func createCLIOutput() -> String { var linkText = "" if let link = link { linkText = "Link: \(link)\n" } let mainTextContent = """ \(cliMessage) \(linkText) To disable this message, please run generate_xcodeproj.sh --mark-read \(id) """ let contentSeparator = "**************************" if shouldAppearAtTopOfCLIOutput { return """ \(contentSeparator) \(mainTextContent) \(contentSeparator) """ } else { return """ \(contentSeparator) \(mainTextContent) """ } } func hasBeenDismissed() -> Bool { return UserDefaults.standard.bool(forKey: id) } func recordDismissal() { UserDefaults.standard.set(true, forKey: id) } // MARK: - Static methods static func getAllAnnouncements() throws -> [Announcement] { guard let jsonPath = Bundle.main.url(forResource: "AnnouncementConfig", withExtension: "json") else { throw TulsiError(errorMessage: "Failed to locate configuration file for announcements") } let data = try Data(contentsOf: jsonPath) let decoder = JSONDecoder() return try decoder.decode([Announcement].self, from: data) } static func getNextUnreadAnnouncement() throws -> Announcement? { return try getAllAnnouncements().first(where: {!$0.hasBeenDismissed()}) } static func loadAnnouncement(byId id: String) throws -> Announcement? { return try getAllAnnouncements().first(where: {$0.id == id}) } }
apache-2.0
d26741ea5adddd9234040fee11fcac75
25.028846
98
0.670484
4.481788
false
false
false
false
allanlykkechristensen/macos-activity-timer
Activity TimerTests/PreferencesModelTests.swift
1
2685
// // PreferencesModelTests.swift // Activity TimerTests // // Created by Allan Lykke Christensen on 29/10/2017. // Copyright © 2017 Allan Lykke Christensen. All rights reserved. // import XCTest @testable import Activity_Timer class PreferencesModelTests: XCTestCase { var unitUnderTest: PreferencesModel! override func setUp() { super.setUp() unitUnderTest = PreferencesModel() } override func tearDown() { super.tearDown() unitUnderTest = nil } func test_reset_returnDefaultSelectedTime() { // Given unitUnderTest.reset() // When let time = unitUnderTest.selectedTime // Then XCTAssert(Double(time) == 360.0) } func test_reset_returnZeroHours() { // Given unitUnderTest.reset() // When let hours = unitUnderTest.selectedHours // Then XCTAssert(Double(hours) == 0) } func test_reset_returnSixMinutes() { // Given unitUnderTest.reset() // When let minutes = unitUnderTest.selectedMinutes // Then XCTAssert(Double(minutes) == 6) } func test_reset_returnZeroSeconds() { // Given unitUnderTest.reset() // When let seconds = unitUnderTest.selectedSeconds // Then XCTAssert(Double(seconds) == 0) } func test_setSelectedTimeOneHourTenMinutesFifteenSeconds_returnSelectedTime4215() { // Given unitUnderTest.selectedTime = (60*60)+(60*10)+(15) // When let time = unitUnderTest.selectedTime // Then XCTAssert(Double(time) == 4215.0) } func test_setSelectedTimeOneHourTenMinutesFifteenSeconds_return1Hour() { // Given unitUnderTest.selectedTime = (60*60)+(60*10)+(15) // When let hours = unitUnderTest.selectedHours // Then XCTAssert(hours == 1) } func test_setSelectedTimeOneHourTenMinutesFifteenSeconds_return10Minutes() { // Given unitUnderTest.selectedTime = (60*60)+(60*10)+(15) // When let minutes = unitUnderTest.selectedMinutes // Then XCTAssert(Double(minutes) == 10) } func test_setSelectedTimeOneHourTenMinutesFifteenSeconds_return15Seconds() { // Given unitUnderTest.selectedTime = (60*60)+(60*10)+(15) // When let seconds = unitUnderTest.selectedSeconds // Then XCTAssert(Double(seconds) == 15) } }
mit
4fac1cf094084058603ad2a0716af8d6
22.752212
87
0.5693
4.675958
false
true
false
false
maxbritto/cours-ios11-swift4
swift_4_cours_complet.playground/Pages/Extensions.xcplaygroundpage/Contents.swift
1
426
//: [< Sommaire](Sommaire) /*: # Extensions --- ### Maxime Britto - Swift 4 */ extension Int { func getDigitsCount() -> Int { var valueCopy = self var digitsCount = 1 while valueCopy >= 10 { valueCopy = valueCopy / 10 digitsCount = digitsCount + 1 } return digitsCount } } let score = 0 score.getDigitsCount() /*: [< Sommaire](Sommaire) */
apache-2.0
d2bc3b1b846ebf41529dd7d0ad9c0b2b
13.2
41
0.535211
3.803571
false
false
false
false
dtrauger/Charts
Source/Charts/Charts/PieChartView.swift
1
19031
// // PieChartView.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// View that represents a pie chart. Draws cake like slices. open class PieChartView: PieRadarChartViewBase { /// rect object that represents the bounds of the piechart, needed for drawing the circle fileprivate var _circleBox = CGRect() /// flag indicating if entry labels should be drawn or not fileprivate var _drawEntryLabelsEnabled = true /// array that holds the width of each pie-slice in degrees fileprivate var _drawAngles = [CGFloat]() /// array that holds the absolute angle in degrees of each slice fileprivate var _absoluteAngles = [CGFloat]() /// if true, the hole inside the chart will be drawn fileprivate var _drawHoleEnabled = true fileprivate var _holeColor: NSUIColor? = NSUIColor.white /// Sets the color the entry labels are drawn with. fileprivate var _entryLabelColor: NSUIColor? = NSUIColor.white /// Sets the font the entry labels are drawn with. fileprivate var _entryLabelFont: NSUIFont? = NSUIFont(name: "HelveticaNeue", size: 13.0) /// if true, the hole will see-through to the inner tips of the slices fileprivate var _drawSlicesUnderHoleEnabled = false /// if true, the values inside the piechart are drawn as percent values fileprivate var _usePercentValuesEnabled = false /// variable for the text that is drawn in the center of the pie-chart fileprivate var _centerAttributedText: NSAttributedString? /// the offset on the x- and y-axis the center text has in dp. fileprivate var _centerTextOffset: CGPoint = CGPoint() /// indicates the size of the hole in the center of the piechart /// /// **default**: `0.5` fileprivate var _holeRadiusPercent = CGFloat(0.5) fileprivate var _transparentCircleColor: NSUIColor? = NSUIColor(white: 1.0, alpha: 105.0/255.0) /// the radius of the transparent circle next to the chart-hole in the center fileprivate var _transparentCircleRadiusPercent = CGFloat(0.55) /// if enabled, centertext is drawn fileprivate var _drawCenterTextEnabled = true fileprivate var _centerTextRadiusPercent: CGFloat = 1.0 /// maximum angle for this pie fileprivate var _maxAngle: CGFloat = 360.0 public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) _xAxis = nil self.highlighter = PieHighlighter(chart: self) } open override func draw(_ rect: CGRect) { super.draw(rect) if _data === nil { return } let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } renderer!.drawData(context: context) if (valuesToHighlight()) { renderer!.drawHighlighted(context: context, indices: _indicesToHighlight) } renderer!.drawExtras(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) drawDescription(context: context) drawMarkers(context: context) } internal override func calculateOffsets() { super.calculateOffsets() // prevent nullpointer when no data set if _data === nil { return } let radius = diameter / 2.0 let c = self.centerOffsets let shift = (data as? PieChartData)?.dataSet?.selectionShift ?? 0.0 // create the circle box that will contain the pie-chart (the bounds of the pie-chart) _circleBox.origin.x = (c.x - radius) + shift _circleBox.origin.y = (c.y - radius) + shift _circleBox.size.width = diameter - shift * 2.0 _circleBox.size.height = diameter - shift * 2.0 } internal override func calcMinMax() { calcAngles() } open override func getMarkerPosition(highlight: Highlight) -> CGPoint { let center = self.centerCircleBox var r = self.radius var off = r / 10.0 * 3.6 if self.isDrawHoleEnabled { off = (r - (r * self.holeRadiusPercent)) / 2.0 } r -= off // offset to keep things inside the chart let rotationAngle = self.rotationAngle let entryIndex = Int(highlight.x) // offset needed to center the drawn text in the slice let offset = drawAngles[entryIndex] / 2.0 // calculate the text position let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[entryIndex] - offset) * CGFloat(_animator.phaseY)) * ChartUtils.Math.FDEG2RAD) + center.x) let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[entryIndex] - offset) * CGFloat(_animator.phaseY)) * ChartUtils.Math.FDEG2RAD) + center.y) return CGPoint(x: x, y: y) } /// calculates the needed angles for the chart slices fileprivate func calcAngles() { _drawAngles = [CGFloat]() _absoluteAngles = [CGFloat]() guard let data = _data else { return } let entryCount = data.entryCount _drawAngles.reserveCapacity(entryCount) _absoluteAngles.reserveCapacity(entryCount) let yValueSum = (_data as! PieChartData).yValueSum var dataSets = data.dataSets var cnt = 0 for i in 0 ..< data.dataSetCount { let set = dataSets[i] let entryCount = set.entryCount for j in 0 ..< entryCount { guard let e = set.entryForIndex(j) else { continue } _drawAngles.append(calcAngle(value: abs(e.y), yValueSum: yValueSum)) if cnt == 0 { _absoluteAngles.append(_drawAngles[cnt]) } else { _absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt]) } cnt += 1 } } } /// Checks if the given index is set to be highlighted. open func needsHighlight(index: Int) -> Bool { // no highlight if !valuesToHighlight() { return false } for i in 0 ..< _indicesToHighlight.count { // check if the xvalue for the given dataset needs highlight if Int(_indicesToHighlight[i].x) == index { return true } } return false } /// calculates the needed angle for a given value fileprivate func calcAngle(_ value: Double) -> CGFloat { return calcAngle(value: value, yValueSum: (_data as! PieChartData).yValueSum) } /// calculates the needed angle for a given value fileprivate func calcAngle(value: Double, yValueSum: Double) -> CGFloat { return CGFloat(value) / CGFloat(yValueSum) * _maxAngle } /// This will throw an exception, PieChart has no XAxis object. open override var xAxis: XAxis { fatalError("PieChart has no XAxis") } open override func indexForAngle(_ angle: CGFloat) -> Int { // take the current angle of the chart into consideration let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle) for i in 0 ..< _absoluteAngles.count { if _absoluteAngles[i] > a { return i } } return -1 // return -1 if no index found } /// - returns: The index of the DataSet this x-index belongs to. open func dataSetIndexForIndex(_ xValue: Double) -> Int { var dataSets = _data?.dataSets ?? [] for i in 0 ..< dataSets.count { if (dataSets[i].entryForXValue(xValue, closestToY: Double.nan) !== nil) { return i } } return -1 } /// - returns: An integer array of all the different angles the chart slices /// have the angles in the returned array determine how much space (of 360°) /// each slice takes open var drawAngles: [CGFloat] { return _drawAngles } /// - returns: The absolute angles of the different chart slices (where the /// slices end) open var absoluteAngles: [CGFloat] { return _absoluteAngles } /// The color for the hole that is drawn in the center of the PieChart (if enabled). /// /// - note: Use holeTransparent with holeColor = nil to make the hole transparent.* open var holeColor: NSUIColor? { get { return _holeColor } set { _holeColor = newValue setNeedsDisplay() } } /// if true, the hole will see-through to the inner tips of the slices /// /// **default**: `false` open var drawSlicesUnderHoleEnabled: Bool { get { return _drawSlicesUnderHoleEnabled } set { _drawSlicesUnderHoleEnabled = newValue setNeedsDisplay() } } /// - returns: `true` if the inner tips of the slices are visible behind the hole, `false` if not. open var isDrawSlicesUnderHoleEnabled: Bool { return drawSlicesUnderHoleEnabled } /// `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot open var drawHoleEnabled: Bool { get { return _drawHoleEnabled } set { _drawHoleEnabled = newValue setNeedsDisplay() } } /// - returns: `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot open var isDrawHoleEnabled: Bool { get { return drawHoleEnabled } } /// the text that is displayed in the center of the pie-chart open var centerText: String? { get { return self.centerAttributedText?.string } set { var attrString: NSMutableAttributedString? if newValue == nil { attrString = nil } else { #if os(OSX) let paragraphStyle = NSParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle #else let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle #endif paragraphStyle.lineBreakMode = NSLineBreakMode.byTruncatingTail paragraphStyle.alignment = .center attrString = NSMutableAttributedString(string: newValue!) attrString?.setAttributes(convertToOptionalNSAttributedStringKeyDictionary([ convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): NSUIColor.black, convertFromNSAttributedStringKey(NSAttributedString.Key.font): NSUIFont.systemFont(ofSize: 12.0), convertFromNSAttributedStringKey(NSAttributedString.Key.paragraphStyle): paragraphStyle ]), range: NSMakeRange(0, attrString!.length)) } self.centerAttributedText = attrString } } /// the text that is displayed in the center of the pie-chart open var centerAttributedText: NSAttributedString? { get { return _centerAttributedText } set { _centerAttributedText = newValue setNeedsDisplay() } } /// Sets the offset the center text should have from it's original position in dp. Default x = 0, y = 0 open var centerTextOffset: CGPoint { get { return _centerTextOffset } set { _centerTextOffset = newValue setNeedsDisplay() } } /// `true` if drawing the center text is enabled open var drawCenterTextEnabled: Bool { get { return _drawCenterTextEnabled } set { _drawCenterTextEnabled = newValue setNeedsDisplay() } } /// - returns: `true` if drawing the center text is enabled open var isDrawCenterTextEnabled: Bool { get { return drawCenterTextEnabled } } internal override var requiredLegendOffset: CGFloat { return _legend.font.pointSize * 2.0 } internal override var requiredBaseOffset: CGFloat { return 0.0 } open override var radius: CGFloat { return _circleBox.width / 2.0 } /// - returns: The circlebox, the boundingbox of the pie-chart slices open var circleBox: CGRect { return _circleBox } /// - returns: The center of the circlebox open var centerCircleBox: CGPoint { return CGPoint(x: _circleBox.midX, y: _circleBox.midY) } /// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart) /// /// **default**: 0.5 (50%) (half the pie) open var holeRadiusPercent: CGFloat { get { return _holeRadiusPercent } set { _holeRadiusPercent = newValue setNeedsDisplay() } } /// The color that the transparent-circle should have. /// /// **default**: `nil` open var transparentCircleColor: NSUIColor? { get { return _transparentCircleColor } set { _transparentCircleColor = newValue setNeedsDisplay() } } /// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart) /// /// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default open var transparentCircleRadiusPercent: CGFloat { get { return _transparentCircleRadiusPercent } set { _transparentCircleRadiusPercent = newValue setNeedsDisplay() } } /// set this to true to draw the enrty labels into the pie slices @available(*, deprecated, message: "Use `drawEntryLabelsEnabled` instead.") open var drawSliceTextEnabled: Bool { get { return drawEntryLabelsEnabled } set { drawEntryLabelsEnabled = newValue } } /// - returns: `true` if drawing entry labels is enabled, `false` ifnot @available(*, deprecated, message: "Use `isDrawEntryLabelsEnabled` instead.") open var isDrawSliceTextEnabled: Bool { get { return isDrawEntryLabelsEnabled } } /// The color the entry labels are drawn with. open var entryLabelColor: NSUIColor? { get { return _entryLabelColor } set { _entryLabelColor = newValue setNeedsDisplay() } } /// The font the entry labels are drawn with. open var entryLabelFont: NSUIFont? { get { return _entryLabelFont } set { _entryLabelFont = newValue setNeedsDisplay() } } /// Set this to true to draw the enrty labels into the pie slices open var drawEntryLabelsEnabled: Bool { get { return _drawEntryLabelsEnabled } set { _drawEntryLabelsEnabled = newValue setNeedsDisplay() } } /// - returns: `true` if drawing entry labels is enabled, `false` ifnot open var isDrawEntryLabelsEnabled: Bool { get { return drawEntryLabelsEnabled } } /// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent. open var usePercentValuesEnabled: Bool { get { return _usePercentValuesEnabled } set { _usePercentValuesEnabled = newValue setNeedsDisplay() } } /// - returns: `true` if drawing x-values is enabled, `false` ifnot open var isUsePercentValuesEnabled: Bool { get { return usePercentValuesEnabled } } /// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole open var centerTextRadiusPercent: CGFloat { get { return _centerTextRadiusPercent } set { _centerTextRadiusPercent = newValue setNeedsDisplay() } } /// The max angle that is used for calculating the pie-circle. /// 360 means it's a full pie-chart, 180 results in a half-pie-chart. /// **default**: 360.0 open var maxAngle: CGFloat { get { return _maxAngle } set { _maxAngle = newValue if _maxAngle > 360.0 { _maxAngle = 360.0 } if _maxAngle < 90.0 { _maxAngle = 90.0 } } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
apache-2.0
ae545277d662a6bbe10739b4faa108e5
27.276374
189
0.568576
5.248207
false
false
false
false
mozilla-mobile/firefox-ios
content-blocker-lib-ios/src/TrackingProtectionPageStats.swift
2
8525
// 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 Shared struct TPPageStats { var domains: [BlocklistCategory: Set<String>] var total: Int { var total = 0 domains.forEach { total += $0.1.count } return total } init() { domains = [BlocklistCategory: Set<String>]() } private init(domains: [BlocklistCategory: Set<String>], blocklistName: BlocklistCategory, host: String) { self.domains = domains if self.domains[blocklistName] == nil { self.domains[blocklistName] = Set<String>() } self.domains[blocklistName]?.insert(host) } func create(matchingBlocklist blocklistName: BlocklistCategory, host: String) -> TPPageStats { return TPPageStats(domains: domains, blocklistName: blocklistName, host: host) } } class TPStatsBlocklistChecker { static let shared = TPStatsBlocklistChecker() // Initialized async, is non-nil when ready to be used. private var blockLists: TPStatsBlocklists? func isBlocked(url: URL, mainDocumentURL: URL) -> Deferred<BlocklistCategory?> { let deferred = Deferred<BlocklistCategory?>() guard let blockLists = blockLists, let host = url.host, !host.isEmpty else { // TP Stats init isn't complete yet deferred.fill(nil) return deferred } guard let domain = url.baseDomain, let docDomain = mainDocumentURL.baseDomain, domain != docDomain else { deferred.fill(nil) return deferred } // Make a copy on the main thread let safelistRegex = ContentBlocker.shared.safelistedDomains.domainRegex DispatchQueue.global().async { // Return true in the Deferred if the domain could potentially be blocked deferred.fill(blockLists.urlIsInList(url, mainDocumentURL: mainDocumentURL, safelistedDomains: safelistRegex)) } return deferred } func startup() { DispatchQueue.global().async { let parser = TPStatsBlocklists() parser.load() DispatchQueue.main.async { self.blockLists = parser } } } } // The 'unless-domain' and 'if-domain' rules use wildcard expressions, convert this to regex. func wildcardContentBlockerDomainToRegex(domain: String) -> String? { struct Memo { static var domains = [String: String]() } if let memoized = Memo.domains[domain] { return memoized } // Convert the domain exceptions into regular expressions. var regex = domain + "$" if regex.first == "*" { regex = "." + regex } regex = regex.replacingOccurrences(of: ".", with: "\\.") Memo.domains[domain] = regex return regex } class TPStatsBlocklists { class Rule { let regex: String let loadType: LoadType let resourceType: ResourceType let domainExceptions: [String]? let list: BlocklistCategory init(regex: String, loadType: LoadType, resourceType: ResourceType, domainExceptions: [String]?, list: BlocklistCategory) { self.regex = regex self.loadType = loadType self.resourceType = resourceType self.domainExceptions = domainExceptions self.list = list } } private var blockRules = [String: [Rule]]() enum LoadType { case all case thirdParty } enum ResourceType { case all case font } func load() { // All rules have this prefix on the domain to match. let standardPrefix = "^https?://([^/]+\\.)?" // Use the strict list of files, as it is the complete list of rules, // keeping in mind the stats can't distinguish block vs cookie-block, // only that an url did or didn't match. for blockListFile in [ BlocklistFileName.advertisingURLs, BlocklistFileName.analyticsURLs, BlocklistFileName.socialURLs, BlocklistFileName.cryptomining, BlocklistFileName.fingerprinting, ] { let list: [[String: AnyObject]] do { guard let path = Bundle.main.path(forResource: blockListFile.filename, ofType: "json") else { assertionFailure("Blocklists: bad file path.") return } let json = try Data(contentsOf: URL(fileURLWithPath: path)) guard let data = try JSONSerialization.jsonObject(with: json, options: []) as? [[String: AnyObject]] else { assertionFailure("Blocklists: bad JSON cast.") return } list = data } catch { assertionFailure("Blocklists: \(error.localizedDescription)") return } for rule in list { guard let trigger = rule["trigger"] as? [String: AnyObject], let filter = trigger["url-filter"] as? String else { assertionFailure("Blocklists error: Rule has unexpected format.") continue } guard let loc = filter.range(of: standardPrefix) else { assert(false, "url-filter code needs updating for new list format") return } let baseDomain = String(filter[loc.upperBound...]).replacingOccurrences(of: "\\.", with: ".") assert(!baseDomain.isEmpty) // Sanity check for the lists. ["*", "?", "+"].forEach { x in // This will only happen on debug assert(!baseDomain.contains(x), "No wildcards allowed in baseDomain") } let domainExceptionsRegex = (trigger["unless-domain"] as? [String])?.compactMap { domain in return wildcardContentBlockerDomainToRegex(domain: domain) } // Only "third-party" is supported; other types are not used in our block lists. let loadTypes = trigger["load-type"] as? [String] ?? [] let loadType = loadTypes.contains("third-party") ? LoadType.thirdParty : .all // Only "font" is supported; other types are not used in our block lists. let resourceTypes = trigger["resource-type"] as? [String] ?? [] let resourceType = resourceTypes.contains("font") ? ResourceType.font : .all let category = BlocklistCategory.fromFile(blockListFile) let rule = Rule(regex: filter, loadType: loadType, resourceType: resourceType, domainExceptions: domainExceptionsRegex, list: category) blockRules[baseDomain] = (blockRules[baseDomain] ?? []) + [rule] } } } func urlIsInList(_ url: URL, mainDocumentURL: URL, safelistedDomains: [String]) -> BlocklistCategory? { let resourceString = url.absoluteString guard let firstPartyDomain = mainDocumentURL.baseDomain, let baseDomain = url.baseDomain, let rules = blockRules[baseDomain] else { return nil } domainSearch: for rule in rules { // First, test the top-level filters to see if this URL might be blocked. if resourceString.range(of: rule.regex, options: .regularExpression) != nil { // Check the domain exceptions. If a domain exception matches, this filter does not apply. for domainRegex in (rule.domainExceptions ?? []) { if firstPartyDomain.range(of: domainRegex, options: .regularExpression) != nil { continue domainSearch } } // Check the safelist. if let baseDomain = url.baseDomain, !safelistedDomains.isEmpty { for ignoreDomain in safelistedDomains { if baseDomain.range(of: ignoreDomain, options: .regularExpression) != nil { return nil } } } return rule.list } } return nil } }
mpl-2.0
b4409bf91d9236942dc482871b49bb8f
35.904762
151
0.574545
4.965055
false
false
false
false
zixun/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/View/CCocoaChinaWebView/ZXHighlightWebView.swift
1
5176
// // ZXHighlightWebView.swift // CocoaChinaPlus // // Created by zixun on 17/1/23. // Copyright © 2017年 zixun. All rights reserved. // import Foundation import Foundation import MBProgressHUD public enum ZXHighlightStyle : String { case Agate = "agate" case Androidstudio = "androidstudio" case Arta = "arta" case Ascetic = "ascetic" case AtelierCaveDark = "atelier-cave.dark" case AtelierCaveLight = "atelier-cave.light" case AtelierDuneDark = "atelier-dune.dark" case AtelierDuneLight = "atelier-dune.light" case AtelierEstuaryDark = "atelier-estuary.dark" case AtelierEstuaryLight = "atelier-estuary.light" case AtelierForestDark = "atelier-forest.dark" case AtelierForestLight = "atelier-forest.light" case AtelierHeathDark = "atelier-heath.dark" case AtelierHeathLight = "atelier-heath.light" case AtelierLakesideDark = "atelier-lakeside.dark" case AtelierLakesideLight = "atelier-lakeside.light" case AtelierPlateauDark = "atelier-plateau.dark" case AtelierPlateauLight = "atelier-plateau.light" case AtelierSavannaDark = "atelier-savanna.dark" case AtelierSavannaLight = "atelier-savanna.light" case AtelierSeasideDark = "atelier-seaside.dark" case AtelierSeasideLight = "atelier-seaside.light" case AtelierSulphurpoolDark = "atelier-sulphurpool.dark" case AtelierSulphurpoolLight = "atelier-sulphurpool.light" case BrownPaper = "brown_paper" case CodepenEmbed = "codepen-embed" case ColorBrewer = "color-brewer" case Dark = "dark" case Darkula = "darkula" case Default = "default" case Docco = "docco" case Far = "far" case Foundation = "foundation" case GithubGist = "github-gist" case Github = "github" case Googlecode = "googlecode" case Grayscale = "grayscale" case Hopscotch = "hopscotch" case Hybrid = "hybrid" case Idea = "idea" case IrBlack = "ir_black" case KimbieDark = "kimbie.dark" case KimbieLight = "kimbie.light" case Magula = "magula" case MonoBlue = "mono-blue" case Monokai = "monokai" case MonokaiSublime = "monokai_sublime" case Obsidian = "obsidian" case ParaisoDark = "paraiso.dark" case ParaisoLight = "paraiso.light" case Pojoaque = "pojoaque" case Railscasts = "railscasts" case Rainbow = "rainbow" case SchoolBook = "school_book" case SolarizedDark = "solarized_dark" case SolarizedLight = "solarized_light" case Sunburst = "sunburst" case TomorrowNightBlue = "tomorrow-night-blue" case TomorrowNightBright = "tomorrow-night-bright" case TomorrowNightEighties = "tomorrow-night-eighties" case TomorrowNight = "tomorrow-night" case Tomorrow = "tomorrow" case VS = "vs" case Xcode = "xcode" case Zenburn = "zenburn" func css() -> String { return self.rawValue + ".css" } } /// 代码高亮WebView open class ZXHighlightWebView: UIWebView { fileprivate let baseURL = URL(fileURLWithPath: Bundle.main.bundlePath) open var hud:MBProgressHUD! override public init(frame: CGRect) { super.init(frame: frame) self.delegate = self self.backgroundColor = UIColor.clear self.isOpaque = false self.hud = MBProgressHUD.showAdded(to: self, animated: true) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func loadHTMLString(_ string: String) { self.loadHTMLString(string, baseURL: self.baseURL) } //MARK: override open override func loadHTMLString(_ string: String, baseURL: URL?) { var html = string html = html.replacingOccurrences(of: "<p><code>", with: "<pre><code>") html = html.replacingOccurrences(of: "<pre><code>\n", with: "<pre><code>") html = html.replacingOccurrences(of: "</code></p>", with: "</code></pre>") html = html.stringByInsertString(str: highlightStyleString(), beforeOccurrencesOfString: "</head>") super.loadHTMLString(html, baseURL: self.baseURL) //由于有的时候加载图片导致HUD不删除,这里添加一个7秒的监听,7秒自动删除 self.hud.hide(true, afterDelay: 7) } fileprivate func highlightStyleString() -> String { //TODO:路径问题后续优化 let arta_css_path = ("highlight/styles/" + ZXHighlightStyle.Arta.css() ) let result = "<link rel='stylesheet' href='\(arta_css_path)'>\n" + "<script src='highlight/highlight.pack.js'></script>\n" + "<script>hljs.initHighlightingOnLoad();</script>" return result; } } //MARK: - UIWebViewDelegate extension ZXHighlightWebView:UIWebViewDelegate { public func webViewDidFinishLoad(_ webView: UIWebView) { self.hud.hide(true) MBProgressHUD.hide(for: self, animated: true) } public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.hud.hide(true) MBProgressHUD.hide(for: self, animated: true) } }
mit
7fb6f439ae3c33c9bc4d0a43b9cf5226
32.453947
107
0.661947
3.58351
false
false
false
false
Orange-Datavenue/Datavenue-iOS-SDK
Sample/DatavenueSample/FieldViewCell.swift
3
1179
// // DetailViewCell.swift // // Copyright (C) 2015 Orange // // 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. // // Created by Marc Capdevielle on 30/04/2015. // Copyright (c) 2015 Orange. All rights reserved. // import UIKit class FieldViewCell : UITableViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var value: UITextField! var field : Field? func configureField(field: Field) { self.field = field label.text = field.name value.text = field.value value.enabled = !field.readOnly } @IBAction func valueEditingChanged(sender: AnyObject) { field!.value = value.text } }
apache-2.0
97a66b3baf1b9f214b3e2fd4ba70ad89
27.756098
75
0.687023
4.09375
false
false
false
false
richarddan/Flying-Swift
test-swift/ObjccBlog/BlogTableViewCell.swift
3
1217
// // BlogTableViewCell.swift // test-swift // // Created by Su Wei on 14-6-19. // Copyright (c) 2014年 OBJCC.COM. All rights reserved. // import UIKit class BlogTableViewCell: UITableViewCell { var post: BlogPost! @IBOutlet var titleImage : UIImageView! @IBOutlet var titleLabel : UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func layoutSubviews() { //self.titleImage.contentMode = UIViewContentMode.ScaleToFill if post.img_url != "" { //println(post.title + " url: \(post.img_url)") self.titleImage.setImage(post.img_url, placeHolder: UIImage(named: "BackgroundTile")) }else{ self.titleImage.image = UIImage(named: "BackgroundTile") } self.titleImage.frame = CGRectMake(6,6,88,88) self.titleLabel.text = post.title self.titleLabel.numberOfLines = 0 super.layoutSubviews() } }
apache-2.0
93d33245bacc39a5b60db8372c229656
24.851064
97
0.611523
4.450549
false
false
false
false
exponent/exponent
packages/expo-dev-launcher/ios/Errors/EXDevLauncherErrorViewController.swift
2
2039
// Copyright 2015-present 650 Industries. All rights reserved. import Foundation @objc public class EXDevLauncherErrorViewController: UIViewController, UITableViewDataSource { internal weak var manager: EXDevLauncherErrorManager? var error: EXDevLauncherAppError? @IBOutlet weak var errorInformation: UILabel! @IBOutlet weak var errorStack: UITableView! @IBAction func reload(_ sender: Any) { guard let appUrl = manager?.controller?.sourceUrl() else { // We don't have app url. So we fallback to launcher. // Shoudn't happen. navigateToLauncher() return } manager?.controller?.loadApp(appUrl, onSuccess: nil, onError: { [weak self] _ in self?.navigateToLauncher() }) } @IBAction func goToHome(_ sender: Any) { navigateToLauncher() } public override func viewDidLoad() { error = manager?.consumeError() errorInformation.text = error?.message ?? "Unknown error" errorStack?.dataSource = self } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return error?.stack?.count ?? 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! EXDevLauncherStackTrace let frame = error!.stack![indexPath.item] cell.function.text = frame.methodName cell.file.text = frame.file return cell } @objc public static func create(forManager manager: EXDevLauncherErrorManager) -> EXDevLauncherErrorViewController? { guard let bundle = EXDevLauncherUtils.resourcesBundle() else { return nil } let storyboard = UIStoryboard(name: "EXDevLauncherErrorView", bundle: bundle) let vc = storyboard.instantiateViewController(withIdentifier: "EXDevLauncherErrorView") as? EXDevLauncherErrorViewController vc?.manager = manager return vc } private func navigateToLauncher() { manager?.controller?.navigateToLauncher() } }
bsd-3-clause
2dbcc20ef4f6adccbf2c67f06186b31d
30.369231
128
0.724865
4.592342
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAWebViewController.swift
1
3415
// // SBAWebViewController.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit open class SBAWebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! open var url: URL? open var html: String? fileprivate var _webviewLoaded = false open override func viewDidLoad() { super.viewDidLoad() if (webView == nil) { self.view.backgroundColor = UIColor.white let subview = UIWebView(frame: self.view.bounds) self.view.addSubview(subview) subview.constrainToFillSuperview() subview.delegate = self subview.dataDetectorTypes = .all subview.backgroundColor = UIColor.white self.webView = subview } } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (!_webviewLoaded) { _webviewLoaded = true if let url = self.url { let request = URLRequest(url: url) webView.loadRequest(request) } else if let html = self.html { webView.loadHTMLString(html, baseURL: nil) } } } open func dismissViewController() { self.dismiss(animated: true, completion: nil) } // MARK: - UIWebViewDelegate open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.url , (navigationType == .linkClicked) { UIApplication.shared.openURL(url) return false } else { return true } } }
bsd-3-clause
d19306a6fb3308eddc744e58641fe4a7
36.516484
135
0.67604
5.027982
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-399/assignment4/CoreDataService/Source/CoreDataService.swift
1
3194
// // CoreDataService.swift // import CoreData import Foundation public typealias SaveCompletionHandler = () -> Void public class CoreDataService { public func saveRootContext(_ completionHandler: @escaping SaveCompletionHandler) { self.rootContext.perform() { do { try self.rootContext.save() DispatchQueue.main.async(execute: { () -> Void in completionHandler() }) } catch let error { fatalError("Failed to save root context: \(error as NSError)") } } } // MARK: Initialization private init() { let bundle = Bundle.main guard let modelPath = bundle.url(forResource: CoreDataService.modelName, withExtension: "momd") else { fatalError("Could not find model file with name \"\(CoreDataService.modelName)\", please set CoreDataService.modelName to the name of the model file (without the file extension)") } guard let someManagedObjectModel = NSManagedObjectModel(contentsOf: modelPath) else { fatalError("Could not load model at URL \(modelPath)") } guard let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first as NSString? else { fatalError("Could not find documents directory") } managedObjectModel = someManagedObjectModel persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) let storeRootPath = documentsDirectoryPath.appendingPathComponent("DataStore") as NSString let fileManager = FileManager.default if !fileManager.fileExists(atPath: storeRootPath as String) { do { try fileManager.createDirectory(atPath: storeRootPath as String, withIntermediateDirectories: true, attributes: nil) } catch let error { fatalError("Error creating data store directory \(error as NSError)") } } let persistentStorePath = storeRootPath.appendingPathComponent("\(CoreDataService.storeName).sqlite") let persistentStoreOptions = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: URL(fileURLWithPath: persistentStorePath), options: persistentStoreOptions) } catch let error { fatalError("Error creating persistent store \(error as NSError)") } rootContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) rootContext.persistentStoreCoordinator = persistentStoreCoordinator rootContext.undoManager = nil mainQueueContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType) mainQueueContext.parent = rootContext mainQueueContext.undoManager = nil } // MARK: Properties public let mainQueueContext: NSManagedObjectContext // MARK: Properties (Private) private let managedObjectModel: NSManagedObjectModel private let persistentStoreCoordinator: NSPersistentStoreCoordinator private let rootContext: NSManagedObjectContext // MARK: Properties (Static) public static var modelName = "Model" public static var storeName = "Model" public static let shared = CoreDataService() }
gpl-3.0
ad7f5df10cde1bb0f0e1587348516fd0
34.098901
183
0.784596
5.176661
false
false
false
false
Wolox/wolmo-core-ios
WolmoCore/Extensions/Foundation/RawRepresentable.swift
1
2064
// // RawRepresentable.swift // WolmoCore // // Created by Guido Marucci Blas on 5/7/16. // Copyright © 2016 Wolox. All rights reserved. // import Foundation public extension RawRepresentable where RawValue == Int { /** Returns a sequence that contains all the possible rawValues of self. - parameter startingAt: The value from which to start. */ static func allValues(startingAt value: Self) -> AnySequence<Self> { let generator = RawRepresentableGenerator(startingAt: value) { Self(rawValue: ($0.rawValue + 1)) } return AnySequence { generator } } /** Returns the count of all the possible values of self, starting in value. - parameter startingAt: The value from which to start. - Complexity: O(N) where N = #values - startingAt. */ static func count(startingAt value: Self) -> Int { var count = 0 for _ in allValues(startingAt: value) { count += 1 } return count } } /** Creates a generator for the specified RawValue type. */ public struct RawRepresentableGenerator<RawValue, Representable: RawRepresentable>: IteratorProtocol where Representable.RawValue == RawValue { private let _valueSuccessor: (Representable) -> Representable? private var _nextValue: Representable? /** Provides a baseRawValue and a function to get a new RawValue. */ public init(startingAt baseValue: Representable, valueSuccessor: @escaping (Representable) -> Representable?) { _nextValue = baseValue _valueSuccessor = valueSuccessor } /** Returns the new representable value. - note: The first value, is always the element associated with the baseRawValue provided at init. */ public mutating func next() -> Representable? { if let nextValue = _nextValue { let value = nextValue _nextValue = _valueSuccessor(nextValue) return value } else { return .none } } }
mit
e4f927aa71b37df08f5adace714b3d43
28.898551
143
0.637906
4.959135
false
false
false
false
loganSims/wsdot-ios-app
wsdot/VesselWatchStore.swift
2
7811
// // VesselWatchStore.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import Alamofire import SwiftyJSON /* * Gets Vessel Watch data from JSON API. */ class VesselWatchStore { typealias FetchVesselCompletion = (_ data: VesselItem?, _ error: Error?) -> () typealias FetchVesselsCompletion = (_ data: [VesselItem]?, _ error: Error?) -> () static func getVessels(_ completion: @escaping FetchVesselsCompletion) { AF.request("https://www.wsdot.wa.gov/ferries/api/vessels/rest/vessellocations?apiaccesscode=" + ApiKeys.getWSDOTKey()).validate().responseJSON { response in switch response.result { case .success: if let value = response.data { let json = JSON(value) let vessels = parseVesselsJSON(json) completion(vessels, nil) } case .failure(let error): print(error) completion(nil, error) } } } static func getVesselForTerminalCombo(_ departingTerminalID: Int, arrivingTerminalID: Int, completion: @escaping FetchVesselCompletion) { AF.request("https://www.wsdot.wa.gov/ferries/api/vessels/rest/vessellocations?apiaccesscode=" + ApiKeys.getWSDOTKey()).validate().responseJSON { response in switch response.result { case .success: if let value = response.data { let json = JSON(value) let vessels = parseVesselsJSON(json) for vessel in vessels { if vessel.departingTerminalID == departingTerminalID && vessel.arrivingTerminalID == arrivingTerminalID { completion(vessel, nil) return } } completion(nil, nil) } case .failure(let error): print(error) completion(nil, error) } } } //Converts JSON from api into and array of FerriesRouteScheduleItems fileprivate static func parseVesselsJSON(_ json: JSON) ->[VesselItem]{ var vessels = [VesselItem]() for (_,vesselJson):(String, JSON) in json { let vessel = VesselItem(id: vesselJson["VesselID"].intValue, name: vesselJson["VesselName"].stringValue, lat: vesselJson["Latitude"].doubleValue, lon: vesselJson["Longitude"].doubleValue, heading: vesselJson["Heading"].intValue, speed: vesselJson["Speed"].floatValue, inService: vesselJson["InService"].boolValue, updated: TimeUtils.parseJSONDateToNSDate(vesselJson["TimeStamp"].stringValue)) if let atDock = vesselJson["AtDock"].bool { vessel.atDock = atDock } if let timeJson = vesselJson["Eta"].string{ vessel.eta = TimeUtils.parseJSONDateToNSDate(timeJson) } if let timeJson = vesselJson["LeftDock"].string{ vessel.leftDock = TimeUtils.parseJSONDateToNSDate(timeJson) } if let timeJson = vesselJson["ScheduledDeparture"].string{ vessel.nextDeparture = TimeUtils.parseJSONDateToNSDate(timeJson) } if let arrTerm = vesselJson["ArrivingTerminalName"].string{ vessel.arrivingTerminal = arrTerm } if let deptTerm = vesselJson["DepartingTerminalName"].string { vessel.departingTerminal = deptTerm } if let arrTermId = vesselJson["ArrivingTerminalID"].int { vessel.arrivingTerminalID = arrTermId } if let deptTermId = vesselJson["DepartingTerminalID"].int { vessel.departingTerminalID = deptTermId } let routes = vesselJson["OpRouteAbbrev"].arrayValue if (routes.count > 0){ vessel.route = routes[0].stringValue.uppercased() } vessels.append(vessel) } return vessels } static func getRouteLocation(scheduleId: Int) -> CLLocationCoordinate2D { switch (scheduleId) { case 272: // Ana-SJ return CLLocationCoordinate2D(latitude: 48.550921, longitude: -122.840836); case 9: // Ana-SJ return CLLocationCoordinate2D(latitude: 48.550921, longitude: -122.840836); case 10: // Ana-Sid return CLLocationCoordinate2D(latitude: 48.550921, longitude: -122.840836); case 6: // Ed-King return CLLocationCoordinate2D(latitude: 47.803096, longitude: -122.438718); case 13: // F-S return CLLocationCoordinate2D(latitude: 47.513625, longitude: -122.450820); case 14: // F-V return CLLocationCoordinate2D(latitude: 47.513625, longitude: -122.450820); case 7: // Muk-Cl return CLLocationCoordinate2D(latitude: 47.963857, longitude: -122.327721); case 8: // Pt-Key return CLLocationCoordinate2D(latitude: 48.135562, longitude: -122.714449); case 1: // Pd-Tal return CLLocationCoordinate2D(latitude: 47.319040, longitude: -122.510890); case 5: // Sea-Bi return CLLocationCoordinate2D(latitude: 47.600325, longitude: -122.437249); case 3: // Sea-Br return CLLocationCoordinate2D(latitude: 47.565125, longitude: -122.480508); case 15: // S-V return CLLocationCoordinate2D(latitude: 47.513625, longitude: -122.450820); default: return CLLocationCoordinate2D(latitude: 47.565125, longitude: -122.480508); } } static func getRouteZoom(scheduleId: Int) -> Float { switch (scheduleId) { case 272: // Ana-SJ return 10; case 9: // Ana-SJ return 10; case 10: // Ana-Sid return 10; case 6: // Ed-King return 12; case 13: // F-S return 12; case 14: // F-V return 12; case 7: // Muk-Cl return 13; case 8: // Pt-Key return 12; case 1: // Pd-Tal return 13; case 5: // Sea-Bi return 11; case 3: // Sea-Br return 10; case 15: // S-V return 12; default: return 11; } } }
gpl-3.0
cad97cb2135c17ab622199f093c16a60
38.449495
164
0.536935
4.671651
false
false
false
false
AndreMuis/Algorithms
ValidateBinarySearchTree.playground/Contents.swift
1
1505
// // Determine if a binary search tree is valid // import Foundation class Node { var value : Int var left : Node? var right : Node? init(value : Int) { self.value = value self.left = nil self.right = nil } } var previousNode : Node? = nil func isValid(rootNode rootNode : Node?) -> Bool { var result : Bool = true if let root = rootNode { if isValid(rootNode: root.left) == false { result = false } if let previous = previousNode where root.value <= previous.value { result = false } previousNode = root if isValid(rootNode: root.right) == false { result = false } } return result } // // 20 // / \ // / \ // / \ // 15 23 // / \ / \ // 5 17 21 34 // \ // 101 // let node5 : Node = Node(value: 5) let node17 : Node = Node(value: 17) var node15 : Node = Node(value: 15) node15.left = node5 node15.right = node17 let node101 : Node = Node(value: 101) var node34 : Node = Node(value: 34) node34.right = node101 let node21 : Node = Node(value: 21) var node23 : Node = Node(value: 23) node23.left = node21 node23.right = node34 var node20 : Node = Node(value: 20) node20.left = node15 node20.right = node23 isValid(rootNode: node20) node17.value = 21 isValid(rootNode: node20)
mit
841d02dbb2275430ab74ffc4227d5f3a
15.182796
73
0.522924
3.428246
false
false
false
false
lightningkite/LKPullToLoadMore
Example/Example/MasterViewController.swift
1
2116
// // MasterViewController.swift // Example // // Created by Erik Sargent on 5/4/15. // Copyright (c) 2015 Lightning Kite. All rights reserved. // import UIKit import LKPullToLoadMore class MasterViewController: UITableViewController, LKPullToLoadMoreDelegate { //MARK: - Properties var numCells = 20 var loadMoreControl: LKPullToLoadMore! //MARK: - View Lifecycle override func viewDidLoad() { tableView.reloadData() loadMoreControl = LKPullToLoadMore(imageHeight: 40, viewWidth: tableView.frame.width, tableView: tableView) loadMoreControl.setIndicatorImage(UIImage(named: "LoadingImage")!) loadMoreControl.enable(true) loadMoreControl.delegate = self loadMoreControl.resetPosition() } //MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numCells } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "\(indexPath.row + 1)" return cell } //MARK: Load More Control func loadMore() { loadMoreControl.loading(true) numCells += 20 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.tableView.reloadData() self.loadMoreControl.loading(false) self.loadMoreControl.resetPosition() } } //MARK: - Scroll View override func scrollViewDidScroll(_ scrollView: UIScrollView) { loadMoreControl.scrollViewDidScroll(scrollView) } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { loadMoreControl.scrollViewWillEndDragging(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } }
mit
852586ab76ada4e8d1c2e38eb62b6223
29.228571
157
0.689509
4.955504
false
false
false
false
bradhilton/Allegro
Sources/ConstructType.swift
1
3596
// // ConstructType.swift // Allegro // // Created by Bradley Hilton on 3/17/16. // Copyright © 2016 Brad Hilton. All rights reserved. // /// Create a class or struct with a constructor method. Return a value of `field.type` for each field. Classes must conform to `Initializable`. public func constructType(type: Any.Type, constructor: Field throws -> Any) throws -> Any { return try anyConstructor(type).constructAnyType(constructor) } protocol AnyConstructor { static func constructAnyType(constructor: Field throws -> Any) throws -> Any } struct _AnyConstructor<T> : AnyConstructor { static func constructAnyType(constructor: Field throws -> Any) throws -> Any { let result: T = try constructType(constructor) return result } } func anyConstructor(type: Any.Type) -> AnyConstructor.Type { unsafeBitCast(_AnyConstructor<Void>.self as Any.Type, UnsafeMutablePointer<Int>.self)[3] = unsafeBitCast(type, Int.self) return _AnyConstructor<Void>.self } public protocol Initializable : class { init() } /// Create a class or struct with a constructor method. Return a value of `field.type` for each field. Classes must conform to `Initializable`. public func constructType<T>(constructor: Field throws -> Any) throws -> T { guard case _? = Metadata(type: T.self).nominalType else { throw Error.NotStructOrClass(type: T.self) } if Metadata(type: T.self)?.kind == .Struct { return try constructValueType(constructor) } else if let initializable = T.self as? Initializable.Type { return try constructReferenceType(initializable.init() as! T, constructor: constructor) } else { throw Error.ClassNotInitializable(type: T.self) } } private func constructValueType<T>(constructor: Field throws -> Any) throws -> T { guard Metadata(type: T.self)?.kind == .Struct else { throw Error.NotStructOrClass(type: T.self) } let pointer = UnsafeMutablePointer<T>.alloc(1) defer { pointer.dealloc(1) } var values = [Any]() try constructType(UnsafeMutablePointer<UInt8>(pointer), values: &values, fields: fieldsForType(T.self), constructor: constructor) return pointer.memory } private func constructReferenceType<T>(value: T, constructor: Field throws -> Any) throws -> T { var copy = value var values = [Any]() try constructType(mutableStorageForInstance(&copy), values: &values, fields: fieldsForType(T.self), constructor: constructor) return copy } private func constructType(storage: UnsafeMutablePointer<UInt8>, inout values: [Any], fields: [Field], constructor: Field throws -> Any) throws { for field in fields { var value = try constructor(field) guard instanceValue(value, isOfType: field.type) else { throw Error.ValueIsNotOfType(value: value, type: field.type) } values.append(value) storage.advancedBy(field.offset).consumeBuffer(bytesForInstance(&value)) } } /// Create a class or struct from a dictionary. Classes must conform to `Initializable`. public func constructType<T>(dictionary: [String: Any]) throws -> T { return try constructType(constructorForDictionary(dictionary)) } private func constructorForDictionary(dictionary: [String: Any]) -> Field throws -> Any { return { field in if let value = dictionary[field.name] { return value } else if let nilLiteralConvertible = field.type as? NilLiteralConvertible.Type { return nilLiteralConvertible.init(nilLiteral: ()) } else { throw Error.RequiredValueMissing(key: field.name) } } }
mit
9fa3645685b6665a2aba4df1a3ac1384
40.321839
145
0.707093
4.117984
false
false
false
false
grandiere/box
box/View/GridVisor/VGridVisorMenuButton.swift
1
1714
import UIKit class VGridVisorMenuButton:UIButton { private let kAlphaNotSelected:CGFloat = 1 private let kAlphaSelected:CGFloat = 0.3 private let kAnimationDuration:TimeInterval = 0.5 init(image:UIImage) { super.init(frame:CGRect.zero) clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false setImage( image.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.normal) setImage( image.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.highlighted) imageView!.clipsToBounds = true imageView!.contentMode = UIViewContentMode.center alpha = 0 } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { alpha = kAlphaSelected } else { alpha = kAlphaNotSelected } } //MARK: public func animate(show:Bool) { let alpha:CGFloat if show { alpha = 1 isUserInteractionEnabled = true } else { alpha = 0 isUserInteractionEnabled = false } UIView.animate(withDuration:kAnimationDuration) { [weak self] in self?.alpha = alpha } } }
mit
b938bcac37709c060fe7c100a5b8d575
19.650602
73
0.528588
5.713333
false
false
false
false
FelixYin66/Sqlite3
SQLiteTest--001/SQLiteTest--001/Person.swift
1
2191
// // Person.swift // SQLiteTest--001 // // Created by FelixYin on 15/8/1. // Copyright © 2015年 felixios. All rights reserved. // import UIKit class Person: NSObject { var id:Int = 0 var name:String? var age:Int = 0 var address:String? init(dict:[String:AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } // 打印描述 private static let pro = ["id","name","age","address"] override var description: String { return "\(dictionaryWithValuesForKeys(Person.pro))" } // 插入模型到数据库中 func insertPerson () -> Bool { assert(address != nil && name != nil, "名字,地址都不能为空") //sql语句,中间拼接的值要在单引号的里面,单引号不能省去 let sql = "INSERT INTO T_Person (name,age,address) VALUES ('\(name!)',\(age),'\(address!)');" //执行sql语句 let result = SQLiteManager.sharedManager.execSQL(sql) //返回执行结果 return result } // 更新数据库中的记录 func updatePerson() -> Bool { let sql = "update T_Person set\n" + "name = '\(name!)',\n" + "age = \(age),\n" + "address = '\(address!)'\n" + "where id = \(id);" //执行sql let result = SQLiteManager.sharedManager.execSQL(sql) return result } // 删除一条记录 func deletePerson () -> Bool { let sql = "DELETE FROM T_Person Where id = \(id);" let result = SQLiteManager.sharedManager.execSQL(sql) return result } // 查询数据库中的数据 class func selectRecord() -> [[String:AnyObject]]? { let sql = "SELECT NAME,AGE,ADDRESS,ID FROM T_Person" return SQLiteManager.sharedManager.selectRecord(sql) } }
bsd-2-clause
5812e48a1971397c54db142fcafd433e
15.290323
99
0.471782
4.325482
false
false
false
false
Palleas/Rewatch
Rewatch/UI/Helpers/PictureHelpers.swift
1
1194
// // PictureHelpers.swift // Rewatch // // Created by Romain Pouclet on 2015-11-02. // Copyright © 2015 Perfectly-Cooked. All rights reserved. // import UIKit func convertToBlackAndWhite(image: UIImage) -> UIImage { let colorSpace = CGColorSpaceCreateDeviceGray() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue).rawValue let width = Int(image.size.width) let height = Int(image.size.height) let context = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, bitmapInfo) CGContextDrawImage(context, CGRect(origin: CGPointZero, size: image.size), image.CGImage) let ref = CGBitmapContextCreateImage(context) if let ref = CGImageCreateCopy(ref) { return UIImage(CGImage: ref) } return image } func tintImage(image: UIImage, color: UIColor) -> UIImage { let rect = CGRect(origin: .zero, size: image.size) UIGraphicsBeginImageContextWithOptions(image.size, false, 0) color.set() UIRectFill(rect) image.drawInRect(rect, blendMode: .DestinationIn, alpha: 1) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage }
mit
f483e2109cb34c9e6884c185f1e4d118
29.615385
93
0.72171
4.434944
false
false
false
false
artursDerkintis/YouTube
YouTube/BrowseViewController.swift
1
6012
// // BrowseViewController.swift // YouTube // // Created by Arturs Derkintis on 1/27/16. // Copyright © 2016 Starfly. All rights reserved. // import UIKit protocol BrowserDelegate{ func loadSubscription(channelId : String) func setOwnInfo() } class BrowseViewController: UIViewController, BrowserDelegate { var subscriptionsVC : SubscriptionsController! var navigationView : BrowseTopView! var channelsVC : ChannelsViewController! var forwardSteps = [Channel]() var currentChannel : Channel! override func viewDidLoad() { super.viewDidLoad() subscriptionsVC = SubscriptionsController() subscriptionsVC.browserDelegate = self addChildViewController(subscriptionsVC) view.addSubview(subscriptionsVC.view) subscriptionsVC.view.snp_makeConstraints { (make) -> Void in make.top.right.bottom.equalTo(0) make.width.equalTo(self.view.snp_width).multipliedBy(0.98) } channelsVC = ChannelsViewController() view.addSubview(channelsVC.view) channelsVC.view.backgroundColor = UIColor.clearColor() channelsVC.view.snp_makeConstraints { (make) -> Void in make.left.top.bottom.equalTo(0) make.right.equalTo(self.subscriptionsVC.view.snp_leftMargin) } self.view.bringSubviewToFront(subscriptionsVC.view) navigationView = BrowseTopView(frame: .zero) view.addSubview(navigationView) navigationView.snp_makeConstraints { (make) -> Void in make.top.left.right.equalTo(0) make.height.equalTo(64) } navigationView.backButton.addTarget(self, action: "goBack", forControlEvents: .TouchDown) let long = UILongPressGestureRecognizer(target: self, action: "goHome") long.minimumPressDuration = 1.0 navigationView.backButton.addGestureRecognizer(long) // Do any additional setup after loading the view. NSNotificationCenter.defaultCenter().addObserver(self, selector: "openChannelByNotif:", name: channelNotification, object: nil) setOwnInfo() } func openChannelByNotif(not : NSNotification){ if let id = (not.object as? Channel)?.channelDetails?.id{ self.loadSubscription(id) } } func goHome(){ channelsVC.removeAll() self.setOwnInfo() self.subscriptionsVC.view.snp_updateConstraints { (make) -> Void in make.width.equalTo(self.view.snp_width) } UIView.animateWithDuration(0.3) { () -> Void in self.view.layoutIfNeeded() } } func goBack(){ if channelsVC.channelViewControllers.count > 1{ channelsVC.removeCurrentChannelController() }else{ channelsVC.removeCurrentChannelController() self.setOwnInfo() self.subscriptionsVC.view.snp_updateConstraints { (make) -> Void in make.width.equalTo(self.view.snp_width).multipliedBy(0.97) } UIView.animateWithDuration(0.3, animations: { () -> Void in self.view.layoutIfNeeded() }, completion: { (fin) -> Void in }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tap(sender : UITapGestureRecognizer){ if sender.state == .Ended{ } } func setOwnInfo(){ if let currentUser = UserHandler.sharedInstance.user{ navigationView.setDetails(currentUser.name!, thumbnail: currentUser.imageURL!, description: "", subscribed: Subscribed.Unknown) navigationView.backButton.hidden = true } } func setChannelInfo(){ if let cdet = currentChannel.channelDetails, subscribed = currentChannel.subscribed { self.navigationView.setDetails(cdet.title!, thumbnail: cdet.thumbnail!, description: "\(cdet.shortSubscriberCount) subscribers", subscribed: subscribed ? Subscribed.Subscribed : Subscribed.NotSubscribed) self.navigationView.backButton.hidden = false self.navigationView.currentChannelId = cdet.id } } func loadSubscription(channelId : String){ let channel = Channel() if let currentUser = UserHandler.sharedInstance.user{ channel.getChannelDetails(channelId) { (channelDetails) -> Void in channel.channelDetails = channelDetails haveISubscribedToChannel(channelId, token: currentUser.token!, completion: { (fin) -> Void in channel.subscribed = fin self.currentChannel = channel self.forwardSteps.append(self.currentChannel) self.setChannelInfo() self.openChannel(self.currentChannel) }) } } } func openChannel(channel: Channel) { minimizeSubscriptions() channelsVC.addChannelController(channel) } func minimizeSubscriptions(){ self.subscriptionsVC.view.snp_updateConstraints { (make) -> Void in make.width.equalTo(self.view.snp_width).dividedBy(4.2) } UIView.animateWithDuration(0.3) { () -> Void in self.view.layoutIfNeeded() self.subscriptionsVC.collectionView.contentInset = UIEdgeInsets(top: 70, left: 0, bottom: 64, right: 0) } } /* // 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
32126bd173626c962e5746faaf8940b8
35.216867
215
0.628514
4.931091
false
false
false
false
jawwad/swift-algorithm-club
3Sum and 4Sum/3Sum.playground/Contents.swift
3
2098
// last checked with Xcode 10.1 #if swift(>=4.2) print("Hello, Swift 4.2!") #endif extension Collection where Element: Equatable { /// In a sorted collection, replaces the given index with a successor mapping to a unique element. /// /// - Parameter index: A valid index of the collection. `index` must be less than `endIndex` func formUniqueIndex(after index: inout Index) { var prev = index repeat { prev = index formIndex(after: &index) } while index < endIndex && self[prev] == self[index] } } extension BidirectionalCollection where Element: Equatable { /// In a sorted collection, replaces the given index with a predecessor that maps to a unique element. /// /// - Parameter index: A valid index of the collection. `index` must be greater than `startIndex`. func formUniqueIndex(before index: inout Index) { var prev = index repeat { prev = index formIndex(before: &index) } while index > startIndex && self[prev] == self[index] } } func threeSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) -> [[T.Element]] where T.Element: Numeric & Comparable { let sorted = collection.sorted() var ret: [[T.Element]] = [] var l = sorted.startIndex ThreeSum: while l < sorted.endIndex { defer { sorted.formUniqueIndex(after: &l) } var m = sorted.index(after: l) var r = sorted.index(before: sorted.endIndex) TwoSum: while m < r && r < sorted.endIndex { let sum = sorted[l] + sorted[m] + sorted[r] if sum == target { ret.append([sorted[l], sorted[m], sorted[r]]) sorted.formUniqueIndex(after: &m) sorted.formUniqueIndex(before: &r) } else if sum < target { sorted.formUniqueIndex(after: &m) } else { sorted.formUniqueIndex(before: &r) } } } return ret } // Answer: [[-1, 0, 1], [-1, -1, 2]] threeSum([-1, 0, 1, 2, -1, -4], target: 0) // Answer: [[-1, -1, 2], [-1, 0, 1]] threeSum([-1, -1, -1, -1, 2, 1, -4, 0], target: 0) // Answer: [[-1, -1, 2]] threeSum([-1, -1, -1, -1, -1, -1, 2], target: 0)
mit
5ecd6dcf706f3f1bfa3feb5447dcef45
30.313433
134
0.616778
3.394822
false
false
false
false
LockLight/Weibo_Demo
SinaWeibo/SinaWeibo/Classes/View/PhotoBrowser(图片浏览器)/WBPhotoViewerController.swift
1
2532
// // WBPhotoViewerController.swift // SinaWeibo // // Created by locklight on 17/4/9. // Copyright © 2017年 LockLight. All rights reserved. // import UIKit import SDWebImage class WBPhotoViewerController: UIViewController { //大图为scrollView lazy var scrollView:UIScrollView = { let scrollView = UIScrollView(frame: screenBounds) return scrollView }() lazy var imageView:UIImageView = UIImageView() //当前展示图片的index var index:Int = 0 //图片的url数组 var pic_urlArr:[String] = [] //重载构造函数,设置所需参数 init(index:Int, pic_urlArr:[String]){ super.init(nibName: nil, bundle: nil) self.index = index self.pic_urlArr = pic_urlArr } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.groupTableViewBackground print("第\(index)张图片,url地址是\(pic_urlArr[index])") setupUI() } } extension WBPhotoViewerController{ func setupUI(){ self.view.addSubview(scrollView) scrollView.addSubview(imageView) //异步下载展示图片 let url = URL(string: pic_urlArr[index]) // print("----\(url!)----") SDWebImageManager.shared().downloadImage(with: url!, options: [], progress: nil) { (middelImg, _,_, _, _) in if let middelImg = middelImg{ //下载完成后设置给当前的imageView self.imageView.image = middelImg let imgSize = middelImg.size //调整比例: 新高/新宽 = 原高/原宽 let newWidth = screenWidth let newHeight = imgSize.height/imgSize.width * newWidth let newSize = CGSize(width: newWidth, height: newHeight) //设置调整后的imageView的frame let frame = CGRect(origin: CGPoint.zero, size: newSize) self.imageView.frame = frame //当图片的高度小于当前屏幕高度 if newHeight <= screenHeight{ self.imageView.center = self.scrollView.center }else{ self.scrollView.contentSize = newSize } } } } }
mit
8af7c6b53a06ee1a920489dcdaf92fbd
27.39759
116
0.551549
4.695219
false
false
false
false
Tarovk/Mundus_Client
Mundus_ios/UserQuestionVC.swift
1
4312
// // UserQuestionVC.swift // Mundus_ios // // Created by Team Aldo on 10/01/2017. // Copyright (c) 2017 Team Aldo. All rights reserved. // import UIKit import Aldo /// ViewController for the user question panel. class UserQuestionVC: UITableViewController, Callback { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21)) var cellDataArrray = [GroupCellData]() var questions: NSMutableArray = NSMutableArray() func onResponse(request: String, responseCode: Int, response: NSDictionary) { if responseCode == 200 { switch request { case MundusRequestURI.REQUEST_ASSIGNED.rawValue: questions = (response.object(forKey: "questions") as! NSArray).mutableCopy() as! NSMutableArray refreshControl!.endRefreshing() if questions.count < 3 { Mundus.getQuestion(callback: self) } updateEmptyMessage() break default: Mundus.getAssignedQuestions(callback: self) break } } self.tableView.reloadData() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) tabBarItem = UITabBarItem(title: "My questions", image: UIImage(named: "userwrite"), tag: 0) } override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = [] self.tabBarController!.tabBar.backgroundColor = UIColor.white self.tableView.allowsSelection = false self.tableView!.separatorStyle = .none initEmptyMessage() initRefreshControl() refresh() } /// Sets the background of the panel. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let backgroundImage = UIImageView(image: UIImage(named: "lightwood")) backgroundImage.contentMode = .scaleAspectFill backgroundImage.layer.zPosition = -1 self.tableView.backgroundView = backgroundImage } /// Initialized the empty message in the middle of the panel. private func initEmptyMessage() { label.textColor = UIColor.black label.textAlignment = .center tableView.backgroundView = label tableView.separatorStyle = .none updateEmptyMessage() } /// Initialized the pull to refresh mechanism. private func initRefreshControl() { refreshControl = UIRefreshControl() refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl!.addTarget(self, action: #selector(UserQuestionVC.refresh), for: UIControlEvents.valueChanged) tableView.addSubview(refreshControl!) } /// Updates the empty message in the middle of the panel /// depening on whether questions are available or not. private func updateEmptyMessage() { var text = "" if questions.count == 0 { text = "No questions left" } label.text = text } /// Sends a request to retrieve the questions assigned to the player. func refresh() { Mundus.getAssignedQuestions(callback: self) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("UserQuestionCell", owner: self)?.first as! UserQuestionCell let review: String = (questions[indexPath.item] as! NSDictionary).object(forKey: "reviewed") as! String if review == "-2" { cell.setActive() } else if review == "-1" { cell.setUnderReview() } else if review == "0" { cell.setDeclined() } cell.backgroundColor = .clear cell.questionId = (questions[indexPath.item] as! NSDictionary).object(forKey: "questionID") as! String cell.question.text = ((questions[indexPath.item] as! NSDictionary).object(forKey: "question") as! String) return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questions.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 300 } }
mit
6d59a495b7a677594aa3aabacd245419
34.344262
117
0.638451
4.922374
false
false
false
false
ben-ng/swift
test/Interpreter/SDK/objc_keypath.swift
19
1806
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation class Person : NSObject { @objc(firstNameString) var firstName: String var lastName: String init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } override var description: String { return "\(lastName), \(firstName)" } } class Band : NSObject { var members: [Person] = [] } class RecordLabel : NSObject { var bands: [String : Band] = [:] } let band = Band() band.members = [Person(firstName: "John", lastName: "Lennon"), Person(firstName: "Paul", lastName: "McCartney"), Person(firstName: "George", lastName: "Harrison"), Person(firstName: "Ringo", lastName: "Star")] // CHECK: ===Members=== // CHECK-NEXT: ( // CHECK-NEXT: Lennon, John // CHECK-NEXT McCartney, Paul, // CHECK-NEXT Harrison, George, // CHECK-NEXT Star, Ringo // CHECK-NEXT) print("===Members===") print((band.value(forKeyPath: #keyPath(Band.members))! as AnyObject).description) // CHECK: ===First Names=== // CHECK-NEXT: ( // CHECK-NEXT: John, // CHECK-NEXT: Paul, // CHECK-NEXT: George, // CHECK-NEXT: Ringo // CHECK-NEXT:) print("===First Names===") print((band.value(forKeyPath: #keyPath(Band.members.firstName))! as AnyObject).description) let recordLabel = RecordLabel() recordLabel.bands["Beatles"] = band // CHECK: ===Last Names=== // CHECK-NEXT: ( // CHECK-NEXT: Lennon, // CHECK-NEXT: McCartney, // CHECK-NEXT: Harrison, // CHECK-NEXT: Star // CHECK-NEXT: ) print("===Last Names===") print((recordLabel.value(forKeyPath: #keyPath(RecordLabel.bands.Beatles.members.lastName))! as AnyObject).description) // CHECK: DONE print("DONE")
apache-2.0
f873d4a7254758a54e81b886747833b9
24.8
118
0.645072
3.45977
false
false
false
false
wesj/firefox-ios-1
Storage/SQL/SQLitePasswords.swift
1
6333
/* 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 private class PasswordsTable<T>: GenericTable<Password> { override var name: String { return "logins" } override var version: Int { return 1 } override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "hostname TEXT NOT NULL, " + "httpRealm TEXT NOT NULL, " + "formSubmitUrl TEXT NOT NULL, " + "usernameField TEXT NOT NULL, " + "passwordField TEXT NOT NULL, " + "guid TEXT NOT NULL UNIQUE, " + "timeCreated REAL NOT NULL, " + "timeLastUsed REAL NOT NULL, " + "timePasswordChanged REAL NOT NULL, " + "username TEXT NOT NULL, " + "password TEXT NOT NULL" } override func getInsertAndArgs(inout item: Password) -> (String, [AnyObject?])? { var args = [AnyObject?]() if item.guid == nil { item.guid = NSUUID().UUIDString } args.append(item.hostname) args.append(item.httpRealm) args.append(item.formSubmitUrl) args.append(item.usernameField) args.append(item.passwordField) args.append(item.guid) args.append(item.timeCreated) args.append(item.timeLastUsed) args.append(item.timePasswordChanged) args.append(item.username) args.append(item.password) return ("INSERT INTO \(name) (hostname, httpRealm, formSubmitUrl, usernameField, passwordField, guid, timeCreated, timeLastUsed, timePasswordChanged, username, password) VALUES (?,?,?,?,?,?,?,?,?,?,?)", args) } override func getUpdateAndArgs(inout item: Password) -> (String, [AnyObject?])? { var args = [AnyObject?]() args.append(item.httpRealm) args.append(item.formSubmitUrl) args.append(item.usernameField) args.append(item.passwordField) args.append(item.timeCreated) args.append(item.timeLastUsed) args.append(item.timePasswordChanged) args.append(item.password) args.append(item.hostname) args.append(item.username) return ("UPDATE \(name) SET httpRealm = ?, formSubmitUrl = ?, usernameField = ?, passwordField = ?, timeCreated = ?, timeLastUsed = ?, timePasswordChanged = ?, password = ? WHERE hostname = ? AND username = ?", args) } override func getDeleteAndArgs(inout item: Password?) -> (String, [AnyObject?])? { var args = [AnyObject?]() if let pw = item { args.append(pw.hostname) args.append(pw.username) return ("DELETE FROM \(name) WHERE hostname = ? AND username = ?", args) } return ("DELETE FROM \(name)", args) } override var factory: ((row: SDRow) -> Password)? { return { row -> Password in let site = Site(url: row["hostname"] as String, title: "") let pw = Password(site: site, username: row["username"] as String, password: row["password"] as String) pw.httpRealm = row["httpRealm"] as String pw.formSubmitUrl = row["formSubmitUrl"] as String pw.usernameField = row["usernameField"] as String pw.passwordField = row["passwordField"] as String pw.guid = row["guid"] as? String pw.timeCreated = NSDate(timeIntervalSince1970: row["timeCreated"] as Double) pw.timeLastUsed = NSDate(timeIntervalSince1970: row["timeLastUsed"] as Double) pw.timePasswordChanged = NSDate(timeIntervalSince1970: row["timePasswordChanged"] as Double) return pw } } override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? { var args = [AnyObject?]() if let filter: AnyObject = options?.filter { args.append(filter) return ("SELECT * FROM \(name) WHERE hostname = ?", args) } return ("SELECT * FROM \(name)", args) } } public class SQLitePasswords : Passwords { private let table = PasswordsTable<Password>() private let db: BrowserDB public init(files: FileAccessor) { self.db = BrowserDB(files: files)! db.createOrUpdate(table) } public func get(options: QueryOptions, complete: (cursor: Cursor) -> Void) { var err: NSError? = nil let cursor = db.query(&err, callback: { (connection, err) -> Cursor in return self.table.query(connection, options: options) }) dispatch_async(dispatch_get_main_queue()) { _ in complete(cursor: cursor) } } public func add(password: Password, complete: (success: Bool) -> Void) { var err: NSError? = nil var success = false let updated = db.update(&err, callback: { (connection, err) -> Int in return self.table.update(connection, item: password, err: &err) }) println("Updated \(updated)") if updated == 0 { let inserted = db.insert(&err, callback: { (connection, err) -> Int in return self.table.insert(connection, item: password, err: &err) }) println("Inserted \(inserted)") if inserted > -1 { success = true } } else { success = true } dispatch_async(dispatch_get_main_queue()) { _ in complete(success: success) return } } public func remove(password: Password, complete: (success: Bool) -> Void) { var err: NSError? = nil let deleted = db.delete(&err, callback: { (connection, err) -> Int in return self.table.delete(connection, item: password, err: &err) }) dispatch_async(dispatch_get_main_queue()) { _ in complete(success: deleted > -1) } } public func removeAll(complete: (success: Bool) -> Void) { var err: NSError? = nil let deleted = db.delete(&err, callback: { (connection, err) -> Int in return self.table.delete(connection, item: nil, err: &err) }) dispatch_async(dispatch_get_main_queue()) { _ in complete(success: deleted > -1) } } }
mpl-2.0
56e0d42e69c601d0f47153eaebc6e7dc
37.852761
224
0.593873
4.4194
false
false
false
false
lanit-tercom-school/grouplock
GroupLockiOS/GroupLockTests/ScanningModelsComparison.swift
1
726
// // ScanningModelsComparison.swift // GroupLock // // Created by Sergej Jaskiewicz on 18.08.16. // Copyright © 2016 Lanit-Tercom School. All rights reserved. // @testable import GroupLock extension Scanning.Keys.ViewModel: EquatableModel { func isEqualTo(_ model: Scanning.Keys.ViewModel) -> Bool { return numberOfDifferentKeys == model.numberOfDifferentKeys && qrCodeCGPath == model.qrCodeCGPath && isValidKey == model.isValidKey } } extension Scanning.CameraError.ViewModel: EquatableModel { func isEqualTo(_ model: Scanning.CameraError.ViewModel) -> Bool { return errorName == model.errorName && errorDescription == model.errorDescription } }
apache-2.0
ded4048fa50987b2974497150399cd63
26.884615
70
0.692414
4.420732
false
false
false
false
OctoberHammer/CoreDataCollViewFRC
Pods/WYMaterialButton/Pod/Classes/DesignableButton.swift
5
2256
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @IBDesignable open class DesignableButton: SpringButton { @IBInspectable open var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable open var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable open var shadowColor: UIColor = UIColor.clear { didSet { layer.shadowColor = shadowColor.cgColor } } @IBInspectable open var shadowRadius: CGFloat = 0 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable open var shadowOpacity: CGFloat = 0 { didSet { layer.shadowOpacity = Float(shadowOpacity) } } @IBInspectable open var shadowOffsetY: CGFloat = 0 { didSet { layer.shadowOffset.height = shadowOffsetY } } }
mit
ee7614c6035d3e3c883f90032e37424b
31.695652
81
0.667553
4.958242
false
false
false
false
google/JacquardSDKiOS
Example/JacquardSDK/Extensions/Extensions.swift
1
2471
// Copyright 2021 Google LLC // // 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 Combine import Foundation import UIKit extension Cancellable { /// Provides a convenient way to retain Combine observation/Cancellables. /// /// example usage: /// ``` /// class Foo { /// private var observations = [Cancellable]() /// func foo() { /// somePublisher.sink({}).addTo(&observations) /// } /// } /// ``` func addTo(_ array: inout [Cancellable]) { array.append(self) } /// Provides a convenient way to retain Combine observation/AnyCancellable. /// /// example usage: /// ``` /// class Foo { /// private var observations = [AnyCancellable]() /// func foo() { /// somePublisher.sink({}).addTo(&observations) /// } /// } /// ``` func addTo(_ array: inout [AnyCancellable]) { if let self = self as? AnyCancellable { array.append(self) } } } extension Publisher { /// Map a publisher with Failure type Never to one with Failure type Error /// /// This can be necessary since in Combine the error types have to match for `flatMap`. It is tempting to put a where clause on /// this extension to limit the application of this function to `Failure == Never` but unfortunately this results in a /// `will never be executed` warning in the code below. func mapNeverToError() -> AnyPublisher<Output, Error> { return self.mapError { error -> Error in return error }.eraseToAnyPublisher() } } extension UIFont { static let system12Medium = UIFont.systemFont(ofSize: 12.0, weight: .medium) static let system14Medium = UIFont.systemFont(ofSize: 14.0, weight: .medium) static let system16Medium = UIFont.systemFont(ofSize: 16.0, weight: .medium) static let system20Normal = UIFont.systemFont(ofSize: 20.0, weight: .regular) } extension Int { /// Helper function to convert second to millisec. func convertSecToMilliSec() -> Self { return self * 1000 } }
apache-2.0
525a3614c5b2b77ae71b6c8e302672f4
31.513158
129
0.683529
4.159933
false
false
false
false
tavon321/FoodApp
FoodApp/FoodApp/UserViewController.swift
1
2121
// // UserViewController.swift // FoodApp // // Created by s209e013 on 11/11/16. // Copyright © 2016 juan david lopera. All rights reserved. // import UIKit class UserViewController: UIViewController { var users = [User]() @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. User.users { (success, response) in if success { if let users = response["users"] as? [User] { self.users = users } }else { print("Error: \(response["error"])") }} } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == "login"{ for i in users { print(i.name) print(i.pass) if usernameTextField.text == i.name && passwordTextField.text == i.pass { return true; } } let alert = UIAlertController(title: "Login", message: "Credenciales invalidas", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(okAction) presentViewController(alert, animated: true, completion:nil) return false; } return true; } 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. } */ }
mit
c090520631bfb146968f33a96fed78b9
28.041096
116
0.573113
5.183374
false
false
false
false
tkremenek/swift
libswift/Sources/SIL/Location.swift
7
606
//===--- Location.swift - Source location ---------------------------------===// // // 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 SILBridging public struct Location { let bridgedLocation: BridgedLocation }
apache-2.0
6efbef953a97c5969e76977c210225ea
34.647059
80
0.59901
5.092437
false
false
false
false
xin-wo/kankan
kankan/kankan/Class/Mine/Controller/MineViewController.swift
1
4374
// // MineViewController.swift // kankan // // Created by Xin on 16/10/19. // Copyright © 2016年 王鑫. All rights reserved. // import UIKit class MineViewController: UIViewController, WXNavigationProtocol { var tableView: UITableView! //所有cell的名称 var cellNames = ["开通看看会员", "", "追剧", "收藏", "购买记录", "扫一扫", "远程设备管理", "设置", "反馈"] var desText = "登入后支持云同步及访问更多特权" var titleText = "点击登录" var userImage = UIImage(named: "default_poster_250_350") var hasLogin = false override func viewDidLoad() { super.viewDidLoad() configUI() } func configUI() { automaticallyAdjustsScrollViewInsets = false view.backgroundColor = UIColor.whiteColor() tableView = UITableView(frame: CGRect(x: 0, y: 64, width: screenWidth, height: screenHeight-108), style: .Plain) tableView.dataSource = self tableView.delegate = self tableView.registerNib(UINib(nibName: "MineTableViewCell", bundle: nil), forCellReuseIdentifier: "firstMine") tableView.registerNib(UINib(nibName: "OtherTableViewCell", bundle: nil), forCellReuseIdentifier: "otherMine") tableView.showsVerticalScrollIndicator = false view.addSubview(tableView) addTitle("个人中心") addBottomImage() addBarButton(imageName: "app_nav_back_normal", bgImageName: "app_nav_back_clicked", postion: .left, select: #selector(backAction)) } func backAction() { self.navigationController?.popViewControllerAnimated(true) } } //MARK:UITableView代理 extension MineViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellNames.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("firstMine", forIndexPath: indexPath) as! MineTableViewCell cell.descLabel.text = desText cell.titleLabel.text = titleText cell.userImage.image = userImage cell.accessoryType = .DisclosureIndicator return cell } else if indexPath.row == 2 { let cell = tableView.dequeueReusableCellWithIdentifier("otherMine", forIndexPath: indexPath) as! OtherTableViewCell cell.itemLabel.text = "播放记录" cell.smallImage.image = UIImage(named: "app_nav_history_clicked") cell.accessoryType = .DisclosureIndicator return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("otherMine", forIndexPath: indexPath) as! OtherTableViewCell cell.itemLabel.text = cellNames[indexPath.row-1] cell.accessoryType = .DisclosureIndicator return cell } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { return 80 } return 50 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.row == 0 { if hasLogin { let AVC = AccountViewController() AVC.desText = self.desText AVC.titleText = self.titleText AVC.userImage = self.userImage AVC.hidesBottomBarWhenPushed = true navigationController?.pushViewController(AVC, animated: true) } else { let LVC = PassViewController() LVC.hidesBottomBarWhenPushed = true navigationController?.pushViewController(LVC, animated: true) } } else if indexPath.row == 2 { let vc = HistoryViewController() vc.hidesBottomBarWhenPushed = true navigationController?.pushViewController(vc, animated: true) } } }
mit
b3a8b4602e2d4235413369a8b4db53df
31.638462
138
0.620316
5.257745
false
false
false
false
dcunited001/SpectraNu
Spectra/Spectra.swift
1
2430
// // Spectra.swift // // // Created by David Conner on 11/28/15. // // import Foundation import simd public class Spectra { } public class SpectraSimd { public static func parseDoubles(str: String) -> [Double] { let valStrs = str.characters.split { $0 == " " }.map(String.init) return valStrs.map() { Double($0)! } } public static func parseInts(str: String) -> [Int] { let valStrs = str.characters.split { $0 == " " }.map(String.init) return valStrs.map() { Int($0)! } } public static func parseInt32s(str: String) -> [Int32] { let valStrs = str.characters.split { $0 == " " }.map(String.init) return valStrs.map() { Int32($0)! } } public static func parseFloats(str: String) -> [Float] { let valStrs = str.characters.split { $0 == " " }.map(String.init) return valStrs.map() { Float($0)! } } public static func parseFloat2(str: String) -> float2 { return float2(parseFloats(str)) } public static func parseInt2(str: String) -> int2 { return int2(parseInt32s(str)) } public static func parseFloat3(str: String) -> float3 { return float3(parseFloats(str)) } public static func parseInt3(str: String) -> int3 { return int3(parseInt32s(str)) } public static func parseFloat4(str: String) -> float4 { return float4(parseFloats(str)) } public static func parseInt4(str: String) -> int4 { return int4(parseInt32s(str)) } public static func compareFloat2(a: float2, with b: float2) -> Bool { return (a.x == b.x) && (a.y == b.y) } public static func compareFloat3(a: float3, with b: float3) -> Bool { return ((a.x == b.x) && (a.y == b.y) && (a.z == b.z)) } public static func compareFloat4(a: float4, with b: float4) -> Bool { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w) } public static func compareInt2(a: int2, with b: int2) -> Bool { return (a.x == b.x) && (a.y == b.y) } public static func compareInt3(a: int3, with b: int3) -> Bool { return ((a.x == b.x) && (a.y == b.y) && (a.z == b.z)) } public static func compareInt4(a: int4, with b: int4) -> Bool { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w) } }
mit
de84c0eb5e3679ed610c96ea17d0eb4e
27.255814
75
0.538683
3.151751
false
false
false
false
tkohout/MMRecord
Examples/MMRecordAtlassian/MMRecordAtlassian/Classes/View/PlansViewController.swift
3
1543
// // ViewController.swift // MMRecordAtlassian // // Created by Conrad Stoll on 6/20/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import UIKit class PlansViewController: UITableViewController, UITableViewDataSource { var plans: [Plan] = [] override func viewDidLoad() { super.viewDidLoad() var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate var managedObjectContext = appDelegate.managedObjectContext Plan.startRequestWithURN("/plans", data: nil, context: managedObjectContext, domain: self, resultBlock: {records in var results: [Plan] = records as [Plan] self.plans = results self.tableView.reloadData() }, failureBlock: { error in }) } override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 1 } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return plans.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell var plan = plans[indexPath.row] cell.textLabel.text = plan.name return cell } }
mit
7f22027ab61c809134ce5d49c95ff663
28.673077
124
0.613739
5.714815
false
false
false
false
a2/arex-7
ArexKit/Models/Pistachio/Adapters.swift
2
5426
import Foundation import MessagePack import Monocle import Pistachio import ReactiveCocoa import Result import ValueTransformer public enum ScheduleAdapterError: ErrorType { case InvalidInput(String) } private extension ScheduleType { enum TypeString: String { case Daily = "daily" case EveryXDays = "everyXDays" case Weekly = "weekly" case Monthly = "monthly" case NotCurrentlyTaken = "notCurrentlyTaken" } var typeString: String { switch self { case .Daily: return TypeString.Daily.rawValue case .EveryXDays: return TypeString.EveryXDays.rawValue case .Weekly: return TypeString.Weekly.rawValue case .Monthly: return TypeString.Monthly.rawValue case .NotCurrentlyTaken: return TypeString.NotCurrentlyTaken.rawValue } } init?(typeString: String) { if let enumValue = TypeString(rawValue: typeString) { switch enumValue { case .Daily: self = .Daily case .EveryXDays: self = .EveryXDays case .Weekly: self = .Weekly case .Monthly: self = .Monthly case .NotCurrentlyTaken: self = .NotCurrentlyTaken } } else { return nil } } } public struct ScheduleAdapter: AdapterType { public init() {} private func error(string: String) -> ErrorType { return ScheduleAdapterError.InvalidInput(string) } public func transform(model: Schedule) -> Result<MessagePackValue, ErrorType> { var encoded: [MessagePackValue : MessagePackValue] = [ "type": .String(model.scheduleType.typeString), ] switch model { case .Daily, .NotCurrentlyTaken: break case let .EveryXDays(interval: interval, startDate: startDate): encoded += [ "interval": .Int(numericCast(interval)), "startDate": .Double(startDate.timeIntervalSince1970), ] case let .Weekly(days: days): encoded += ["days": .Int(numericCast(days))] case let .Monthly(days: days): encoded += ["days": .Int(numericCast(days))] } return .success(.Map(encoded)) } public func reverseTransform(data: MessagePackValue) -> Result<Schedule, ErrorType> { if let dictionary = data.dictionaryValue, typeString = dictionary["type"]?.stringValue, scheduleType = ScheduleType(typeString: typeString) { switch scheduleType { case .Daily: return .success(.Daily) case .EveryXDays: if let interval = dictionary["interval"]?.integerValue, startDateInterval = dictionary["startDate"]?.doubleValue { let startDate = NSDate(timeIntervalSince1970: startDateInterval) return .success(.EveryXDays(interval: numericCast(interval), startDate: startDate)) } else { let stringKeys = dictionary.keys.map { String($0) } return .failure(error("Expected \"interval\" (Int) and \"startDate\" (Double) in data for Schedule.EveryXDays, got: \(stringKeys)")) } case .Weekly: if let days = dictionary["days"]?.integerValue { return .success(.Weekly(days: numericCast(days))) } else { let stringKeys = dictionary.keys.map { String($0) } return .failure(error("Expected \"days\" (Int) in data for Schedule.Weekly, got: \(stringKeys)")) } case .Monthly: if let days = dictionary["days"]?.integerValue { return .success(.Monthly(days: numericCast(days))) } else { let stringKeys = dictionary.keys.map { String($0) } return .failure(error("Expected \"days\" (Int) in data for Schedule.Monthly, got: \(stringKeys)")) } case .NotCurrentlyTaken: return .success(.NotCurrentlyTaken) } } else { return .failure(error("Expected MessagePackValue.Map with one of \"daily\", \"everyXDays\", \"weekly\", \"monthly\", \"notCurrentlyTaken\" as \"type\" (String) in Schedule data , got: \(data)")) } } } public struct Adapters { public static func medication(UUID UUID: NSUUID? = nil) -> MessagePackAdapter<Medication> { return MessagePackAdapter(specification: [ "name": messagePackString(MedicationLenses.name), "schedule": messagePackMap(MedicationLenses.schedule)(adapter: Adapters.schedule), "strength": messagePackString(MedicationLenses.strength), "times": messagePackArray(MedicationLenses.times)(adapter: Adapters.time), ], value: Medication(UUID: UUID)) } public static let schedule = ScheduleAdapter() public static let time = MessagePackAdapter(specification: [ "hour": messagePackInt(TimeLenses.hour), "minute": messagePackInt(TimeLenses.minute), ], value: Time()) }
mit
fdb7f6dc5ed0e2968c6f6fe2a3c16f64
37.48227
206
0.568559
5.071028
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Profile/User/BFEditUserController.swift
1
8522
// // BFEditUserController.swift // BeeFun // // Created by WengHengcong on 2017/4/17. // Copyright © 2017年 JungleSong. All rights reserved. // import UIKit import Moya import ObjectMapper import Alamofire class BFEditUserController: BFBaseViewController { var cellModels: [JSCellModel] = [] var switchCell: JSSwitchCell? var cells: [JSBaseCell] = [] // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() euc_viewInit() euc_dataInit() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // MARK: - Action override func leftItemAction(_ sender: UIButton?) { _ = self.navigationController?.popViewController(animated: true) } override func rightItemAction(_ sender: UIButton?) { if euc_dataChange() { //有值改变 euc_save() } else { //所有值均未变 popToLastView() } } /// 保存 func euc_save() { view.endEditing(true) // name, email, blog, company, location, hireable, bio let name = textFiledValue(index: 0) ?? "" let email = textFiledValue(index: 1) ?? "" let blog = textFiledValue(index: 2) ?? "" let company = textFiledValue(index: 3) ?? "" let location = textFiledValue(index: 4) ?? "" let bio = textFiledValue(index: 5) ?? "" let hire = switchCell?.value ?? false let para: Parameters = [ "name": name, "email": email, "blog": blog, "company": company, "location": location, "hireable": hire, "bio": bio ] var request = URLRequest(url: URL(string: "https://api.github.com/user")!) request.httpMethod = HTTPMethod.patch.rawValue request.setValue(AppToken.shared.access_token ?? "", forHTTPHeaderField: "Authorization") request.setValue("15.0", forHTTPHeaderField: "timeoutInterval") request.setValue("BeeFun", forHTTPHeaderField: "User-Agent") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") let paraData = para.jsonData() request.httpBody = paraData let hud = JSMBHUDBridge.showHud(view: self.view) Alamofire.request(request).responseJSON { (response) in hud.hide(animated: true) let message = kNetworkErrorTip if response.response?.statusCode == BFStatusCode.ok.rawValue { switch response.result { case .success: if let gitUser: ObjUser = Mapper<ObjUser>().map(JSONObject: response.result.value) { ObjUser.saveUserInfo(gitUser) //post successful noti //更新用户信息 UserManager.shared.updateUserInfo() _ = self.navigationController?.popViewController(animated: true) } else { } case .failure: JSMBHUDBridge.showError(message, view: self.view) } } } } /// 返回上一页 func popToLastView() { _ = self.navigationController?.popViewController(animated: true) } // MARK: - view func euc_viewInit() { title = "Edit".localized rightItem?.setTitle("Save".localized, for: .normal) rightItem?.isHidden = false refreshHidden = .all view.addSubview(tableView) view.backgroundColor = .white self.tableView.frame = CGRect(x: 0, y: topOffset, w: ScreenSize.width, h: ScreenSize.height-topOffset) self.automaticallyAdjustsScrollViewInsets = false } func euc_dataInit() { // name, email, blog, company, location, hireable, bio //0 let nameM = JSCellModelFactory.eidtInit(type: JSCellType.edit.rawValue, id: "name", key: "Name".localized, value: UserManager.shared.login?.localized, placeholder: "".localized) cellModels.append(nameM) //1 let emailM = JSCellModelFactory.eidtInit(type: JSCellType.edit.rawValue, id: "email", key: "Email".localized, value: UserManager.shared.user?.email?.localized, placeholder: "".localized) cellModels.append(emailM) //2 let blogM = JSCellModelFactory.eidtInit(type: JSCellType.edit.rawValue, id: "blog", key: "Blog".localized, value: UserManager.shared.user?.blog?.localized, placeholder: "".localized) cellModels.append(blogM) //3 let companyM = JSCellModelFactory.eidtInit(type: JSCellType.edit.rawValue, id: "company", key: "Company".localized, value: UserManager.shared.user?.company?.localized, placeholder: "".localized) cellModels.append(companyM) //4 let locM = JSCellModelFactory.eidtInit(type: JSCellType.edit.rawValue, id: "location", key: "Location".localized, value: UserManager.shared.user?.location?.localized, placeholder: "".localized) cellModels.append(locM) //5 let hireM = JSCellModelFactory.switchInit(type: JSCellType.switched.rawValue, id: "hireable", key: "Hireable".localized, switched: UserManager.shared.user?.hireable) cellModels.append(hireM) //6 let bioM = JSCellModelFactory.eidtInit(type: JSCellType.edit.rawValue, id: "bio", key: "Bio".localized, value: UserManager.shared.user?.bio?.localized, placeholder: "".localized) cellModels.append(bioM) tableView.reloadData() } func euc_dataChange() -> Bool { if !cells.isEmpty && cells.count >= 6 { if UserManager.shared.user?.login != textFiledValue(index: 0) || UserManager.shared.user?.email != textFiledValue(index: 1) || UserManager.shared.user?.company != textFiledValue(index: 2) || UserManager.shared.user?.company != textFiledValue(index: 3) || UserManager.shared.user?.location != textFiledValue(index: 4) || UserManager.shared.user?.login != textFiledValue(index: 5) { return true } if UserManager.shared.user?.hireable != switchCell?.value { return true } return false } return false } func textFiledValue(index: Int) -> String? { if cells.isEmpty { return nil } if cells.isBeyond(index: index) { return nil } if let cell = cells[index] as? JSEditCell { return cell.value } return nil } } extension BFEditUserController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellModels.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = indexPath.row let cellModel = cellModels[row] if row == 5 { var cell = tableView.dequeueReusableCell(withIdentifier: "EditUserIdentifierSwtich") as? JSSwitchCell if cell == nil { cell = JSCellFactory.cell(type:cellModel.type!) as? JSSwitchCell } cell?.model = cellModel cell?.bothEndsLine(row, all: cellModels.count) switchCell = cell return cell! } var cell = tableView.dequeueReusableCell(withIdentifier: "EditUserIdentifier") as? JSEditCell if cell == nil { cell = JSCellFactory.cell(type:cellModel.type!) as? JSEditCell } cell?.model = cellModel cell?.bothEndsLine(row, all: cellModels.count) cells.append(cell!) return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) } }
mit
f9beb61e4488fc37a1a414c144dd38e8
35.209402
398
0.594477
4.555376
false
false
false
false