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
mokagio/Quick
Sources/Quick/DSL/World+DSL.swift
28
7291
import Foundation /** Adds methods to World to support top-level DSL functions (Swift) and macros (Objective-C). These functions map directly to the DSL that test writers use in their specs. */ extension World { internal func beforeSuite(closure: BeforeSuiteClosure) { suiteHooks.appendBefore(closure) } internal func afterSuite(closure: AfterSuiteClosure) { suiteHooks.appendAfter(closure) } internal func sharedExamples(name: String, closure: SharedExampleClosure) { registerSharedExample(name, closure: closure) } internal func describe(description: String, flags: FilterFlags, closure: () -> ()) { guard currentExampleMetadata == nil else { raiseError("'describe' cannot be used inside '\(currentPhase)', 'describe' may only be used inside 'context' or 'describe'. ") } guard currentExampleGroup != nil else { raiseError("Error: example group was not created by its parent QuickSpec spec. Check that describe() or context() was used in QuickSpec.spec() and not a more general context (i.e. an XCTestCase test)") } let group = ExampleGroup(description: description, flags: flags) currentExampleGroup.appendExampleGroup(group) performWithCurrentExampleGroup(group, closure: closure) } internal func context(description: String, flags: FilterFlags, closure: () -> ()) { guard currentExampleMetadata == nil else { raiseError("'context' cannot be used inside '\(currentPhase)', 'context' may only be used inside 'context' or 'describe'. ") } self.describe(description, flags: flags, closure: closure) } internal func fdescribe(description: String, flags: FilterFlags, closure: () -> ()) { var focusedFlags = flags focusedFlags[Filter.focused] = true self.describe(description, flags: focusedFlags, closure: closure) } internal func xdescribe(description: String, flags: FilterFlags, closure: () -> ()) { var pendingFlags = flags pendingFlags[Filter.pending] = true self.describe(description, flags: pendingFlags, closure: closure) } internal func beforeEach(closure: BeforeExampleClosure) { guard currentExampleMetadata == nil else { raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'. ") } currentExampleGroup.hooks.appendBefore(closure) } #if _runtime(_ObjC) @objc(beforeEachWithMetadata:) internal func beforeEach(closure closure: BeforeExampleWithMetadataClosure) { currentExampleGroup.hooks.appendBefore(closure) } #else internal func beforeEach(closure closure: BeforeExampleWithMetadataClosure) { currentExampleGroup.hooks.appendBefore(closure) } #endif internal func afterEach(closure: AfterExampleClosure) { guard currentExampleMetadata == nil else { raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'. ") } currentExampleGroup.hooks.appendAfter(closure) } #if _runtime(_ObjC) @objc(afterEachWithMetadata:) internal func afterEach(closure closure: AfterExampleWithMetadataClosure) { currentExampleGroup.hooks.appendAfter(closure) } #else internal func afterEach(closure closure: AfterExampleWithMetadataClosure) { currentExampleGroup.hooks.appendAfter(closure) } #endif internal func it(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { if beforesCurrentlyExecuting { raiseError("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'. ") } if aftersCurrentlyExecuting { raiseError("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'. ") } guard currentExampleMetadata == nil else { raiseError("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'. ") } let callsite = Callsite(file: file, line: line) let example = Example(description: description, callsite: callsite, flags: flags, closure: closure) currentExampleGroup.appendExample(example) } internal func fit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { var focusedFlags = flags focusedFlags[Filter.focused] = true self.it(description, flags: focusedFlags, file: file, line: line, closure: closure) } internal func xit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { var pendingFlags = flags pendingFlags[Filter.pending] = true self.it(description, flags: pendingFlags, file: file, line: line, closure: closure) } internal func itBehavesLike(name: String, sharedExampleContext: SharedExampleContext, flags: FilterFlags, file: String, line: UInt) { guard currentExampleMetadata == nil else { raiseError("'itBehavesLike' cannot be used inside '\(currentPhase)', 'itBehavesLike' may only be used inside 'context' or 'describe'. ") } let callsite = Callsite(file: file, line: line) let closure = World.sharedWorld.sharedExample(name) let group = ExampleGroup(description: name, flags: flags) currentExampleGroup.appendExampleGroup(group) performWithCurrentExampleGroup(group) { closure(sharedExampleContext) } group.walkDownExamples { (example: Example) in example.isSharedExample = true example.callsite = callsite } } #if _runtime(_ObjC) @objc(itWithDescription:flags:file:line:closure:) private func objc_it(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { it(description, flags: flags, file: file, line: line, closure: closure) } @objc(fitWithDescription:flags:file:line:closure:) private func objc_fit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { fit(description, flags: flags, file: file, line: line, closure: closure) } @objc(xitWithDescription:flags:file:line:closure:) private func objc_xit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { xit(description, flags: flags, file: file, line: line, closure: closure) } @objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:flags:file:line:) private func objc_itBehavesLike(name: String, sharedExampleContext: SharedExampleContext, flags: FilterFlags, file: String, line: UInt) { itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: flags, file: file, line: line) } #endif internal func pending(description: String, closure: () -> ()) { print("Pending: \(description)") } private var currentPhase: String { if beforesCurrentlyExecuting { return "beforeEach" } else if aftersCurrentlyExecuting { return "afterEach" } return "it" } }
apache-2.0
3bbd2ad2ebe491677b2e38039a010ee0
42.142012
213
0.673844
4.787262
false
false
false
false
mindbody/Conduit
Example/ConduitExampleIOS/Services/ProtectedResourceService.swift
1
3329
// // ProtectedResourceService.swift // ConduitExample // // Created by John Hammerlund on 6/23/17. // Copyright © 2017 MINDBODY. All rights reserved. // import Foundation import Conduit struct ProtectedResourceService { private let apiBaseURL = URL(string: "http://localhost:5000")! func fetchThing(completion: @escaping Result<ProtectedThing>.Block) { let userBearerAuthorization = OAuth2Authorization(type: .bearer, level: .user) let clientConfiguration = AuthManager.shared.localClientConfiguration var urlComponents = URLComponents(url: apiBaseURL, resolvingAgainstBaseURL: false) urlComponents?.path = "/answers/life" guard let url = urlComponents?.url else { completion(.error(RequestSerializerError.invalidURL)) return } let builder = HTTPRequestBuilder(url: url) builder.method = .GET /// We typically use a JSON serializer, but serializers exist for most other common transport operations /// and content types (XML/SOAP, multipart form-data, www-form-encoded) builder.serializer = JSONRequestSerializer() /// Here, we can also configure special formatting options and declare query string parameters /// or POST/PUT/PATCH input fields // builder.queryStringFormattingOptions.dictionaryFormat = .subscripted // builder.queryStringFormattingOptions.plusSymbolEncodingRule = .replacedWithEncodedPlus // builder.queryStringFormattingOptions.arrayFormat = .commaSeparated // builder.queryStringParameters = ["key" : ["value 1", "value 2"]] let request: URLRequest do { request = try builder.build() } catch { completion(.error(error)) return } var sessionClient = URLSessionClientManager.localAPISessionClient /// OAuth2 token management, including refreshing where applicable, is completely handled by a middleware component. /// When a new token needs to be fetched for any means (and Conduit has the needed credentials or refresh token), /// the network pipeline will freeze, all outgoing requests will finish, a new token will be fetched, and /// request processing will resume. let authMiddleware = OAuth2RequestPipelineMiddleware(clientConfiguration: clientConfiguration, authorization: userBearerAuthorization, tokenStorage: AuthManager.shared.localTokenStore) sessionClient.requestMiddleware.append(authMiddleware) sessionClient.begin(request: request) { (data, response, error) in let responseDeserializer = JSONResponseDeserializer() let dto: ProtectedThing do { guard let json = try responseDeserializer.deserialize(response: response, data: data) as? [String : Any] else { throw ResponseDeserializerError.deserializationFailure } dto = try ProtectedThing(json: json) } catch { completion(.error(error)) return } completion(.value(dto)) } } }
apache-2.0
78485160a43a8628dc50a7113c287955
43.373333
127
0.640625
5.528239
false
true
false
false
24/ios-o2o-c
gxc/OpenSource/ExSwift/Int.swift
3
4623
// // Int.swift // ExSwift // // Created by pNre on 03/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension Int { /** Calls function self times. :param: function Function to call */ func times <T> (function: Void -> T) { (0..<self).each { _ in function(); return } } /** Calls function self times. :param: function Function to call */ func times (function: Void -> Void) { (0..<self).each { _ in function(); return } } /** Calls function self times passing a value from 0 to self on each call. :param: function Function to call */ func times <T> (function: (Int) -> T) { (0..<self).each { index in function(index); return } } /** Checks if a number is even. :returns: true if self is even */ func isEven () -> Bool { return (self % 2) == 0 } /** Checks if a number is odd. :returns: true if self is odd */ func isOdd () -> Bool { return !isEven() } /** Iterates function, passing in integer values from self up to and including limit. :param: limit Last value to pass :param: function Function to invoke */ func upTo (limit: Int, function: (Int) -> ()) { if limit < self { return } (self...limit).each(function) } /** Iterates function, passing in integer values from self down to and including limit. :param: limit Last value to pass :param: function Function to invoke */ func downTo (limit: Int, function: (Int) -> ()) { if limit > self { return } Array(limit...self).reverse().each(function) } /** Clamps self to a specified range. :param: range Clamping range :returns: Clamped value */ func clamp (range: Range<Int>) -> Int { return clamp(range.startIndex, range.endIndex - 1) } /** Clamps self to a specified range. :param: min Lower bound :param: max Upper bound :returns: Clamped value */ func clamp (min: Int, _ max: Int) -> Int { return Swift.max(min, Swift.min(max, self)) } /** Checks if self is included a specified range. :param: range Range :param: string If true, "<" is used for comparison :returns: true if in range */ func isIn (range: Range<Int>, strict: Bool = false) -> Bool { if strict { return range.startIndex < self && self < range.endIndex - 1 } return range.startIndex <= self && self <= range.endIndex - 1 } /** Checks if self is included in a closed interval. :param: interval Interval to check :returns: true if in the interval */ func isIn (interval: ClosedInterval<Int>) -> Bool { return interval.contains(self) } /** Checks if self is included in an half open interval. :param: interval Interval to check :returns: true if in the interval */ func isIn (interval: HalfOpenInterval<Int>) -> Bool { return interval.contains(self) } /** Returns an [Int] containing the digits in self. :return: Array of digits */ func digits () -> [Int] { var result = [Int]() for char in String(self) { let string = String(char) if let toInt = string.toInt() { result.append(toInt) } } return result } /** Absolute value. :returns: abs(self) */ func abs () -> Int { return Swift.abs(self) } /** Greatest common divisor of self and n. :param: n :returns: GCD */ func gcd (n: Int) -> Int { return n == 0 ? self : n.gcd(self % n) } /** Least common multiple of self and n :param: n :@returns: LCM */ func lcm (n: Int) -> Int { return (self * n).abs() / gcd(n) } /** Random integer between min and max (inclusive). :param: min Minimum value to return :param: max Maximum value to return :returns: Random integer */ static func random(min: Int = 0, max: Int) -> Int { return Int(arc4random_uniform(UInt32((max - min) + 1))) + min } }
mit
6f564a49c042410a4b818a21e4cf06d8
22.115
91
0.512222
4.304469
false
false
false
false
yo-op/sketchcachecleaner
Sketch Cache Cleaner/Extensions/NSButton+Extensions.swift
1
1076
// // NSButtonExtensions.swift // Sketch Cache Cleaner // // Created by Sasha Prokhorenko on 19.12.17. // Copyright © 2017 Sasha Prokhorenko. All rights reserved. // import Cocoa extension NSButton { @discardableResult static func setButton(_ button: NSButton, title: String) -> NSButton { button.title = title button.backgroundColor = NSColor(red: 1.0, green: 0.70, blue: 0.0, alpha: 1.00) let textColor = NSColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.00) let style = NSMutableParagraphStyle() style.alignment = .center let font = NSFont.mainFont(ofSize: 14) let attributes = [NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: style] as [NSAttributedString.Key: Any] button.attributedTitle = NSAttributedString(string: title, attributes: attributes) button.layer?.cornerRadius = 3.0 button.layer?.masksToBounds = true return button } }
mit
432a33ad33da394eab87f220824e643c
36.068966
104
0.652093
4.182879
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/Extensions/NSAttributedString+Helpers.swift
2
2857
import Foundation extension NSAttributedString { /// Checks if a given Push Notification is a Push Authentication. /// This method will embed a collection of assets, in the specified NSRange's. /// Since NSRange is an ObjC struct, you'll need to wrap it up into a NSValue instance! /// /// - Parameter embeds: A collection of embeds. NSRange > UIImage. /// /// - Returns: An attributed string with all of the embeds specified, inlined. /// func stringByEmbeddingImageAttachments(_ embeds: [NSValue: UIImage]?) -> NSAttributedString { // Allow nil embeds: behave as a simple NO-OP if embeds == nil { return self } // Proceed embedding! let unwrappedEmbeds = embeds! let theString = self.mutableCopy() as! NSMutableAttributedString var rangeDelta = 0 for (value, image) in unwrappedEmbeds { let imageAttachment = NSTextAttachment() imageAttachment.bounds = CGRect(origin: CGPoint.zero, size: image.size) imageAttachment.image = image // Each embed is expected to add 1 char to the string. Compensate for that let attachmentString = NSAttributedString(attachment: imageAttachment) var correctedRange = value.rangeValue correctedRange.location += rangeDelta // Bounds Safety let lastPosition = correctedRange.location + correctedRange.length if lastPosition <= theString.length { theString.replaceCharacters(in: correctedRange, with: attachmentString) } rangeDelta += attachmentString.length } return theString } /// This helper method returns a new NSAttributedString instance, with all of the the leading / trailing newLines /// characters removed. /// func trimNewlines() -> NSAttributedString { guard let trimmed = mutableCopy() as? NSMutableAttributedString else { return self } let characterSet = CharacterSet.newlines // Trim: Leading var range = (trimmed.string as NSString).rangeOfCharacter(from: characterSet) while range.length != 0 && range.location == 0 { trimmed.replaceCharacters(in: range, with: String()) range = (trimmed.string as NSString).rangeOfCharacter(from: characterSet) } // Trim Trailing range = (trimmed.string as NSString).rangeOfCharacter(from: characterSet, options: .backwards) while range.length != 0 && NSMaxRange(range) == trimmed.length { trimmed.replaceCharacters(in: range, with: String()) range = (trimmed.string as NSString).rangeOfCharacter(from: characterSet, options: .backwards) } return trimmed } }
gpl-2.0
8271e98223884777b563a018511ebf9c
37.093333
117
0.634232
5.280961
false
false
false
false
HabitRPG/habitrpg-ios
Habitica API Client/Habitica API Client/Models/Group/APIChatMessage.swift
1
2821
// // APIChatMessage.swift // Habitica API Client // // Created by Phillip Thelen on 29.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models public class APIChatMessage: ChatMessageProtocol, Codable { public var id: String? public var userID: String? public var text: String? public var attributedText: NSAttributedString? public var timestamp: Date? public var displayName: String? public var username: String? public var flagCount: Int public var contributor: ContributorProtocol? public var userStyles: UserStyleProtocol? public var likes: [ChatMessageReactionProtocol] = [] public var flags: [ChatMessageReactionProtocol] = [] public var isValid: Bool { return true } enum CodingKeys: String, CodingKey { case id case userID = "uuid" case text case timestamp case displayName = "user" case username case flagCount case contributor case userStyles case likes case flags } enum ContainerCodingKeys: String, CodingKey { case message } public required init(from decoder: Decoder) throws { let messageContainer = try decoder.container(keyedBy: ContainerCodingKeys.self) let values = try messageContainer.contains(.message) ? messageContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .message) : decoder.container(keyedBy: CodingKeys.self) id = try values.decode(String.self, forKey: .id) userID = try? values.decode(String.self, forKey: .userID) text = try? values.decode(String.self, forKey: .text) let timeStampNumber = try? values.decode(Double.self, forKey: .timestamp) if let number = timeStampNumber { timestamp = Date(timeIntervalSince1970: number/1000) } else { timestamp = try? values.decode(Date.self, forKey: .timestamp) } displayName = try? values.decode(String.self, forKey: .displayName) username = try? values.decode(String.self, forKey: .username) flagCount = try values.decode(Int.self, forKey: .flagCount) contributor = (try? values.decode(APIContributor.self, forKey: .contributor)) if values.contains(.userStyles) { userStyles = try? values.decode(APIUserStyle.self, forKey: .userStyles) } if values.contains(.likes) { likes = APIChatMessageReaction.fromList(try? values.decode([String: Bool].self, forKey: .likes)) } if values.contains(.flags) { flags = APIChatMessageReaction.fromList(try? values.decode([String: Bool].self, forKey: .flags)) } } public func encode(to encoder: Encoder) throws { } }
gpl-3.0
09f6665634723c5c4942775d52f6556e
35.623377
185
0.656738
4.462025
false
false
false
false
jmgc/swift
validation-test/Sema/type_checker_perf/slow/fast-operator-typechecking.swift
1
984
// RUN: %target-typecheck-verify-swift -swift-version 5 -solver-expression-time-threshold=1 // rdar://problem/32998180 func checksum(value: UInt16) -> UInt16 { var checksum = (((value >> 2) ^ (value >> 8) ^ (value >> 12) ^ (value >> 14)) & 0x01) << 1 // expected-error@-1 {{the compiler is unable to type-check this expression in reasonable time}} checksum |= (((value) ^ (value >> UInt16(4)) ^ (value >> UInt16(6)) ^ (value >> UInt16(10))) & 0x01) // expected-error@-1 {{the compiler is unable to type-check this expression in reasonable time}} checksum ^= 0x02 return checksum } // rdar://problem/42672829 func f(tail: UInt64, byteCount: UInt64) { if tail & ~(1 << ((byteCount & 7) << 3) - 1) == 0 { } } // rdar://problem/32547805 func size(count: Int) { // Size of the buffer we need to allocate let _ = count * MemoryLayout<Float>.size * (4 + 3 + 3 + 2 + 4) // expected-error@-1 {{the compiler is unable to type-check this expression in reasonable time}} }
apache-2.0
36fa8199f75ea13f9b73383c484b2a94
41.782609
102
0.643293
3.247525
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Control/KeyComparisonQualifier.swift
1
2122
// // KeyComparisonQualifier.swift // ZeeQL // // Created by Helge Hess on 28/02/17. // Copyright © 2017-2019 ZeeZide GmbH. All rights reserved. // public struct KeyComparisonQualifier : Qualifier, Equatable { public let leftKeyExpr : Key public let rightKeyExpr : Key public let operation : ComparisonOperation public init(_ left: Key, _ op: ComparisonOperation = .EqualTo, _ right: Key) { self.leftKeyExpr = left self.rightKeyExpr = right self.operation = op } public init(_ left: String, _ op: String = "==", _ right: String) { self.init(StringKey(left), ComparisonOperation(string: op), StringKey(right)) } public var leftKey : String { return leftKeyExpr.key } public var rightKey : String { return rightKeyExpr.key } public var leftExpression : Expression { return leftKeyExpr } public var rightExpression : Expression { return rightKeyExpr } public var isEmpty : Bool { return false } public func addReferencedKeys(to set: inout Set<String>) { set.insert(leftKeyExpr.key) set.insert(rightKeyExpr.key) } // MARK: - Bindings public var hasUnresolvedBindings : Bool { return false } // MARK: - Equality public static func ==(lhs: KeyComparisonQualifier, rhs: KeyComparisonQualifier) -> Bool { guard lhs.operation == rhs.operation else { return false } guard lhs.leftKeyExpr.isEqual(to: rhs.leftKeyExpr) else { return false } guard lhs.rightKeyExpr.isEqual(to: rhs.rightKeyExpr) else { return false } return true } public func isEqual(to object: Any?) -> Bool { guard let other = object as? KeyComparisonQualifier else { return false } return self == other } // MARK: - Description public func appendToDescription(_ ms: inout String) { // TODO: improve ms += " \(leftKeyExpr) \(operation) \(rightKeyExpr)" } public func appendToStringRepresentation(_ ms: inout String) { ms += leftKeyExpr.key ms += " \(operation.stringRepresentation) " ms += rightKeyExpr.key } }
apache-2.0
29a8487542a40b8a5fb6a88baac5efc6
27.662162
80
0.655823
4.071017
false
false
false
false
zirinisp/SlackKit
SlackKit/Sources/User.swift
1
4678
// // User.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct User { public struct Profile { internal(set) public var firstName: String? internal(set) public var lastName: String? internal(set) public var realName: String? internal(set) public var email: String? internal(set) public var skype: String? internal(set) public var phone: String? internal(set) public var image24: String? internal(set) public var image32: String? internal(set) public var image48: String? internal(set) public var image72: String? internal(set) public var image192: String? internal(set) public var customProfile: CustomProfile? internal init(profile: [String: Any]?) { firstName = profile?["first_name"] as? String lastName = profile?["last_name"] as? String realName = profile?["real_name"] as? String email = profile?["email"] as? String skype = profile?["skype"] as? String phone = profile?["phone"] as? String image24 = profile?["image_24"] as? String image32 = profile?["image_32"] as? String image48 = profile?["image_48"] as? String image72 = profile?["image_72"] as? String image192 = profile?["image_192"] as? String customProfile = CustomProfile(customFields: profile?["fields"] as? [String: Any]) } } public let id: String? internal(set) public var name: String? internal(set) public var deleted: Bool? internal(set) public var profile: Profile? internal(set) public var doNotDisturbStatus: DoNotDisturbStatus? internal(set) public var presence: String? internal(set) public var color: String? public let isBot: Bool? internal(set) public var isAdmin: Bool? internal(set) public var isOwner: Bool? internal(set) public var isPrimaryOwner: Bool? internal(set) public var isRestricted: Bool? internal(set) public var isUltraRestricted: Bool? internal(set) public var has2fa: Bool? internal(set) public var hasFiles: Bool? internal(set) public var status: String? internal(set) public var timeZone: String? internal(set) public var timeZoneLabel: String? internal(set) public var timeZoneOffSet: Int? internal(set) public var preferences: [String: Any]? // Client properties internal(set) public var userGroups: [String: String]? internal init(user: [String: Any]?) { id = user?["id"] as? String name = user?["name"] as? String deleted = user?["deleted"] as? Bool profile = Profile(profile: user?["profile"] as? [String: Any]) color = user?["color"] as? String isAdmin = user?["is_admin"] as? Bool isOwner = user?["is_owner"] as? Bool isPrimaryOwner = user?["is_primary_owner"] as? Bool isRestricted = user?["is_restricted"] as? Bool isUltraRestricted = user?["is_ultra_restricted"] as? Bool has2fa = user?["has_2fa"] as? Bool hasFiles = user?["has_files"] as? Bool isBot = user?["is_bot"] as? Bool presence = user?["presence"] as? String status = user?["status"] as? String timeZone = user?["tz"] as? String timeZoneLabel = user?["tz_label"] as? String timeZoneOffSet = user?["tz_offset"] as? Int preferences = user?["prefs"] as? [String: Any] } internal init(id: String?) { self.id = id self.isBot = nil } }
mit
d305cf87e28ff99d5c77014910d5b872
43.122642
93
0.651486
4.279048
false
false
false
false
sschiau/swift
test/ModuleInterface/Inputs/opaque-result-types-client.swift
7
2197
import OpaqueResultTypes func getAssocType<T: AssocTypeInference>(_ x: T) -> T.Assoc { return x.foo(0) } func getAssocPropType<T: AssocTypeInference>(_ x: T) -> T.AssocProperty { return x.prop } func getAssocSubscriptType<T: AssocTypeInference>(_ x: T) -> T.AssocSubscript { return x[] } struct MyFoo: Foo {} struct YourFoo: Foo {} @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func someTypeIsTheSame() { var a = foo(0) a = foo(0) a = foo("") // expected-error{{cannot assign value of type 'some Foo' (result of 'foo') to type 'some Foo' (result of 'foo')}} var b = foo("") b = foo(0) // expected-error{{cannot assign value of type 'some Foo' (result of 'foo') to type 'some Foo' (result of 'foo')}} b = foo("") var c = foo(MyFoo()) c = foo(0) // expected-error{{cannot assign value of type 'some Foo' (result of 'foo') to type 'some Foo' (result of 'foo')}} c = foo(MyFoo()) c = foo(YourFoo()) // expected-error{{cannot convert value of type 'YourFoo' to expected argument type 'MyFoo'}} var barInt = Bar<Int>() var barString = Bar<String>() var d = barInt.foo(0) d = barInt.foo(0) d = barString.foo(0) // expected-error{{cannot assign}} d = getAssocType(barInt) d = getAssocType(barString) // expected-error{{cannot assign}} var d2 = barInt.prop d2 = barInt.prop d2 = barString.prop // expected-error{{cannot assign}} d2 = getAssocPropType(barInt) d2 = getAssocPropType(barString) // expected-error{{cannot assign}} var d3 = barInt[] d3 = barInt[] d3 = barString[] // expected-error{{cannot assign}} d3 = getAssocSubscriptType(barInt) d3 = getAssocSubscriptType(barString) // expected-error{{cannot assign}} var e = barString.foo(0) e = barInt.foo(0) // expected-error{{cannot assign}} e = barString.foo(0) e = getAssocType(barInt) // expected-error{{cannot assign}} e = getAssocType(barString) var f = barInt.foo(MyFoo()) f = barInt.foo(MyFoo()) f = barString.foo(MyFoo()) // expected-error{{cannot assign}} f = barInt.foo(YourFoo()) // expected-error{{cannot convert value of type 'YourFoo' to expected argument type 'MyFoo'}} f = barString.foo(MyFoo()) // expected-error{{cannot assign}} }
apache-2.0
0c5c9062d1b6c68aa1a9bf1d9cd9afc2
33.873016
128
0.666363
3.207299
false
false
false
false
rockwotj/shiloh-ranch
ios/shiloh_ranch/shiloh_ranch/SermonUpdater.swift
1
1819
// // SermonUpdater.swift // Shiloh Ranch // // Created by Tyler Rockwood on 6/13/15. // Copyright (c) 2015 Shiloh Ranch Cowboy Church. All rights reserved. // import Foundation class SermonsUpdater : Updater { override func getSyncQuery() -> GTLQuery? { return GTLQueryShilohranch.queryForUpdateSermonsWithMilliseconds(getLastSyncTime()) } override func update(pageToken : String? = nil) { let service = getApiService() let query = GTLQueryShilohranch.queryForSermons() as GTLQueryShilohranch query.pageToken = pageToken service.executeQuery(query) { (ticket, response, error) -> Void in if error != nil { showErrorDialog(error) } else { let sermonCollection = response as! GTLShilohranchSermonCollection let sermons = sermonCollection.items() as! [GTLShilohranchSermon] if pageToken == nil && !sermons.isEmpty { let lastSync = convertDateToUnixTime(sermons[0].timeAdded) if lastSync > 0 { println("Setting last SyncTime for Sermons to be \(lastSync)") self.setLastSyncTime(lastSync) } } for sermon in sermons { println("Got Sermon named: \(sermon.title)") self.save(sermon) } if let nextPageToken = sermonCollection.nextPageToken { self.update(pageToken: nextPageToken) } } } } func save(entity : GTLShilohranchSermon) { let database = getDatabase() database.insert(entity) } override func getModelType() -> String! { return "Category" } }
mit
500924c70e4764e69c08b23c0ce74ebf
33.339623
91
0.565695
4.351675
false
false
false
false
practicalswift/swift
test/Parse/try_swift5.swift
20
16110
// RUN: %target-typecheck-verify-swift -swift-version 5 // Intentionally has lower precedence than assignments and ?: infix operator %%%% : LowPrecedence precedencegroup LowPrecedence { associativity: none lowerThan: AssignmentPrecedence } func %%%%<T, U>(x: T, y: U) -> Int { return 0 } // Intentionally has lower precedence between assignments and ?: infix operator %%% : MiddlingPrecedence precedencegroup MiddlingPrecedence { associativity: none higherThan: AssignmentPrecedence lowerThan: TernaryPrecedence } func %%%<T, U>(x: T, y: U) -> Int { return 1 } func foo() throws -> Int { return 0 } func bar() throws -> Int { return 0 } var x = try foo() + bar() x = try foo() + bar() x += try foo() + bar() x += try foo() %%%% bar() // expected-error {{'try' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{21-21=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{21-21=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{21-21=try! }} x += try foo() %%% bar() x = foo() + try bar() // expected-error {{'try' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} var y = true ? try foo() : try bar() + 0 var z = true ? try foo() : try bar() %%% 0 // expected-error {{'try' following conditional operator does not cover everything to its right}} var a = try! foo() + bar() a = try! foo() + bar() a += try! foo() + bar() a += try! foo() %%%% bar() // expected-error {{'try!' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{22-22=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{22-22=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{22-22=try! }} a += try! foo() %%% bar() a = foo() + try! bar() // expected-error {{'try!' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} var b = true ? try! foo() : try! bar() + 0 var c = true ? try! foo() : try! bar() %%% 0 // expected-error {{'try!' following conditional operator does not cover everything to its right}} infix operator ?+= : AssignmentPrecedence func ?+=(lhs: inout Int?, rhs: Int?) { lhs = lhs! + rhs! } var i = try? foo() + bar() let _: Double = i // expected-error {{cannot convert value of type 'Int?' to specified type 'Double'}} i = try? foo() + bar() i ?+= try? foo() + bar() i ?+= try? foo() %%%% bar() // expected-error {{'try?' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{23-23=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{23-23=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{23-23=try! }} i ?+= try? foo() %%% bar() _ = foo() == try? bar() // expected-error {{'try?' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} _ = (try? foo()) == bar() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{21-21=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{21-21=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{21-21=try! }} _ = foo() == (try? bar()) // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} _ = (try? foo()) == (try? bar()) let j = true ? try? foo() : try? bar() + 0 let k = true ? try? foo() : try? bar() %%% 0 // expected-error {{'try?' following conditional operator does not cover everything to its right}} try let singleLet = foo() // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{21-21=try }} try var singleVar = foo() // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{21-21=try }} try let uninit: Int // expected-error {{'try' must be placed on the initial value expression}} try let (destructure1, destructure2) = (foo(), bar()) // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{40-40=try }} try let multi1 = foo(), multi2 = bar() // expected-error {{'try' must be placed on the initial value expression}} expected-error 2 {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{18-18=try }} expected-note@-1 {{did you mean to use 'try'?}} {{34-34=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{18-18=try? }} expected-note@-2 {{did you mean to handle error as optional value?}} {{34-34=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{18-18=try! }} expected-note@-3 {{did you mean to disable error propagation?}} {{34-34=try! }} class TryDecl { // expected-note {{in declaration of 'TryDecl'}} try let singleLet = foo() // expected-error {{'try' must be placed on the initial value expression}} {{3-7=}} {{23-23=try }} // expected-error @-1 {{call can throw, but errors cannot be thrown out of a property initializer}} try var singleVar = foo() // expected-error {{'try' must be placed on the initial value expression}} {{3-7=}} {{23-23=try }} // expected-error @-1 {{call can throw, but errors cannot be thrown out of a property initializer}} try // expected-error {{expected declaration}} func method() {} } func test() throws -> Int { try while true { // expected-error {{'try' cannot be used with 'while'}} try break // expected-error {{'try' cannot be used with 'break'}} } try throw // expected-error {{'try' must be placed on the thrown expression}} {{3-7=}} {{3-3=try }} expected-error {{expected expression in 'throw' statement}} ; // Reset parser. try return // expected-error {{'try' cannot be used with 'return'}} expected-error {{non-void function should return a value}} ; // Reset parser. try throw foo() // expected-error {{'try' must be placed on the thrown expression}} {{3-7=}} {{13-13=try }} // expected-error@-1 {{thrown expression type 'Int' does not conform to 'Error'}} try return foo() // expected-error {{'try' must be placed on the returned expression}} {{3-7=}} {{14-14=try }} } // Test operators. func *(a : String, b : String) throws -> Int { return 42 } let _ = "foo" * // expected-error {{operator can throw but expression is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{9-9=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{9-9=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{9-9=try! }} "bar" let _ = try! "foo"*"bar" let _ = try? "foo"*"bar" let _ = (try? "foo"*"bar") ?? 0 // <rdar://problem/21414023> Assertion failure when compiling function that takes throwing functions and rethrows func rethrowsDispatchError(handleError: ((Error) throws -> ()), body: () throws -> ()) rethrows { do { body() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} } catch { } } // <rdar://problem/21432429> Calling rethrows from rethrows crashes Swift compiler struct r21432429 { func x(_ f: () throws -> ()) rethrows {} func y(_ f: () throws -> ()) rethrows { x(f) // expected-error {{call can throw but is not marked with 'try'}} expected-note {{call is to 'rethrows' function, but argument function can throw}} } } // <rdar://problem/21427855> Swift 2: Omitting try from call to throwing closure in rethrowing function crashes compiler func callThrowingClosureWithoutTry(closure: (Int) throws -> Int) rethrows { closure(0) // expected-error {{call can throw but is not marked with 'try'}} expected-warning {{result of call to function returning 'Int' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{3-3=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{3-3=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{3-3=try! }} } func producesOptional() throws -> Int? { return nil } let singleOptional = try? producesOptional() let _: String = singleOptional // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} let _ = (try? foo())!! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} func producesDoubleOptional() throws -> Int?? { return 3 } let _: String = try? producesDoubleOptional() // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} func maybeThrow() throws {} try maybeThrow() // okay try! maybeThrow() // okay try? maybeThrow() // okay since return type of maybeThrow is Void _ = try? maybeThrow() // okay let _: () -> Void = { try! maybeThrow() } // okay let _: () -> Void = { try? maybeThrow() } // okay since return type of maybeThrow is Void if try? maybeThrow() { // expected-error {{cannot be used as a boolean}} {{4-4=((}} {{21-21=) != nil)}} } let _: Int = try? foo() // expected-error {{value of optional type 'Int?' not unwrapped; did you mean to use 'try!' or chain with '?'?}} {{14-18=try!}} class X {} func test(_: X) {} func producesObject() throws -> AnyObject { return X() } test(try producesObject()) // expected-error {{'AnyObject' is not convertible to 'X'; did you mean to use 'as!' to force downcast?}} {{26-26= as! X}} _ = "a\(try maybeThrow())b" _ = try "a\(maybeThrow())b" _ = "a\(maybeThrow())" // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{9-9=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{9-9=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{9-9=try! }} extension DefaultStringInterpolation { mutating func appendInterpolation() throws {} } _ = try "a\()b" _ = "a\()b" // expected-error {{interpolation can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} _ = try "\() \(1)" func testGenericOptionalTry<T>(_ call: () throws -> T ) { let _: String = try? call() // expected-error {{cannot convert value of type 'T?' to specified type 'String'}} } func genericOptionalTry<T>(_ call: () throws -> T ) -> T? { let x = try? call() // no error expected return x } // Test with a non-optional type let _: String = genericOptionalTry({ () throws -> Int in return 3 }) // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} // Test with an optional type let _: String = genericOptionalTry({ () throws -> Int? in return nil }) // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} func produceAny() throws -> Any { return 3 } let _: Int? = try? produceAny() as? Int // good let _: Int? = (try? produceAny()) as? Int // good let _: String = try? produceAny() as? Int // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} let _: String = (try? produceAny()) as? Int // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} struct ThingProducer { func produceInt() throws -> Int { return 3 } func produceIntNoThrowing() -> Int { return 3 } func produceAny() throws -> Any { return 3 } func produceOptionalAny() throws -> Any? { return 3 } func produceDoubleOptionalInt() throws -> Int?? { return 3 } } let optProducer: ThingProducer? = ThingProducer() let _: Int? = try? optProducer?.produceInt() let _: Int = try? optProducer?.produceInt() // expected-error {{cannot convert value of type 'Int?' to specified type 'Int'}} let _: String = try? optProducer?.produceInt() // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} let _: Int?? = try? optProducer?.produceInt() // This was the expected type before Swift 5, but this still works; just adds more optional-ness let _: Int? = try? optProducer?.produceIntNoThrowing() // expected-warning {{no calls to throwing functions occur within 'try' expression}} let _: Int? = (try? optProducer?.produceAny()) as? Int // good let _: Int? = try? optProducer?.produceAny() as? Int // good let _: Int?? = try? optProducer?.produceAny() as? Int // good let _: String = try? optProducer?.produceAny() as? Int // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} let _: String = try? optProducer?.produceDoubleOptionalInt() // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} let producer = ThingProducer() let _: Int = try? producer.produceDoubleOptionalInt() // expected-error {{cannot convert value of type 'Int??' to specified type 'Int'}} // We don't offer 'try!' here because it would not change the type of the expression in Swift 5+ let _: Int? = try? producer.produceDoubleOptionalInt() // expected-error {{cannot convert value of type 'Int??' to specified type 'Int?'}} let _: Int?? = try? producer.produceDoubleOptionalInt() // good let _: Int??? = try? producer.produceDoubleOptionalInt() // good let _: String = try? producer.produceDoubleOptionalInt() // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} // rdar://problem/46742002 protocol Dummy : class {} class F<T> { func wait() throws -> T { fatalError() } } func bar(_ a: F<Dummy>, _ b: F<Dummy>) { _ = (try? a.wait()) === (try? b.wait()) }
apache-2.0
800c45205a34882c30bd446716b7c50e
57.79562
251
0.615767
3.888487
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat.SDK/Controllers/OfflineFormViewController.swift
1
3187
// // OfflineFormViewController.swift // Rocket.Chat // // Created by Lucas Woo on 7/16/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import UIKit class OfflineFormViewController: UITableViewController, LivechatManagerInjected { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var messageTextView: UITextView! @IBOutlet var sectionHeader: UIView! @IBOutlet weak var offlineMessageLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = livechatManager.offlineTitle offlineMessageLabel.text = livechatManager.offlineMessage let messageLabelSize = offlineMessageLabel.sizeThatFits(CGSize(width: self.view.frame.width - 16, height: CGFloat.infinity)) offlineMessageLabel.heightAnchor.constraint(equalToConstant: messageLabelSize.height).isActive = true var frame = sectionHeader.frame frame.size = CGSize(width: self.view.frame.width, height: 8 + 16 + 4 + messageLabelSize.height + 8) sectionHeader.frame = frame } // MARK: - Actions @IBAction func didTouchCancelButton(_ sender: UIBarButtonItem) { dismissSelf() } func dismissSelf() { self.dismiss(animated: true, completion: nil) } @IBAction func didTouchSendButton(_ sender: UIBarButtonItem) { guard let email = emailField.text else { return } guard let name = nameField.text else { return } guard let message = messageTextView.text else { return } LoaderView.showLoader(for: self.view, preset: .white) livechatManager.sendOfflineMessage(email: email, name: name, message: message) { LoaderView.hideLoader(for: self.view) let alert = UIAlertController(title: self.livechatManager.title, message: self.livechatManager.offlineSuccessMessage, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in self.dismissSelf() }) self.present(alert, animated: true, completion: nil) } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 0: return sectionHeader?.frame.size.height ?? 0 default: return super.tableView(tableView, heightForHeaderInSection: section) } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 0: return sectionHeader default: return super.tableView(tableView, viewForHeaderInSection: section) } } } extension OfflineFormViewController: UITextFieldDelegate { public func textFieldShouldReturn(_ textField: UITextField) -> Bool { let nextTag = textField.tag + 1 if let nextResponder = textField.superview?.viewWithTag(nextTag) { nextResponder.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } }
mit
2e6f26c814ba046c8ceee333d1edd869
34.010989
159
0.667294
4.970359
false
false
false
false
Dax220/Swifty_HTTP
SwiftyHttp/SHDataRequest.swift
2
872
// // SHDataRequest.swift // SwiftyHttp // // Created by Максим on 18.08.17. // Copyright © 2017 Maks. All rights reserved. // import Foundation open class SHDataRequest: SHRequest { public var failure: FailureHTTPCallBack? public var success: SuccessHTTPCallBack? @discardableResult public func send() -> URLSessionDataTask { configureRequest() let dataTask = SHDataTaskManager.createDataTaskWithRequest(request: self, completion: success, failure: self.failure) dataTask.resume() return dataTask } @discardableResult public func send(completion: SuccessHTTPCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDataTask { success = completion self.failure = failure return send() } }
mit
e39a4973ce31957fffd3ed224a5bcab2
23.714286
125
0.634682
4.887006
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
1 - Getting Started/3 - Operators/lab/Lab - Operators.playground/Pages/2. App Exercise - Fitness Calculations.xcplaygroundpage/Contents.swift
1
2068
/*: ## App Exercise - Fitness Calculations >These exercises reinforce Swift concepts in the context of a fitness tracking app. Your fitness tracker keeps track of users' heart rate, but you might also want to display their average heart rate over the last hour. Create three constants, `heartRate1`, `heartRate2`, and `heartRate3`. Give each constant a different value between 60 and 100. Create a constant `addedHR` equal to the sum of all three heart rates. Now create a constant called `averageHR` that equals `addedHR` divided by 3 to get the average. Print the result. */ let heartRate = 60 let heartRate2 = 72 let heartRate3 = 81 let addedHR = heartRate + heartRate2 + heartRate3 let averageHR = addedHR / 3 print(averageHR) /*: Now create three more constants, `heartRate1D`, `heartRate2D`, and `heartRate3D`, equal to the same values as `heartRate1`, `heartRate2`, and `heartRate3`. These new constants should be of type `Double`. Create a constant `addedHRD` equal to the sum of all three heart rates. Create a constant called `averageHRD` that equals the `addedHRD` divided by 3 to get the average of your new heart rate constants. Print the result. Does this differ from your previous average? Why or why not? */ let heartRate1D = Double(heartRate) let heartRate2D = Double(heartRate2) let heartRate3D = Double(heartRate3) let addedHRD = heartRate1D + heartRate2D + heartRate3D let averageHRD = addedHRD / 3 print(averageHRD) /*: Imagine that partway through the day a user has taken 3,467 steps out of the 10,000 step goal. Create constants `steps` and `goal`. Both will need to be of type `Double` so that you can perform accurate calculations. `steps` should be assigned the value 3,467, and `goal` should be assigned 10,000. Create a constant `percentOfGoal` that equals an expression that evaluates to the percent of the goal that has been achieved so far. */ let steps: Double = 3_467 let goal: Double = 10_000 let percentOfGoal = steps / goal //: [Previous](@previous) | page 2 of 8 | [Next: Exercise - Compound Assignment](@next)
mit
5317819bb78444cecaccf6a5aa9d4d44
63.625
486
0.759188
3.939048
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
Example/Pods/ZIPFoundation/Sources/ZIPFoundation/Archive+MemoryFile.swift
1
7071
// // Archive+MemoryFile.swift // ZIPFoundation // // Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation #if swift(>=5.0) extension Archive { /// Returns a `Data` object containing a representation of the receiver. public var data: Data? { return memoryFile?.data } static func configureMemoryBacking(for data: Data, mode: AccessMode) -> (UnsafeMutablePointer<FILE>, MemoryFile)? { let posixMode: String switch mode { case .read: posixMode = "rb" case .create: posixMode = "wb+" case .update: posixMode = "rb+" } let memoryFile = MemoryFile(data: data) guard let archiveFile = memoryFile.open(mode: posixMode) else { return nil } if mode == .create { let endOfCentralDirectoryRecord = EndOfCentralDirectoryRecord(numberOfDisk: 0, numberOfDiskStart: 0, totalNumberOfEntriesOnDisk: 0, totalNumberOfEntriesInCentralDirectory: 0, sizeOfCentralDirectory: 0, offsetToStartOfCentralDirectory: 0, zipFileCommentLength: 0, zipFileCommentData: Data()) _ = endOfCentralDirectoryRecord.data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in fwrite(buffer.baseAddress, buffer.count, 1, archiveFile) // Errors handled during read } } return (archiveFile, memoryFile) } } class MemoryFile { private(set) var data: Data private var offset = 0 init(data: Data = Data()) { self.data = data } func open(mode: String) -> UnsafeMutablePointer<FILE>? { let cookie = Unmanaged.passRetained(self) let writable = mode.count > 0 && (mode.first! != "r" || mode.last! == "+") let append = mode.count > 0 && mode.first! == "a" #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let result = writable ? funopen(cookie.toOpaque(), readStub, writeStub, seekStub, closeStub) : funopen(cookie.toOpaque(), readStub, nil, seekStub, closeStub) #else let stubs = cookie_io_functions_t(read: readStub, write: writeStub, seek: seekStub, close: closeStub) let result = fopencookie(cookie.toOpaque(), mode, stubs) #endif if append { fseek(result, 0, SEEK_END) } return result } } private extension MemoryFile { func readData(buffer: UnsafeMutableRawBufferPointer) -> Int { let size = min(buffer.count, data.count-offset) let start = data.startIndex data.copyBytes(to: buffer.bindMemory(to: UInt8.self), from: start+offset..<start+offset+size) offset += size return size } func writeData(buffer: UnsafeRawBufferPointer) -> Int { let start = data.startIndex if offset < data.count && offset+buffer.count > data.count { data.removeSubrange(start+offset..<start+data.count) } else if offset > data.count { data.append(Data(count: offset-data.count)) } if offset == data.count { data.append(buffer.bindMemory(to: UInt8.self)) } else { let start = data.startIndex // May have changed in earlier mutation data.replaceSubrange(start+offset..<start+offset+buffer.count, with: buffer.bindMemory(to: UInt8.self)) } offset += buffer.count return buffer.count } func seek(offset: Int, whence: Int32) -> Int { var result = -1 if whence == SEEK_SET { result = offset } else if whence == SEEK_CUR { result = self.offset + offset } else if whence == SEEK_END { result = data.count + offset } self.offset = result return self.offset } } private func fileFromCookie(cookie: UnsafeRawPointer) -> MemoryFile { return Unmanaged<MemoryFile>.fromOpaque(cookie).takeUnretainedValue() } private func closeStub(_ cookie: UnsafeMutableRawPointer?) -> Int32 { if let cookie = cookie { Unmanaged<MemoryFile>.fromOpaque(cookie).release() } return 0 } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) private func readStub(_ cookie: UnsafeMutableRawPointer?, _ bytePtr: UnsafeMutablePointer<Int8>?, _ count: Int32) -> Int32 { guard let cookie = cookie, let bytePtr = bytePtr else { return 0 } return Int32(fileFromCookie(cookie: cookie).readData( buffer: UnsafeMutableRawBufferPointer(start: bytePtr, count: Int(count)))) } private func writeStub(_ cookie: UnsafeMutableRawPointer?, _ bytePtr: UnsafePointer<Int8>?, _ count: Int32) -> Int32 { guard let cookie = cookie, let bytePtr = bytePtr else { return 0 } return Int32(fileFromCookie(cookie: cookie).writeData( buffer: UnsafeRawBufferPointer(start: bytePtr, count: Int(count)))) } private func seekStub(_ cookie: UnsafeMutableRawPointer?, _ offset: fpos_t, _ whence: Int32) -> fpos_t { guard let cookie = cookie else { return 0 } return fpos_t(fileFromCookie(cookie: cookie).seek(offset: Int(offset), whence: whence)) } #else private func readStub(_ cookie: UnsafeMutableRawPointer?, _ bytePtr: UnsafeMutablePointer<Int8>?, _ count: Int) -> Int { guard let cookie = cookie, let bytePtr = bytePtr else { return 0 } return fileFromCookie(cookie: cookie).readData( buffer: UnsafeMutableRawBufferPointer(start: bytePtr, count: count)) } private func writeStub(_ cookie: UnsafeMutableRawPointer?, _ bytePtr: UnsafePointer<Int8>?, _ count: Int) -> Int { guard let cookie = cookie, let bytePtr = bytePtr else { return 0 } return fileFromCookie(cookie: cookie).writeData( buffer: UnsafeRawBufferPointer(start: bytePtr, count: count)) } private func seekStub(_ cookie: UnsafeMutableRawPointer?, _ offset: UnsafeMutablePointer<Int>?, _ whence: Int32) -> Int32 { guard let cookie = cookie, let offset = offset else { return 0 } let result = fileFromCookie(cookie: cookie).seek(offset: Int(offset.pointee), whence: whence) if result >= 0 { offset.pointee = result return 0 } else { return -1 } } #endif #endif
bsd-3-clause
e60df67d9508bcd9643c4092ea51337c
38.719101
120
0.579774
4.620915
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/View/Positioning/ViewStackHorizontal.swift
1
2427
// // ViewStackHorizontal.swift // OOSwift // // Created by Karsten Litsche on 01.09.17. // // import UIKit // TODO: change it so it doesnt has to be last public let HorizontalStretched: Float = -1 /** A view container that present the contents horizontal ordered. Note: Last view ignores it's width and stretches to end (use HorizontalStretched to tell)! Add a VrSpace at end if you don't like it. Visual: e.g. 3 contents |content1|content2|coooontent3| */ public final class ViewStackHorizontal: OOView { // MARK: init public init(content childs: [(width: Float, view: OOView)]) { guard childs.count != 0 else { fatalError("A container without childs doesn't make any sense!") } guard childs.last!.width == HorizontalStretched else { fatalError("Last element will be stretched, use width=HorizontalStretched!") } self.childs = childs } // MARK: protocol OOView private var _ui: UIView? public var ui: UIView { if _ui == nil { _ui = createView() } return _ui! } public func setNeedsRefresh() { childs.forEach { $0.view.setNeedsRefresh() } } // MARK: private private let childs: [(width: Float, view: OOView)] private func createView() -> UIView { let view = PointInsideCheckingView() view.backgroundColor = UIColor.clear addChilds(toView: view) return view } private func addChilds(toView parentView: UIView) { let last = childs.last!.view var leadingAnchor = parentView.leadingAnchor childs.forEach { (width: Float, view: OOView) in let childView = view.ui childView.translatesAutoresizingMaskIntoConstraints = false parentView.addSubview(childView) childView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true childView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true childView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true if view === last { childView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true } else { childView.widthAnchor.constraint(equalToConstant: CGFloat(width)).isActive = true leadingAnchor = childView.trailingAnchor } } } }
mit
61af46ce079d967105b62416adfb550c
32.246575
141
0.644417
4.730994
false
false
false
false
linkedin/LayoutKit
Sources/Layouts/LabelLayout.swift
1
7642
// Copyright 2016 LinkedIn Corp. // 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. import UIKit /** Layout for a UILabel. */ open class LabelLayout<Label: UILabel>: BaseLayout<Label>, ConfigurableLayout { public let text: Text public let font: UIFont public let numberOfLines: Int public let lineHeight: CGFloat public let lineBreakMode: NSLineBreakMode public init(text: Text, font: UIFont = LabelLayoutDefaults.defaultFont, lineHeight: CGFloat? = nil, numberOfLines: Int = LabelLayoutDefaults.defaultNumberOfLines, lineBreakMode: NSLineBreakMode = LabelLayoutDefaults.defaultLineBreakMode, alignment: Alignment = LabelLayoutDefaults.defaultAlignment, flexibility: Flexibility = LabelLayoutDefaults.defaultFlexibility, viewReuseId: String? = nil, config: ((Label) -> Void)? = nil) { self.text = text self.numberOfLines = numberOfLines self.font = font self.lineHeight = lineHeight ?? font.lineHeight self.lineBreakMode = lineBreakMode super.init(alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, config: config) } init(attributedString: NSAttributedString, font: UIFont = LabelLayoutDefaults.defaultFont, lineHeight: CGFloat? = nil, numberOfLines: Int = LabelLayoutDefaults.defaultNumberOfLines, lineBreakMode: NSLineBreakMode = LabelLayoutDefaults.defaultLineBreakMode, alignment: Alignment = LabelLayoutDefaults.defaultAlignment, flexibility: Flexibility = LabelLayoutDefaults.defaultFlexibility, viewReuseId: String? = nil, viewClass: Label.Type? = nil, config: ((Label) -> Void)? = nil) { self.text = .attributed(attributedString) self.numberOfLines = numberOfLines self.font = font self.lineHeight = lineHeight ?? font.lineHeight self.lineBreakMode = lineBreakMode super.init(alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, viewClass: viewClass ?? Label.self, config: config) } init(string: String, font: UIFont = LabelLayoutDefaults.defaultFont, lineHeight: CGFloat? = nil, numberOfLines: Int = LabelLayoutDefaults.defaultNumberOfLines, lineBreakMode: NSLineBreakMode = LabelLayoutDefaults.defaultLineBreakMode, alignment: Alignment = LabelLayoutDefaults.defaultAlignment, flexibility: Flexibility = LabelLayoutDefaults.defaultFlexibility, viewReuseId: String? = nil, viewClass: Label.Type? = nil, config: ((Label) -> Void)? = nil) { self.text = .unattributed(string) self.numberOfLines = numberOfLines self.font = font self.lineHeight = lineHeight ?? font.lineHeight self.lineBreakMode = lineBreakMode super.init(alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, viewClass: viewClass ?? Label.self, config: config) } // MARK: - Convenience initializers public convenience init(text: String, font: UIFont = LabelLayoutDefaults.defaultFont, lineHeight: CGFloat? = nil, numberOfLines: Int = LabelLayoutDefaults.defaultNumberOfLines, lineBreakMode: NSLineBreakMode = LabelLayoutDefaults.defaultLineBreakMode, alignment: Alignment = LabelLayoutDefaults.defaultAlignment, flexibility: Flexibility = LabelLayoutDefaults.defaultFlexibility, viewReuseId: String? = nil, config: ((Label) -> Void)? = nil) { self.init(text: .unattributed(text), font: font, lineHeight: lineHeight, numberOfLines: numberOfLines, lineBreakMode: lineBreakMode, alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, config: config) } public convenience init(attributedText: NSAttributedString, font: UIFont = LabelLayoutDefaults.defaultFont, lineHeight: CGFloat? = nil, numberOfLines: Int = LabelLayoutDefaults.defaultNumberOfLines, lineBreakMode: NSLineBreakMode = LabelLayoutDefaults.defaultLineBreakMode, alignment: Alignment = LabelLayoutDefaults.defaultAlignment, flexibility: Flexibility = LabelLayoutDefaults.defaultFlexibility, viewReuseId: String? = nil, config: ((Label) -> Void)? = nil) { self.init(text: .attributed(attributedText), font: font, lineHeight: lineHeight, numberOfLines: numberOfLines, lineBreakMode: lineBreakMode, alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, config: config) } // MARK: - Layout protocol open func measurement(within maxSize: CGSize) -> LayoutMeasurement { let fittedSize = textSize(within: maxSize) return LayoutMeasurement(layout: self, size: fittedSize.decreasedToSize(maxSize), maxSize: maxSize, sublayouts: []) } private func textSize(within maxSize: CGSize) -> CGSize { var size = text.textSize(within: maxSize, font: font, lineBreakMode: lineBreakMode) if numberOfLines > 0 { let maxHeight = (CGFloat(numberOfLines) * lineHeight).roundedUpToFractionalPoint if size.height > maxHeight { size = CGSize(width: maxSize.width, height: maxHeight) } } return size } open func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement { let frame = alignment.position(size: measurement.size, in: rect) return LayoutArrangement(layout: self, frame: frame, sublayouts: []) } open override func configure(view label: Label) { config?(label) label.numberOfLines = numberOfLines label.lineBreakMode = lineBreakMode label.font = font switch text { case .unattributed(let text): label.text = text case .attributed(let attributedText): label.attributedText = attributedText } } open override var needsView: Bool { return true } } // MARK: - Things that belong in LabelLayout but aren't because LabelLayout is generic. // "Static stored properties not yet supported in generic types" public class LabelLayoutDefaults { public static let defaultNumberOfLines = 0 public static let defaultFont = UILabel().font ?? UIFont.systemFont(ofSize: 17) public static let defaultAlignment = Alignment.topLeading public static let defaultLineBreakMode = NSLineBreakMode.byTruncatingTail public static let defaultFlexibility = Flexibility.flexible }
apache-2.0
067c79bbd20703351cfae21c6f8b55d3
43.17341
144
0.63766
5.737237
false
true
false
false
chrisamanse/iOS-NSDate-Utilities
NSDate_Extensions/NSDate+Periods.swift
1
5573
// // NSDate+Periods.swift // NSDate_Extensions // // Created by Chris Amanse on 5/12/15. // Copyright (c) 2015 Joe Christopher Paul Amanse. All rights reserved. // // This code is licensed under the MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension NSDate { func startOf(unit: NSDateUnit) -> NSDate { switch unit { case .Second: return NSDate.dateWithYear(year, month: month, day: day, hour: hour, minute: minute, andSecond: second)! case .Minute: return NSDate.dateWithYear(year, month: month, day: day, hour: hour, minute: minute, andSecond: 0)! case .Hour: return NSDate.dateWithYear(year, month: month, day: day, hour: hour, minute: 0, andSecond: 0)! case .Day: return calendar.startOfDayForDate(self) case .Week: let components = NSDateComponents() components.year = year components.month = month components.weekOfMonth = weekOfMonth components.weekday = 1 return calendar.dateFromComponents(components)! case .Month: return NSDate.dateWithYear(year, month: month, andDay: 1)! case .Year: return NSDate.dateWithYear(year, month: 1, andDay: 1)! } } func endOf(unit: NSDateUnit) -> NSDate { switch unit { case .Second: let components = NSDateComponents() components.year = year components.month = month components.day = day components.hour = hour components.minute = minute components.second = second components.nanosecond = 999999999 return calendar.dateFromComponents(components)! case .Minute: return NSDate.dateWithYear(year, month: month, day: day, hour: hour, minute: minute, andSecond: 59)! case .Hour: return NSDate.dateWithYear(year, month: month, day: day, hour: hour, minute: 59, andSecond: 59)! case .Day: return NSDate.dateWithYear(year, month: month, day: day, hour: 23, minute: 59, andSecond: 59)! case .Week: let components = NSDateComponents() components.year = year components.month = month components.weekOfMonth = weekOfMonth components.weekday = 7 components.hour = 23 components.minute = 59 components.second = 59 return calendar.dateFromComponents(components)! case .Month: let daysInMonth = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: self).length return NSDate.dateWithYear(year, month: month, day: daysInMonth, hour: 23, minute: 59, andSecond: 59)! case .Year: return NSDate.dateWithYear(year, month: 12, day: 31, hour: 23, minute: 59, andSecond: 59)! } } func next(unit: NSDateUnit) -> NSDate { switch unit { case .Second: return self.dateByAddingTimeInterval(1.seconds) case .Minute: return self.dateByAddingTimeInterval(1.minutes) case .Hour: return self.dateByAddingTimeInterval(1.hours) case .Day: return self.dateByAddingTimeInterval(1.days) case .Week: return self.dateByAddingTimeInterval(1.weeks) case .Month: return NSDate.dateWithYear(year, month: month+1, day: day, hour: hour, minute: minute, andSecond: second)! case .Year: return NSDate.dateWithYear(year+1, month: month, day: day, hour: hour, minute: minute, andSecond: second)! } } func previous(unit: NSDateUnit) -> NSDate { switch unit { case .Second: return self.dateByAddingTimeInterval(-1.seconds) case .Minute: return self.dateByAddingTimeInterval(-1.minutes) case .Hour: return self.dateByAddingTimeInterval(-1.hours) case .Day: return self.dateByAddingTimeInterval(-1.days) case .Week: return self.dateByAddingTimeInterval(-1.weeks) case .Month: return NSDate.dateWithYear(year, month: month-1, day: day, hour: hour, minute: minute, andSecond: second)! case .Year: return NSDate.dateWithYear(year-1, month: month, day: day, hour: hour, minute: minute, andSecond: second)! } } }
mit
4ec729c338c5bd2f39d2ac929de54572
41.219697
118
0.625336
4.605785
false
false
false
false
LQJJ/demo
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/menuUI/DZMRMStatusView.swift
1
2718
// // DZMRMStatusView.swift // DZMeBookRead // // Created by 邓泽淼 on 2017/5/11. // Copyright © 2017年 DZM. All rights reserved. // import UIKit class DZMRMStatusView: DZMRMBaseView { /// 电池 private(set) var batteryView:DZMBatteryView! /// 时间 private(set) var timeLabel:UILabel! /// 标题 private(set) var titleLabel:UILabel! /// 计时器 private(set) var timer:Timer? override func addSubviews() { super.addSubviews() // 背景颜色 backgroundColor = DZMColor_1.withAlphaComponent(0.4) // 电池 batteryView = DZMBatteryView() batteryView.tintColor = DZMColor_3 addSubview(batteryView) // 时间 timeLabel = UILabel() timeLabel.textAlignment = .center timeLabel.font = DZMFont_12 timeLabel.textColor = DZMColor_3 addSubview(timeLabel) // 标题 titleLabel = UILabel() titleLabel.font = DZMFont_12 titleLabel.textColor = DZMColor_3 addSubview(titleLabel) // 初始化调用 didChangeTime() // 添加定时器 addTimer() } override func layoutSubviews() { super.layoutSubviews() // 适配间距 let space = isX ? DZMSpace_1 : 0 // 电池 batteryView.origin = CGPoint(x: width - DZMBatterySize.width - space, y: (height - DZMBatterySize.height)/2) // 时间 let timeLabelW:CGFloat = DZMSizeW(50) timeLabel.frame = CGRect(x: batteryView.frame.minX - timeLabelW, y: 0, width: timeLabelW, height: height) // 标题 titleLabel.frame = CGRect(x: space, y: 0, width: timeLabel.frame.minX - space, height: height) } // MARK: -- 时间相关 /// 添加定时器 func addTimer() { if timer == nil { timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(didChangeTime), userInfo: nil, repeats: true) RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes) } } /// 删除定时器 func removeTimer() { if timer != nil { timer!.invalidate() timer = nil } } /// 时间变化 @objc func didChangeTime() { timeLabel.text = GetCurrentTimerString(dateFormat: "HH:mm") batteryView.batteryLevel = UIDevice.current.batteryLevel } /// 销毁 deinit { removeTimer() } }
apache-2.0
555913b72b7d8a87742c6862c157a868
22.133929
138
0.531069
4.391525
false
false
false
false
bouwman/LayoutResearch
LayoutResearch/Search/SearchDescriptionStepViewController.swift
1
2126
// // SearchDescriptionStepViewController.swift // LayoutResearch // // Created by Tassilo Bouwman on 25.07.17. // Copyright © 2017 Tassilo Bouwman. All rights reserved. // import UIKit import ResearchKit class SearchDescriptionStepViewController: ORKActiveStepViewController { var nextButton: UIButton? override func viewDidLoad() { super.viewDidLoad() guard let searchStep = step as? SearchDescriptionStep else { return } let topMargin = topMarginFor(layout: searchStep.settings.layout, itemDistance: searchStep.settings.itemDistance) let estimatedLayoutHeight = 6 * (searchStep.settings.itemDiameter + searchStep.settings.itemDistance) let yPosition = topMargin + CGFloat(searchStep.settings.targetDescriptionPosition) * estimatedLayoutHeight / 2.8 let size = searchStep.settings.itemDiameter let targetItem = searchStep.settings.targetItem let button = RoundedButton(frame: CGRect(x: 0, y: yPosition, width: size, height: size)) let contentView = UIView(frame: CGRect(x: 0, y: 0, width: size, height: yPosition + size)) let inset = size / Const.Interface.iconInsetDiameterRatio button.identifier = targetItem.identifier button.backgroundColor = UIColor.searchColorFor(id: targetItem.colorId) button.setImage(UIImage.searchImageFor(id: targetItem.shapeId), for: .normal) button.imageView?.contentMode = .scaleAspectFit button.imageEdgeInsets = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) contentView.addSubview(button) customView = contentView // Find next button for subview in self.view.subviews { for subview1 in subview.subviews { for subview2 in subview1.subviews { for subview3 in subview2.subviews { if let button = subview3 as? UIButton { nextButton = button } } } } } } }
mit
1916258539e99a701a64f7b7b0d79853
39.09434
120
0.639529
4.907621
false
false
false
false
cxy921126/SoftSwift
SoftSwift/SoftSwift/AppDelegate.swift
1
3812
// // AppDelegate.swift // SoftSwift // // Created by Mac mini on 16/3/1. // Copyright © 2016年 XMU. All rights reserved. // import UIKit let userHasLoginNote = "userHasLoginNote" ///账号登录标识 var isLogin : Bool = false @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func isLoginOrNot(){ if UserAccount.readAccount() != nil { isLogin = true }else{ isLogin = false } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { isLoginOrNot() //注册通知的监听事件 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.switchController(_:)), name: userHasLoginNote, object: nil) // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() window?.rootViewController = MainTabBarController() window?.makeKeyAndVisible() ///设置全局navibar和tabbar的渲染颜色为orange UINavigationBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().alpha = 0.97 return true } func switchController(notify:NSNotification){ isLogin = true //新建一个uiwindow以代替未登录window window = UIWindow(frame: UIScreen.mainScreen().bounds) if notify.object!.isEqual("toWeibo"){ self.window?.rootViewController = MainTabBarController() self.window?.rootViewController?.view.alpha = 0.0 UIView.animateWithDuration(1.0, animations: { self.window?.rootViewController?.view.alpha = 1.0 }, completion: nil) } if notify.object!.isEqual("toNewfeature"){ window?.rootViewController = NewfeatureCollectionViewController() } window?.makeKeyAndVisible() } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
36403a5067269a46651c14719905b0a8
40.988764
285
0.699224
5.384726
false
false
false
false
nkirby/Humber
_lib/HMCore/_src/Image/Image.swift
1
800
// ======================================================= // HMCore // Nathaniel Kirby // ======================================================= import Foundation // ======================================================= public enum ImageSource { case Local(String) case Remote(String) } public enum ImageType { case JPEG case PNG case GIF } // ======================================================= public struct Image { public let source: ImageSource public let type: ImageType public init(source: ImageSource, type: ImageType) { self.source = source self.type = type } public init(userID: String) { self.source = .Remote("https://avatars3.githubusercontent.com/u/\(userID)?v=3") self.type = .JPEG } }
mit
5c9071dbc73f1d77615dd276d9b70d8f
21.222222
87
0.4425
5.228758
false
false
false
false
AsyncNinja/AsyncNinja
Sources/AsyncNinja/appleOS_Observation.swift
1
3960
// // Copyright (c) 2016-2017 Anton Mironov // // 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. // #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Foundation /// A policy for handling `None` (or `nil`) update of `Channel<Update?, Success>` public enum UpdateWithNoneHandlingPolicy<T> { /// drop `None` (or `nil`) update case drop /// replace `None` (or `nil`) with a specified value case replace(T) } /// **Internal use only** `KeyPathObserver` is an object for managing KVO. final class KeyPathObserver: NSObject, ObservationSessionItem { /// block that is called as new events being observed typealias ObservationBlock = (_ object: Any?, _ changes: [NSKeyValueChangeKey: Any]) -> Void let object: Unmanaged<NSObject> let keyPath: String let options: NSKeyValueObservingOptions let observationBlock: ObservationBlock var isEnabled: Bool { didSet { if isEnabled == oldValue { return } else if isEnabled { object.takeUnretainedValue().addObserver(self, forKeyPath: keyPath, options: options, context: nil) } else { object.takeUnretainedValue().removeObserver(self, forKeyPath: keyPath) } } } init(object: NSObject, keyPath: String, options: NSKeyValueObservingOptions, isEnabled: Bool, observationBlock: @escaping ObservationBlock) { self.object = Unmanaged.passUnretained(object) self.keyPath = keyPath self.options = options self.observationBlock = observationBlock self.isEnabled = isEnabled super.init() if isEnabled { object.addObserver(self, forKeyPath: keyPath, options: options, context: nil) } } deinit { self.isEnabled = false } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { assert(keyPath == self.keyPath) if let change = change { observationBlock(object, change) } } } @objc public protocol ObservationSessionItem: AnyObject { var isEnabled: Bool { get set } } /// An object that is able to control (enable and disable) observation-related channel constructors public class ObservationSession { /// enables or disables observation public var isEnabled: Bool { didSet { if isEnabled != oldValue { for item in items { item?.isEnabled = isEnabled } } } } private var items = QueueOfWeakElements<ObservationSessionItem>() /// designated initializer public init(isEnabled: Bool = true) { self.isEnabled = isEnabled } func insert(item: ObservationSessionItem) { items.push(item) } } #endif
mit
f2019374f855f456b8a09949ef9c65da
32.846154
109
0.661111
4.748201
false
false
false
false
antonyharfield/FirebaseStorageCache
FirebaseStorageCache/UIImageView+FirebaseStorageCache.swift
1
779
// // UIImageView+FirebaseStorageCache.swift // // Created by Ant on 28/12/2016. // Copyright © 2016 Apptitude. All rights reserved. // import UIKit import FirebaseStorage extension UIImageView { public func setImage(storageReference: StorageReference, cache: FirebaseStorageCache = .main) { cache.get(storageReference: storageReference) { data in if let data = data, let image = UIImage(data: data) { self.image = image } } } public func setImage(downloadURL: String, cache: FirebaseStorageCache = .main) { cache.get(downloadURL: downloadURL) { data in if let data = data, let image = UIImage(data: data) { self.image = image } } } }
mit
d8607bfcb0a62ef27efc5f4adfc22043
26.785714
99
0.609254
4.370787
false
false
false
false
magnetsystems/max-ios
MagnetMax/Core/MMHTTPSessionManager.swift
2
7127
/* * Copyright (c) 2015 Magnet Systems, Inc. * 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 AFNetworking enum AuthenticationErrorType: String { case InvalidClientCredentials = "client_credentials" case ExpiredCATToken = "client_access_token" case ExpiredHATToken = "user_access_token" case InvalidRefreshToken = "refresh_token" // Refresh token is (not valid|has expired|not valid for this device) } public class MMHTTPSessionManager: AFHTTPSessionManager { public init(baseURL url: NSURL?, sessionConfiguration configuration: NSURLSessionConfiguration?, serviceAdapter: MMServiceAdapter) { self.serviceAdapter = serviceAdapter super.init(baseURL: url, sessionConfiguration: configuration) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public unowned var serviceAdapter: MMServiceAdapter override public func dataTaskWithRequest(request: NSURLRequest, completionHandler originalCompletionHandler: ((NSURLResponse, AnyObject?, NSError?) -> Void)?) -> NSURLSessionDataTask { let completionHandler = { (response: NSURLResponse, responseObject: AnyObject?, error: NSError?) in guard let URLResponse = response as? NSHTTPURLResponse else { // FIXME: Log this error originalCompletionHandler?(response, responseObject, error) print("Could not cast response to NSHTTPURLResponse") return // fatalError("Could not cast response to NSHTTPURLResponse") } if URLResponse.statusCode == 401 { if let wwwAuthenticateHeader = URLResponse.allHeaderFields["WWW-Authenticate"] as? String { let token = "error=\"" let firstError = wwwAuthenticateHeader.characters.split(",").map { String($0) }.filter { $0.hasPrefix(token) }.first if let e = firstError { let errorType = e.substringWithRange(Range<String.Index>(start: e.startIndex.advancedBy(token.characters.count), end: e.endIndex.advancedBy(-1))) if let authenticationErrorType = AuthenticationErrorType(rawValue: errorType) { switch authenticationErrorType { case .InvalidClientCredentials: self.serviceAdapter.CATToken = nil assert(false, "An invalid set of clientID/clientSecret are used to configure MagnetMax. Please check them again.") NSNotificationCenter.defaultCenter().postNotificationName(MMServiceAdapterDidReceiveInvalidCATTokenNotification, object: nil) case .ExpiredCATToken: // print(request) self.serviceAdapter.authenticateApplicationWithSuccess({ let requestWithNewToken = request.mutableCopy() as! NSMutableURLRequest requestWithNewToken.setValue(self.serviceAdapter.bearerAuthorization(), forHTTPHeaderField: "Authorization") let originalTask = super.dataTaskWithRequest(requestWithNewToken, completionHandler: originalCompletionHandler) originalTask.resume() }) { error in print(error) originalCompletionHandler?(response, responseObject, error) } case .ExpiredHATToken: // print(request) if self.serviceAdapter.refreshToken != nil { self.serviceAdapter.authenticateUserWithSuccess({ let requestWithNewToken = request.mutableCopy() as! NSMutableURLRequest requestWithNewToken.setValue(self.serviceAdapter.bearerAuthorization(), forHTTPHeaderField: "Authorization") let originalTask = super.dataTaskWithRequest(requestWithNewToken, completionHandler: originalCompletionHandler) originalTask.resume() }, failure: { error in print(error) originalCompletionHandler?(response, responseObject, error) }) } else { originalCompletionHandler?(response, responseObject, error) } case .InvalidRefreshToken: // print(request) self.serviceAdapter.HATToken = nil originalCompletionHandler?(response, responseObject, error) } } else { // TODO: Log error // This is possible if the server is not able to decrypt our access token. // Perhaps, the salt changed since the server was rebuilt? self.serviceAdapter.CATToken = nil self.serviceAdapter.HATToken = nil self.serviceAdapter.authenticateApplicationWithSuccess({ let requestWithNewToken = request.mutableCopy() as! NSMutableURLRequest requestWithNewToken.setValue(self.serviceAdapter.bearerAuthorization(), forHTTPHeaderField: "Authorization") let originalTask = super.dataTaskWithRequest(requestWithNewToken, completionHandler: originalCompletionHandler) originalTask.resume() }) { error in print(error) originalCompletionHandler?(response, responseObject, error) } } } } } else { originalCompletionHandler?(response, responseObject, error) } } let task = super.dataTaskWithRequest(request, completionHandler: completionHandler) return task } }
apache-2.0
7577a21d25410c543ac91f8295379930
56.943089
188
0.560685
6.75545
false
false
false
false
czechboy0/XcodeServerSDK
XcodeServerSDK/Server Entities/DeviceSpecification.swift
1
8713
// // DeviceSpecification.swift // XcodeServerSDK // // Created by Honza Dvorsky on 24/06/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation public class DevicePlatform : XcodeServerEntity { public let displayName: String public let version: String public enum PlatformType: String { case Unknown = "unknown" case iOS = "com.apple.platform.iphoneos" case iOS_Simulator = "com.apple.platform.iphonesimulator" case OSX = "com.apple.platform.macosx" case watchOS = "com.apple.platform.watchos" case watchOS_Simulator = "com.apple.platform.watchsimulator" case tvOS = "com.apple.platform.appletvos" case tvOS_Simulator = "com.apple.platform.appletvsimulator" } public enum SimulatorType: String { case iPhone = "com.apple.platform.iphonesimulator" case Watch = "com.apple.platform.watchsimulator" case TV = "com.apple.platform.appletvsimulator" } public let type: PlatformType public let simulatorType: SimulatorType? public required init(json: NSDictionary) throws { self.displayName = try json.stringForKey("displayName") self.version = try json.stringForKey("version") self.type = PlatformType(rawValue: json.optionalStringForKey("identifier") ?? "") ?? .Unknown self.simulatorType = SimulatorType(rawValue: json.optionalStringForKey("simulatorIdentifier") ?? "") try super.init(json: json) } //for just informing the intention - iOS or WatchOS or OS X - and we'll fetch the real ones and replace this placeholder with a fetched one. public init(type: PlatformType) { self.type = type self.displayName = "" self.version = "" self.simulatorType = nil super.init() } public class func OSX() -> DevicePlatform { return DevicePlatform(type: DevicePlatform.PlatformType.OSX) } public class func iOS() -> DevicePlatform { return DevicePlatform(type: DevicePlatform.PlatformType.iOS) } public class func watchOS() -> DevicePlatform { return DevicePlatform(type: DevicePlatform.PlatformType.watchOS) } public class func tvOS() -> DevicePlatform { return DevicePlatform(type: DevicePlatform.PlatformType.tvOS) } public override func dictionarify() -> NSDictionary { //in this case we want everything the way we parsed it. if let original = self.originalJSON { return original } let dictionary = NSMutableDictionary() dictionary["displayName"] = self.displayName dictionary["version"] = self.version dictionary["identifier"] = self.type.rawValue dictionary.optionallyAddValueForKey(self.simulatorType?.rawValue, key: "simulatorIdentifier") return dictionary } } public class DeviceFilter : XcodeServerEntity { public var platform: DevicePlatform public enum FilterType: Int { case AllAvailableDevicesAndSimulators = 0 case AllDevices = 1 case AllSimulators = 2 case SelectedDevicesAndSimulators = 3 public func toString() -> String { switch self { case .AllAvailableDevicesAndSimulators: return "All Available Devices and Simulators" case .AllDevices: return "All Devices" case .AllSimulators: return "All Simulators" case .SelectedDevicesAndSimulators: return "Selected Devices and Simulators" } } public static func availableFiltersForPlatform(platformType: DevicePlatform.PlatformType) -> [FilterType] { switch platformType { case .iOS, .tvOS: return [ .AllAvailableDevicesAndSimulators, .AllDevices, .AllSimulators, .SelectedDevicesAndSimulators ] case .OSX, .watchOS: return [ .AllAvailableDevicesAndSimulators ] default: return [] } } } public let filterType: FilterType public enum ArchitectureType: Int { case Unknown = -1 case iOS_Like = 0 //also watchOS and tvOS case OSX_Like = 1 public static func architectureFromPlatformType(platformType: DevicePlatform.PlatformType) -> ArchitectureType { switch platformType { case .iOS, .iOS_Simulator, .watchOS, .watchOS_Simulator, .tvOS, .tvOS_Simulator, .Unknown: return .iOS_Like case .OSX: return .OSX_Like } } } public let architectureType: ArchitectureType //TODO: ditto, find out more. public required init(json: NSDictionary) throws { self.platform = try DevicePlatform(json: try json.dictionaryForKey("platform")) self.filterType = FilterType(rawValue: try json.intForKey("filterType")) ?? .AllAvailableDevicesAndSimulators self.architectureType = ArchitectureType(rawValue: json.optionalIntForKey("architectureType") ?? -1) ?? .Unknown try super.init(json: json) } public init(platform: DevicePlatform, filterType: FilterType, architectureType: ArchitectureType) { self.platform = platform self.filterType = filterType self.architectureType = architectureType super.init() } public override func dictionarify() -> NSDictionary { return [ "filterType": self.filterType.rawValue, "architectureType": self.architectureType.rawValue, "platform": self.platform.dictionarify() ] } } public class DeviceSpecification : XcodeServerEntity { public let deviceIdentifiers: [String] public let filters: [DeviceFilter] public required init(json: NSDictionary) throws { self.deviceIdentifiers = try json.arrayForKey("deviceIdentifiers") self.filters = try XcodeServerArray(try json.arrayForKey("filters")) try super.init(json: json) } public init(filters: [DeviceFilter], deviceIdentifiers: [String]) { self.deviceIdentifiers = deviceIdentifiers self.filters = filters super.init() } /** Initializes a new DeviceSpecification object with only a list of tested device ids. This is a convenience initializer for compatibility with old Xcode 6 bots that are still hanging around on old servers. */ public init(testingDeviceIDs: [String]) { self.deviceIdentifiers = testingDeviceIDs self.filters = [] super.init() } public override func dictionarify() -> NSDictionary { return [ "deviceIdentifiers": self.deviceIdentifiers, "filters": self.filters.map({ $0.dictionarify() }) ] } // MARK: Convenience methods public class func OSX() -> DeviceSpecification { let platform = DevicePlatform.OSX() let filter = DeviceFilter(platform: platform, filterType: .AllAvailableDevicesAndSimulators, architectureType: .OSX_Like) let spec = DeviceSpecification(filters: [filter], deviceIdentifiers: []) return spec } public class func iOS(filterType: DeviceFilter.FilterType, deviceIdentifiers: [String]) -> DeviceSpecification { let platform = DevicePlatform.iOS() let filter = DeviceFilter(platform: platform, filterType: filterType, architectureType: .iOS_Like) let spec = DeviceSpecification(filters: [filter], deviceIdentifiers: deviceIdentifiers) return spec } public class func watchOS() -> DeviceSpecification { let platform = DevicePlatform.watchOS() let filter = DeviceFilter(platform: platform, filterType: .AllAvailableDevicesAndSimulators, architectureType: .iOS_Like) let spec = DeviceSpecification(filters: [filter], deviceIdentifiers: []) return spec } public class func tvOS() -> DeviceSpecification { let platform = DevicePlatform.tvOS() let filter = DeviceFilter(platform: platform, filterType: .AllAvailableDevicesAndSimulators, architectureType: .iOS_Like) let spec = DeviceSpecification(filters: [filter], deviceIdentifiers: []) return spec } }
mit
9feae73f401944d7d23fb8960ccc6abf
33.848
144
0.626722
5.201194
false
false
false
false
nghiaphunguyen/NKit
NKit/Source/Manager/NKLogEventManager.swift
1
978
// // NKNKLogEventManager.swift // NKit // // Created by Nghia Nguyen on 11/1/16. // Copyright © 2016 Nghia Nguyen. All rights reserved. // import Foundation public enum NKEventType { case screen case normal } public protocol NKLogEventManagerProtocol { func logEvent(name: String, type: NKEventType, extraInfo: [String : NSObject]?) } public final class NKLogEventManager { public static let sharedInstance = NKLogEventManager() fileprivate var eventManagers = [NKLogEventManagerProtocol]() public func registerEventManager(_ eventManager: NKLogEventManagerProtocol) { self.eventManagers.append(eventManager) } public func log(name: String, type: NKEventType = .normal, extraInfo: [String : NSObject]? = nil) { for eventManager in self.eventManagers { eventManager.logEvent(name: name, type: type, extraInfo: extraInfo) } } } public let NKEVENT = NKLogEventManager.sharedInstance
mit
b241a11d0f48f3e411edad35e811c293
26.138889
103
0.706244
4.247826
false
false
false
false
away4m/Vendors
Vendors/Extensions/UICollectionView.swift
1
9874
// // UICollectionView.swift // Pods // // Ali Kiran on 11/24/16. // // #if canImport(UIKit) import UIKit #if !os(watchOS) // MARK: - Properties public extension UICollectionView { /// SwifterSwift: Index path of last item in collectionView. public var indexPathForLastItem: IndexPath? { return indexPathForLastItem(inSection: lastSection) } /// SwifterSwift: Index of last section in collectionView. public var lastSection: Int { return numberOfSections > 0 ? numberOfSections - 1 : 0 } } public extension UICollectionView { // SwifterSwift: Number of all items in all sections of collectionView. /// /// - Returns: The count of all rows in the collectionView. public func numberOfItems() -> Int { var section = 0 var itemsCount = 0 while section < numberOfSections { itemsCount += numberOfItems(inSection: section) section += 1 } return itemsCount } /// SwifterSwift: IndexPath for last item in section. /// /// - Parameter section: section to get last item in. /// - Returns: optional last indexPath for last item in section (if applicable). public func indexPathForLastItem(inSection section: Int) -> IndexPath? { guard section >= 0 else { return nil } guard section < numberOfSections else { return nil } guard numberOfItems(inSection: section) > 0 else { return IndexPath(item: 0, section: section) } return IndexPath(item: numberOfItems(inSection: section) - 1, section: section) } /// SwifterSwift: Dequeue reusable UICollectionViewCell using class name. /// /// - Parameters: /// - name: UICollectionViewCell type. /// - indexPath: location of cell in collectionView. /// - Returns: UICollectionViewCell object with associated class name. public func dequeueReusableCell<T: UICollectionViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withReuseIdentifier: String(describing: name), for: indexPath) as? T else { fatalError("Couldn't find UICollectionViewCell for \(String(describing: name))") } return cell } /// SwifterSwift: Dequeue reusable UICollectionReusableView using class name. /// /// - Parameters: /// - kind: the kind of supplementary view to retrieve. This value is defined by the layout object. /// - name: UICollectionReusableView type. /// - indexPath: location of cell in collectionView. /// - Returns: UICollectionReusableView object with associated class name. public func dequeueReusableSupplementaryView<T: UICollectionReusableView>(ofKind kind: String, withClass name: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: String(describing: name), for: indexPath) as? T else { fatalError("Couldn't find UICollectionReusableView for \(String(describing: name))") } return cell } /// SwifterSwift: Register UICollectionReusableView using class name. /// /// - Parameters: /// - kind: the kind of supplementary view to retrieve. This value is defined by the layout object. /// - name: UICollectionReusableView type. public func register<T: UICollectionReusableView>(supplementaryViewOfKind kind: String, withClass name: T.Type) { register(T.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UICollectionViewCell using class name. /// /// - Parameters: /// - nib: Nib file used to create the collectionView cell. /// - name: UICollectionViewCell type. public func register<T: UICollectionViewCell>(nib: UINib?, forCellWithClass name: T.Type) { register(nib, forCellWithReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UICollectionViewCell using class name. /// /// - Parameter name: UICollectionViewCell type. public func register<T: UICollectionViewCell>(cellWithClass name: T.Type) { register(T.self, forCellWithReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UICollectionReusableView using class name. /// /// - Parameters: /// - nib: Nib file used to create the reusable view. /// - kind: the kind of supplementary view to retrieve. This value is defined by the layout object. /// - name: UICollectionReusableView type. public func register<T: UICollectionReusableView>(nib: UINib?, forSupplementaryViewOfKind kind: String, withClass name: T.Type) { register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UICollectionViewCell with .xib file using only its corresponding class. /// Assumes that the .xib filename and cell class has the same name. /// /// - Parameters: /// - name: UICollectionViewCell type. /// - bundleClass: Class in which the Bundle instance will be based on. public func register<T: UICollectionViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) { let identifier = String(describing: name) var bundle: Bundle? if let bundleName = bundleClass { bundle = Bundle(for: bundleName) } register(UINib(nibName: identifier, bundle: bundle), forCellWithReuseIdentifier: identifier) } func registerCells(nibClasses: [AnyClass]) { for eachClass in nibClasses { let classString = String(describing: eachClass) let nib = UINib(nibName: classString, bundle: nil) register(nib, forCellWithReuseIdentifier: classString) } } func registerCells(classes: [AnyClass]) { for eachClass in classes { let classString = String(describing: eachClass) register(eachClass, forCellWithReuseIdentifier: classString) } } public func reload(completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } /** Inserts rows into self. - parameter indices: The rows indices to insert into self. - parameter section: The section in which to insert the rows (optional, defaults to 0). - parameter completion: The completion handler, called after the rows have been inserted (optional). */ public func insert(_ indices: [Int], section: Int = 0, completion: @escaping (Bool) -> Void = { _ in }) { guard !indices.isEmpty else { return } let indexPaths = indices.map { IndexPath(row: $0, section: section) } performBatchUpdates({ self.insertItems(at: indexPaths) }, completion: completion) } /** Deletes rows from self. - parameter indices: The rows indices to delete from self. - parameter section: The section in which to delete the rows (optional, defaults to 0). - parameter completion: The completion handler, called after the rows have been deleted (optional). */ public func delete(_ indices: [Int], section: Int = 0, completion: @escaping (Bool) -> Void = { _ in }) { guard !indices.isEmpty else { return } let indexPaths = indices.map { IndexPath(row: $0, section: section) } performBatchUpdates({ self.deleteItems(at: indexPaths) }, completion: completion) } /** Reloads rows in self. - parameter indices: The rows indices to reload in self. - parameter section: The section in which to reload the rows (optional, defaults to 0). - parameter completion: The completion handler, called after the rows have been reloaded (optional). */ public func reload(_ indices: [Int], section: Int = 0, completion: @escaping (Bool) -> Void = { _ in }) { guard !indices.isEmpty else { return } let indexPaths = indices.map { IndexPath(row: $0, section: section) } performBatchUpdates({ self.reloadItems(at: indexPaths) }, completion: completion) } public var centerPoint: CGPoint { let x = center.x + contentOffset.x let y = center.y + contentOffset.y return CGPoint(x: x, y: y) } public var centerItemIndexPath: IndexPath? { return indexPathForItem(at: centerPoint) } } #endif #endif
mit
11e3b7b4a83ba5ebd4a94d4b3f351ae5
46.471154
163
0.574235
5.704217
false
false
false
false
nghiaphunguyen/NKit
NKit/Source/CustomViews/NKLabel.swift
1
1430
// // NKLabel.swift // FastSell // // Created by Nghia Nguyen on 6/18/16. // Copyright © 2016 vn.fastsell. All rights reserved. // import UIKit open class NKLabel: UILabel { open var edgeInsets: UIEdgeInsets = UIEdgeInsets.zero open var fitBounds: Bool = false open override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { var rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines) if self.fitBounds { rect.origin.y = self.bounds.origin.y } return rect } open override func drawText(in rect: CGRect) { var actualRect = rect if self.fitBounds { actualRect = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines) let height = self.nk_heightWithWidth(width: self.nk_width) if actualRect.size.height < height { actualRect.size.height = height } } return super.drawText(in: actualRect.inset(by: self.edgeInsets)) } open override var intrinsicContentSize: CGSize { var contentSize = super.intrinsicContentSize contentSize.width += self.edgeInsets.left + self.edgeInsets.right contentSize.height += self.edgeInsets.top + self.edgeInsets.bottom return contentSize } }
mit
fba119b8dc597d7b0d63c5aa8964d008
29.404255
112
0.630511
4.609677
false
false
false
false
davejlin/treehouse
swift/swift2/selfie-photo/SelfiePhoto/PhotoMetadataController.swift
1
7223
// // PhotoMetadataController.swift // SelfiePhoto // // Created by Lin David, US-205 on 11/13/16. // Copyright © 2016 Lin David. All rights reserved. // import UIKit import CoreLocation class PhotoMetadataController: UITableViewController { private let photo: UIImage init(photo: UIImage) { self.photo = photo super.init(style: .Grouped) } required init?(coder aDecoder: NSCoder) { fatalError() } // MARK: - Metadata fields private lazy var photoImageView: UIImageView = { let imageView = UIImageView(image: self.photo) imageView.contentMode = .ScaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private lazy var imageViewHeight: CGFloat = { let imgFactor = self.photoImageView.frame.size.height/self.photoImageView.frame.size.width let screenWidth = UIScreen.mainScreen().bounds.size.width return screenWidth * imgFactor }() private lazy var locationLabel: UILabel = { let label = UILabel() label.text = "Tap to add location" label.textColor = .lightGrayColor() label.translatesAutoresizingMaskIntoConstraints = false return label }() private var locationManger: LocationManager! private var location: CLLocation! private lazy var tagsTextField: UITextField = { let textField = UITextField() textField.placeholder = "summer, vacation" textField.translatesAutoresizingMaskIntoConstraints = false return textField }() private lazy var activityIndicator: UIActivityIndicatorView = { let view = UIActivityIndicatorView(activityIndicatorStyle: .Gray) view.translatesAutoresizingMaskIntoConstraints = false view.hidden = true return view }() override func viewDidLoad() { super.viewDidLoad() let saveButton = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: #selector(PhotoMetadataController.savePhotoWithMetadata)) navigationItem.rightBarButtonItem = saveButton } } extension PhotoMetadataController { // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.selectionStyle = .None switch (indexPath.section, indexPath.row) { case (0, 0): cell.contentView.addSubview(photoImageView) NSLayoutConstraint.activateConstraints([ photoImageView.topAnchor.constraintEqualToAnchor(cell.contentView.topAnchor), photoImageView.rightAnchor.constraintEqualToAnchor(cell.contentView.rightAnchor), photoImageView.bottomAnchor.constraintEqualToAnchor(cell.contentView.bottomAnchor), photoImageView.leftAnchor.constraintEqualToAnchor(cell.contentView.leftAnchor) ]) case (1, 0): cell.contentView.addSubview(locationLabel) cell.contentView.addSubview(activityIndicator) NSLayoutConstraint.activateConstraints([ activityIndicator.centerYAnchor.constraintEqualToAnchor(cell.contentView.centerYAnchor), activityIndicator.leftAnchor.constraintEqualToAnchor(cell.contentView.leftAnchor, constant: 20.0), locationLabel.topAnchor.constraintEqualToAnchor(cell.contentView.topAnchor), locationLabel.rightAnchor.constraintEqualToAnchor(cell.contentView.rightAnchor, constant: 16.0), locationLabel.bottomAnchor.constraintEqualToAnchor(cell.contentView.bottomAnchor), locationLabel.leftAnchor.constraintEqualToAnchor(cell.contentView.leftAnchor, constant: 20.0) ]) case (2,0): cell.contentView.addSubview(tagsTextField) NSLayoutConstraint.activateConstraints([ tagsTextField.topAnchor.constraintEqualToAnchor(cell.contentView.topAnchor), tagsTextField.rightAnchor.constraintEqualToAnchor(cell.contentView.rightAnchor, constant: 16.0), tagsTextField.bottomAnchor.constraintEqualToAnchor(cell.contentView.bottomAnchor), tagsTextField.leftAnchor.constraintEqualToAnchor(cell.contentView.leftAnchor, constant: 20.0) ]) default: break } return cell } } // MARK: - Helper Methods extension PhotoMetadataController { func tagsFromTextField() -> [String] { guard let tags = tagsTextField.text else { return [] } let commaSeparatedSubSequences = tags.characters.split { $0 == "," } let commaSeparatedStrings = commaSeparatedSubSequences.map(String.init) let lowerCaseTags = commaSeparatedStrings.map { $0.lowercaseString } return lowerCaseTags.map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } } // MARK: - Persistence extension PhotoMetadataController { @objc private func savePhotoWithMetadata() { let tags = tagsFromTextField() Photo.photoWith(photo, tags: tags, location: location) CoreDataController.save() dismissViewControllerAnimated(true, completion: nil) } } // MARK: - UITableViewDelegate extension PhotoMetadataController { override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch (indexPath.section, indexPath.row) { case (0,0): return imageViewHeight default: return tableView.rowHeight } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch (indexPath.section, indexPath.row) { case (1,0): locationLabel.hidden = true activityIndicator.hidden = false activityIndicator.startAnimating() locationManger = LocationManager() locationManger.onLocationFix = { placemark, error in if let placemark = placemark { self.location = placemark.location self.activityIndicator.stopAnimating() self.activityIndicator.hidden = true self.locationLabel.hidden = false guard let name = placemark.name, city = placemark.locality, area = placemark.administrativeArea else { return } self.locationLabel.text = "\(name), \(city), \(area)" } } default: break } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Photo" case 1: return "Enter a location" case 2: return "Enter tags" default: return nil } } }
unlicense
45853f88fd44125fa364ff09be923c98
38.464481
148
0.664082
5.736299
false
false
false
false
OscarSwanros/swift
test/Migrator/double_fixit_ok.swift
12
851
// RUN: %target-swift-frontend -typecheck %s -swift-version 3 // RUN: rm -rf %t && mkdir -p %t && %target-swift-frontend -typecheck -update-code -primary-file %s -emit-migrated-file-path %t/double_fixit_ok.result -swift-version 3 // RUN: diff -u %s.expected %t/double_fixit_ok.result // RUN: %target-swift-frontend -typecheck %s.expected -swift-version 4 @available(swift, obsoleted: 4, renamed: "Thing.constant___renamed") let ThingConstantGotRenamed = 1 @available(swift, obsoleted: 4, renamed: "Thing.constant_renamed") let ThingConstantWasRenamed = 1 struct Thing { static let constant___renamed = 1 static let constant_renamed = 1 func foo(_ c: Int) {} } class MyClass { func foo() { let _: Thing = { let t = Thing() t.foo(ThingConstantGotRenamed) t.foo(ThingConstantWasRenamed) return t }() } }
apache-2.0
b12a9dd8886ede64b8971ef10491ef24
28.344828
167
0.679201
3.285714
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/Messages/MentionTests.swift
1
3395
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import XCTest @testable import WireDataModel class MentionTests: ZMBaseManagedObjectTest { func createMention(start: Int = 0, length: Int = 1, userId: String = UUID().transportString(), domain: String? = nil) -> WireProtos.Mention { // Make user mentioned user exists if let remoteIdentifier = UUID(uuidString: userId) { let user = ZMUser.insertNewObject(in: uiMOC) user.remoteIdentifier = remoteIdentifier user.domain = domain } return WireProtos.Mention.with { $0.start = Int32(start) $0.length = Int32(length) $0.userID = userId if let domain = domain { $0.qualifiedUserID = WireProtos.QualifiedUserId.with { $0.id = userId $0.domain = domain } } } } func testConstructionOfValidMention_WhenTheUserIsNotFederated() { // given let buffer = createMention() // when let mention = Mention(buffer, context: uiMOC) // then XCTAssertNotNil(mention) } func testConstructionOfValidMention_WhenTheUserIsFederated() { // given let buffer = createMention(domain: UUID().uuidString) // when let mention = Mention(buffer, context: uiMOC) // then XCTAssertNotNil(mention) } func testConstructionOfInvalidMentionRangeCase1() { // given let buffer = createMention(start: 5, length: 0) // when let mention = Mention(buffer, context: uiMOC) // then XCTAssertNil(mention) } func testConstructionOfInvalidMentionRangeCase2() { // given let buffer = createMention(start: 1, length: 0) // when let mention = Mention(buffer, context: uiMOC) // then XCTAssertNil(mention) } func testConstructionOfInvalidMentionRangeCase3() { // given let buffer = createMention(start: -1, length: 1) // when let mention = Mention(buffer, context: uiMOC) // then XCTAssertNil(mention) } func testConstructionOfInvalidMentionRangeCase4() { // given let buffer = createMention(start: 1, length: -1) // when let mention = Mention(buffer, context: uiMOC) // then XCTAssertNil(mention) } func testConstructionOfInvalidMentionUserId() { // given let buffer = createMention(userId: "not-a-valid-uuid") // when let mention = Mention(buffer, context: uiMOC) // then XCTAssertNil(mention) } }
gpl-3.0
6bb104a9048d58fc51d4e7b26224fa61
26.16
145
0.614138
4.600271
false
true
false
false
Ranxan/NetworkService
NetworkService/Classes/ServiceOAuthHandler.swift
1
4438
// // NetworkServiceOAuthHandler.swift // SMS-iOS Template // // Created by Ranxan Adhikari on 5/15/17. // Copyright © 2017 SMS. All rights reserved. // import Foundation import ObjectMapper /** Base model to be received from service API for the authentication tokens.*/ class OAuthTokenModel : BaseModel { var tokenType : String? var expiresIn : Double? var refreshToken : String? var accessToken : String? override init() { super.init() } required init?(map: Map) { super.init(map: map) } override func mapping(map: Map) { tokenType <- map["token_type"] expiresIn <- map["expires_in"] refreshToken <- map["refresh_token"] accessToken <- map["access_token"] } } /** Defines requirements for network service call to refresh the authentication token.*/ struct OAuthTokenServiceRequirements : NetworkServiceDelegate { static var path : String = "/auth/refresh" static var method = NetworkServiceHTTPMethod.post typealias V = OAuthTokenModel /*Response*/ } /** Service manages authentication tokens for OAuth Validations. For the token expired, it resets token values stored in the user defaults, calls API to refresh the tokens and stores new authentication token with refresh token in the userdefaults. */ class OAuthTokenService { static let TAG = "OAuthTokenService" /** Service instances **/ var networkCallCompletionHandler : NetworkServiceCallStatusCallback? static let AUTHENTICATION_TOKEN : String = "AUTHENTICATION_TOKEN" static let AUTHENTICATION_REFRESH_TOKEN : String = "AUTHENTICATION_REFRESH_TOKEN" static var authenticationToken = "" static var authenticationRefreshToken = "" init() { } /*Calls network service API caller to refresh the authentication token. */ func refreshToken(completionCallback : @escaping NetworkServiceCallStatusCallback) { self.networkCallCompletionHandler = completionCallback NetworkService<OAuthTokenServiceRequirements>().call(requestParams : OAuthTokenModel().toJSON()) { data, error in /*Hanlding response in the closure callback..*/ guard let responseData = data, let oAuthModel = responseData.data else { /*Hanlde error..*/ print(error?.errorMessage ?? "ERROR: refreshToken : \(OAuthTokenService.TAG) ") OAuthTokenService.resetAuthTokens() self.networkCallCompletionHandler!(false) return } OAuthTokenService.saveOAuthTokens(authenticationModel: oAuthModel) self.networkCallCompletionHandler!(true) } } /**Persisting authentication tokens .. */ static func saveOAuthTokens(authenticationModel oAuthModel : OAuthTokenModel) -> Void { let userDefaults = UserDefaults.standard userDefaults.set(oAuthModel.refreshToken, forKey: OAuthTokenService.AUTHENTICATION_REFRESH_TOKEN) userDefaults.set(oAuthModel.accessToken, forKey: OAuthTokenService.AUTHENTICATION_TOKEN) OAuthTokenService.authenticationRefreshToken = oAuthModel.refreshToken! OAuthTokenService.authenticationToken = oAuthModel.accessToken! } static func resetAuthTokens() { let userDefaults = UserDefaults.standard userDefaults.removeObject(forKey: OAuthTokenService.AUTHENTICATION_TOKEN) OAuthTokenService.authenticationToken = "" } static func findOAuthToken() -> Bool { if OAuthTokenService.authenticationToken.characters.count == 0 { let userDefaults = UserDefaults.standard if let AUTH_TOKEN = userDefaults.string(forKey: OAuthTokenService.AUTHENTICATION_TOKEN) { OAuthTokenService.authenticationToken = AUTH_TOKEN } } if OAuthTokenService.authenticationToken.characters.count == 0 { return false } return true } static func findOAuthRefreshToken() -> Bool { if OAuthTokenService.authenticationRefreshToken.characters.count == 0 { let userDefaults = UserDefaults.standard if let REFRESH_TOKEN = userDefaults.string(forKey: OAuthTokenService.AUTHENTICATION_REFRESH_TOKEN) { OAuthTokenService.authenticationRefreshToken = REFRESH_TOKEN } } if OAuthTokenService.authenticationRefreshToken.characters.count == 0 { return false } return true } }
mit
e559dedd08b09a8899cd369cd6eceb57
33.130769
186
0.697543
4.94098
false
false
false
false
SimonFairbairn/Stormcloud
Sources/Stormcloud/JSONMetadata.swift
1
1839
// // JSONMetadata.swift // Stormcloud // // Created by Simon Fairbairn on 21/09/2017. // Copyright © 2017 Voyage Travel Apps. All rights reserved. // #if os(macOS) import Cocoa #else import UIKit #endif open class JSONMetadata: StormcloudMetadata { public static let dateFormatter = DateFormatter() /// The name of the device open var device : String public override init() { self.device = UIDevice.current.model super.init() let dateComponents = NSCalendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date()) (dateComponents as NSDateComponents).calendar = NSCalendar.current (dateComponents as NSDateComponents).timeZone = TimeZone(abbreviation: "UTC") JSONMetadata.dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss" if let date = (dateComponents as NSDateComponents).date { self.date = date } else { self.date = Date() } let stringDate = JSONMetadata.dateFormatter.string(from: self.date) self.filename = "\(stringDate)--\(self.device).json" self.type = .json } public override init( path : String ) { JSONMetadata.dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss" var filename = "" var date = Date() var device = UIDevice.current.name filename = path let components = path.components(separatedBy: "--") if components.count > 1 { if let newDate = JSONMetadata.dateFormatter.date(from: components[0]) { date = newDate } device = components[1].replacingOccurrences(of: ".json", with: "") } self.device = device super.init() self.filename = filename self.date = date self.type = .json } } // MARK: - NSCopying extension JSONMetadata : NSCopying { public func copy(with zone: NSZone?) -> Any { let backup = JSONMetadata(path : self.filename) return backup } }
mit
a45e23c4783ebf9c86669c0c6f4cca23
20.372093
118
0.680631
3.568932
false
false
false
false
benlangmuir/swift
test/SILOptimizer/unsafebufferpointer.swift
9
2421
// RUN: %target-swift-frontend -parse-as-library -Osize -emit-ir %s | %FileCheck %s // REQUIRES: swift_stdlib_no_asserts,optimized_stdlib // This is an end-to-end test to ensure that the optimizer generates // optimal code for UnsafeBufferPointer. // CHECK-LABEL: define {{.*}}testIteration // Check if the code contains no traps at all. // CHECK-NOT: unreachable public func testIteration(_ p: UnsafeBufferPointer<Int>) -> Int { var s = 0 // Check for an optimal loop kernel // CHECK: phi // CHECK-NEXT: phi // CHECK-NEXT: bitcast // CHECK-NEXT: load // CHECK-NEXT: getelementptr // CHECK-NEXT: add // CHECK-NEXT: icmp // CHECK-NEXT: br for x in p { s = s &+ x } // CHECK-NOT: unreachable // CHECK: phi // CHECK-NEXT: ret // CHECK-NOT: unreachable return s } // CHECK-LABEL: define {{.*}}testIsEmpty // CHECK: entry: // CHECK-NEXT: icmp // CHECK-NEXT: ret public func testIsEmpty(_ x: UnsafeBufferPointer<UInt>) -> Bool { return x.isEmpty } // CHECK-LABEL: define {{.*}}testCount // CHECK: entry: // CHECK-NEXT: ret public func testCount(_ x: UnsafeBufferPointer<UInt>) -> Int { return x.count } // Within the loop, there should be no extra checks. // CHECK-LABEL: define {{.*}} float {{.*}}testSubscript // The only unconditional branch is into the loop. // CHECK: br label %[[LOOP:[0-9]+]] // // CHECK: [[LOOP]]: // CHECK: phi float [ 0.000000e+00 // CHECK: load float, float* // CHECK: fadd float // CHECK: [[CMP:%[0-9]+]] = icmp eq // CHECK: br i1 [[CMP]], label %.loopexit, label %[[LOOP]] // // CHECK: .loopexit: ; preds = %[[LOOP]] // CHECK: ret float public func testSubscript(_ ubp: UnsafeBufferPointer<Float>) -> Float { var sum: Float = 0 for i in 0 ..< ubp.count { sum += ubp[i] } return sum } // Within the loop, there should be no extra checks. // CHECK-LABEL: define {{.*}} i64 {{.*}}testSubscript // The only unconditional branch is into the loop. // CHECK: br label %[[LOOP:[0-9]+]] // // CHECK: [[LOOP]]: // CHECK: phi i64 [ 0 // CHECK: load i8, i8* // CHECK: zext i8 %{{.*}} to i64 // CHECK: add i64 // CHECK: [[CMP:%[0-9]+]] = icmp eq // CHECK: br i1 [[CMP]], label %[[RET:.*]], label %[[LOOP]] // // CHECK: [[RET]]: ; preds = %[[LOOP]], %{{.*}} // CHECK: ret i64 public func testSubscript(_ ubp: UnsafeRawBufferPointer) -> Int64 { var sum: Int64 = 0 for i in 0 ..< ubp.count { sum &+= Int64(ubp[i]) } return sum }
apache-2.0
5ff0fbfbfcecf88bd82dbc0ccf7b3783
25.604396
84
0.620818
3.276049
false
true
false
false
KrishMunot/swift
test/Inputs/clang-importer-sdk/swift-modules-without-ns/Darwin.swift
1
1025
@_exported import Darwin // Clang module //===----------------------------------------------------------------------===// // MacTypes.h //===----------------------------------------------------------------------===// public let noErr: OSStatus = 0 /// The `Boolean` type declared in MacTypes.h and used throughout Core /// Foundation. /// /// The C type is a typedef for `unsigned char`. public struct DarwinBoolean : BooleanType, BooleanLiteralConvertible { var value: UInt8 public init(_ value: Bool) { self.value = value ? 1 : 0 } /// The value of `self`, expressed as a `Bool`. public var boolValue: Bool { return value != 0 } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self.init(value) } } public // COMPILER_INTRINSIC func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean { return DarwinBoolean(x) } public // COMPILER_INTRINSIC func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool { return Bool(x) }
apache-2.0
f07a9b997592e5a2d38e5b291ab7e58f
25.282051
80
0.582439
4.701835
false
false
false
false
societymedia/SwiftyContainer
SwiftyContainer/SwiftableContainer.swift
1
1264
// // Created by Tony Merante on 1/3/16. // Copyright (c) 2016 Societymedia. All rights reserved. // import Foundation public class SwiftyContainer { private static let sharedInstance = SwiftyContainer() private var container = Dictionary<String, () -> BeSwifty>() init() { } public class var itemCount:Int { return sharedInstance.container.count } class public func bind<T:BeSwifty>(bindableType: T.Type) { SwiftyContainer.bind(bindableType, withScope: .Singleton) } class public func bind<T:BeSwifty>(bindableType: T.Type, withScope scope: SwiftyContainerScope) { let myStr = String(bindableType) if scope == .Singleton { let instance = T() sharedInstance.container[myStr] = { return instance } } else { sharedInstance.container[myStr] = { return T() } } } class public func resolve<T>(swiftType: T.Type) -> T { let myStr = String(swiftType) let value = sharedInstance.container[myStr]!() print(value) return value as! T } class public func empty() { sharedInstance.container.removeAll(keepCapacity: false) } }
apache-2.0
77c5f7a6d85f6e20d7e0e8b035eb1863
21.175439
101
0.602057
4.373702
false
false
false
false
diegosanchezr/Chatto
ChattoAdditions/Source/Input/Photos/PhotosInputDataProvider.swift
1
3505
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 PhotosUI protocol PhotosInputDataProviderProtocol { var count: Int { get } func requestPreviewImageAtIndex(index: Int, targetSize: CGSize, completion: (UIImage) -> Void) -> Int32 func requestFullImageAtIndex(index: Int, completion: (UIImage) -> Void) func cancelPreviewImageRequest(requestID: Int32) } class PhotosInputPlaceholderDataProvider: PhotosInputDataProviderProtocol { var count: Int { return 5 } func requestPreviewImageAtIndex(index: Int, targetSize: CGSize, completion: (UIImage) -> Void) -> Int32 { return 0 } func requestFullImageAtIndex(index: Int, completion: (UIImage) -> Void) { } func cancelPreviewImageRequest(requestID: Int32) { } } class PhotosInputDataProvider: PhotosInputDataProviderProtocol { private var imageManager = PHCachingImageManager() private var fetchResult: PHFetchResult! init() { let options = PHFetchOptions() options.sortDescriptors = [ NSSortDescriptor(key: "modificationDate", ascending: false) ] self.fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: options) } var count: Int { return self.fetchResult.count } func requestPreviewImageAtIndex(index: Int, targetSize: CGSize, completion: (UIImage) -> Void) -> Int32 { assert(index >= 0 && index < self.fetchResult.count, "Index out of bounds") let asset = self.fetchResult[index] as! PHAsset let options = PHImageRequestOptions() options.deliveryMode = .HighQualityFormat return self.imageManager.requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options) { (image, info) in if let image = image { completion(image) } } } func cancelPreviewImageRequest(requestID: Int32) { self.imageManager.cancelImageRequest(requestID) } func requestFullImageAtIndex(index: Int, completion: (UIImage) -> Void) { assert(index >= 0 && index < self.fetchResult.count, "Index out of bounds") let asset = self.fetchResult[index] as! PHAsset self.imageManager.requestImageDataForAsset(asset, options: .None) { (data, dataUTI, orientation, info) -> Void in if let data = data, image = UIImage(data: data) { completion(image) } } } }
mit
b4840bc591e5611f124e24d20b712a6b
38.829545
147
0.709558
4.72372
false
false
false
false
lzpfmh/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Conversation/Bubbles.swift
11
1380
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class Bubbles { private static let textLayouter = AABubbleTextCellLayouter() private static let mediaLayouter = AABubbleMediaCellLayouter() private static let documentLayouter = AABubbleDocumentCellLayout() private static let serviceLayouter = AABubbleServiceCellLayouter() private static let layouters:[AABubbleLayouter] = [ serviceLayouter, mediaLayouter, documentLayouter, textLayouter ] class func initCollectionView(collectionView: UICollectionView) { for layouter in layouters { collectionView.registerClass(layouter.cellClass(), forCellWithReuseIdentifier: layouter.reuseId) } } class func cellTypeForMessage(message: ACMessage) -> String { for layouter in layouters { if (layouter.isSuitable(message)) { return layouter.reuseId } } fatalError("No layouter for cell") } class func buildLayout(peer: ACPeer, message: ACMessage) -> CellLayout { for layouter in layouters { if (layouter.isSuitable(message)) { return layouter.buildLayout(peer, message: message) } } fatalError("No layouter for cell") } }
mit
7eb5b613dca518093b3b37f77c234006
28.382979
108
0.630435
5.073529
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/AppDelegate.swift
1
11314
// // AppDelegate.swift // NearbyWeather // // Created by Erik Maximilian Martens on 03.12.16. // Copyright © 2016 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift import RxOptional import RxFlow import Swinject import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: - Properties var window: UIWindow? var welcomeWindow: UIWindow? private var flowCoordinator: FlowCoordinator! private var dependencyContainer: Container! private var daemonContainer: [Daemon] = [] private let migrationIsRunningSubject = BehaviorSubject<Bool>(value: false) private var tempOnAsAppIconBadgeBackgroundFetchTaskId: UIBackgroundTaskIdentifier = .invalid // MARK: - Functions /// only called on cold start func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { registerServices() instantiateDaemons() instantiateFirebase() setInstallVersionIfNeeded() runMigrationIfNeeded() SettingsBundleTransferWorker.updateSystemSettings() return true } /// only called on cold start func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { instantiateApplicationUserInterface() startDaemons() return true } /// only called on warm start func applicationWillEnterForeground(_ application: UIApplication) { startDaemons() } /// called on any start func applicationDidBecomeActive(_ application: UIApplication) { // nothing to do } func applicationWillResignActive(_ application: UIApplication) { stopDaemons() } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { beginTempAsAppIconBadgeBackgroundFetchTask(for: application, performFetchWithCompletionHandler: completionHandler) } func applicationDidReceiveMemoryWarning(_ application: UIApplication) { restartDaemons() } } // MARK: - Private Helper Functions private extension AppDelegate { func registerServices() { dependencyContainer = Container() dependencyContainer.register(PersistencyService.self) { _ in PersistencyService() } dependencyContainer.register(ApplicationCycleService.self) { resolver in ApplicationCycleService( dependencies: ApplicationCycleService.Dependencies(persistencyService: resolver.resolve(PersistencyService.self)! )) } dependencyContainer.register(UserLocationService.self) { resolver in UserLocationService( dependencies: UserLocationService.Dependencies(persistencyService: resolver.resolve(PersistencyService.self)! )) } dependencyContainer.register(PreferencesService.self) { resolver in PreferencesService(dependencies: PreferencesService.Dependencies( persistencyService: resolver.resolve(PersistencyService.self)! )) } dependencyContainer.register(ApiKeyService.self) { resolver in ApiKeyService(dependencies: ApiKeyService.Dependencies( persistencyService: resolver.resolve(PersistencyService.self)! )) } dependencyContainer.register(WeatherStationService.self) { resolver in WeatherStationService(dependencies: WeatherStationService.Dependencies( persistencyService: resolver.resolve(PersistencyService.self)! )) } dependencyContainer.register(WeatherInformationService.self) { resolver in WeatherInformationService(dependencies: WeatherInformationService.Dependencies( persistencyService: resolver.resolve(PersistencyService.self)!, preferencesService: resolver.resolve(PreferencesService.self)!, weatherStationService: resolver.resolve(WeatherStationService.self)!, userLocationService: resolver.resolve(UserLocationService.self)!, apiKeyService: resolver.resolve(ApiKeyService.self)! )) } dependencyContainer.register(NetworkReachabilityService.self) { _ in NetworkReachabilityService() } dependencyContainer.register(NotificationService.self) { resolver in NotificationService(dependencies: NotificationService.Dependencies( persistencyService: resolver.resolve(PersistencyService.self)!, weatherStationService: resolver.resolve(WeatherStationService.self)!, weatherInformationService: resolver.resolve(WeatherInformationService.self)!, preferencesService: resolver.resolve(PreferencesService.self)! )) } } func instantiateDaemons() { let apiKeyService = dependencyContainer.resolve(ApiKeyService.self)! let preferencesService = dependencyContainer.resolve(PreferencesService.self)! let userLocationService = dependencyContainer.resolve(UserLocationService.self)! let weatherStationService = dependencyContainer.resolve(WeatherStationService.self)! let weatherInformationService = dependencyContainer.resolve(WeatherInformationService.self)! let notificationService = dependencyContainer.resolve(NotificationService.self)! daemonContainer.append(contentsOf: [ WeatherInformationUpdateDaemon(dependencies: WeatherInformationUpdateDaemon.Dependencies( apiKeyService: apiKeyService, preferencesService: preferencesService, userLocationService: userLocationService, weatherStationService: weatherStationService, weatherInformationService: weatherInformationService )), UserLocationUpdateDaemon(dependencies: UserLocationUpdateDaemon.Dependencies( userLocationService: userLocationService )), NotificationUpdateDaemon(dependencies: NotificationUpdateDaemon.Dependencies( weatherStationService: weatherStationService, weatherInformationService: weatherInformationService, preferencesService: preferencesService, notificationService: notificationService )) ]) } func startDaemons() { printDebugMessage( domain: String(describing: self), message: "👹 STARTED", type: .info ) daemonContainer.forEach { $0.startObservations() } } func stopDaemons() { printDebugMessage( domain: String(describing: self), message: "👹 STOPPED", type: .info ) daemonContainer.forEach { $0.stopObservations() } } func restartDaemons() { stopDaemons() daemonContainer = [] instantiateDaemons() startDaemons() } func instantiateFirebase() { if let filePath = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"), let firebaseOptions = FirebaseOptions(contentsOfFile: filePath) { FirebaseApp.configure(options: firebaseOptions) } } func instantiateApplicationUserInterface() { let window = UIWindow(frame: UIScreen.main.bounds) self.window = window let rootFlow = RootFlow(dependencies: RootFlow.Dependencies( rootWindow: window, dependencyContainer: dependencyContainer! )) flowCoordinator = FlowCoordinator() flowCoordinator?.coordinate( flow: rootFlow, with: RootStepper(dependencies: RootStepper.Dependencies( applicationCycleService: dependencyContainer.resolve(ApplicationCycleService.self)!, migrationRunningObservable: migrationIsRunningSubject.asObservable() )) ) } // TODO: move this to a background task worker func beginTempAsAppIconBadgeBackgroundFetchTask(for application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { tempOnAsAppIconBadgeBackgroundFetchTaskId = application.beginBackgroundTask( withName: Constants.Keys.BackgroundTaskIdentifiers.kRefreshTempOnAppIconBadge, expirationHandler: { [unowned self] in endTempAsAppIconBadgeBackgroundFetchTask() }) let preferencesService = dependencyContainer.resolve(PreferencesService.self)! let weatherStationService = dependencyContainer.resolve(WeatherStationService.self)! let weatherInformationService = dependencyContainer.resolve(WeatherInformationService.self)! let notificationService = dependencyContainer.resolve(NotificationService.self)! _ = weatherStationService .createGetPreferredBookmarkObservable() .flatMapLatest { preferredBookmarkOption -> Observable<TemperatureOnAppIconBadgeInformation?> in guard let stationIdentifierInt = preferredBookmarkOption?.intValue else { return Observable.just(nil) } return Observable .combineLatest( weatherInformationService.createGetBookmarkedWeatherInformationItemObservable(for: String(stationIdentifierInt)).map { $0.entity }, preferencesService.createGetTemperatureUnitOptionObservable(), resultSelector: TemperatureOnAppIconBadgeInformation.init ) .catchAndReturn(nil) } .take(1) .asSingle() .flatMapCompletable(notificationService.createPerformTemperatureOnBadgeUpdateCompletable) .subscribe( onCompleted: { [unowned self] in completionHandler(.newData) endTempAsAppIconBadgeBackgroundFetchTask() }, onError: { [unowned self] _ in completionHandler(.failed) endTempAsAppIconBadgeBackgroundFetchTask() } ) } func endTempAsAppIconBadgeBackgroundFetchTask() { UIApplication.shared.endBackgroundTask(tempOnAsAppIconBadgeBackgroundFetchTaskId) tempOnAsAppIconBadgeBackgroundFetchTaskId = .invalid } func setInstallVersionIfNeeded() { let applicationCycleService = dependencyContainer.resolve(ApplicationCycleService.self)! _ = applicationCycleService .createGetInstallVersionObservable() .take(1) .asSingle() .flatMapCompletable { installVersion in guard installVersion == nil else { return Completable.emptyCompletable } // TODO: log failure of writing installversion guard let installVersion = appVersion?.toInstallVersion else { return Completable.emptyCompletable } return applicationCycleService.createSetInstallVersionCompletable(installVersion) } .subscribe() } func runMigrationIfNeeded() { _ = MigrationService(dependencies: MigrationService.Dependencies( migrationIsRunningSubject: migrationIsRunningSubject, preferencesService: dependencyContainer.resolve(PreferencesService.self)!, weatherInformationService: dependencyContainer.resolve(WeatherInformationService.self)!, weatherStationService: dependencyContainer.resolve(WeatherStationService.self)!, apiKeyService: dependencyContainer.resolve(ApiKeyService.self)!, notificationService: dependencyContainer.resolve(NotificationService.self)!, applicationCycleService: dependencyContainer.resolve(ApplicationCycleService.self)! )) .createRun_2_2_1_to_3_0_0_migrationCompletable() .subscribe() } }
mit
67fe21e88072f9d36ec695b1741eda93
36.440397
181
0.735916
5.523693
false
false
false
false
artsy/Emergence
Emergence/Contexts/Presenting a Show/ShowDataSource+Delegate.swift
1
7431
import UIKit import CoreGraphics import ARCollectionViewMasonryLayout import SDWebImage import RxSwift import Artsy_UIColors import SDWebImage // Just a dumb protocol to pass a message back that // something has been tapped on protocol ShowItemTapped { func didTapArtwork(item: Artwork) } // Generic DataSource for dealing with an image based collectionview class CollectionViewDelegate <T>: NSObject, ARCollectionViewMasonryLayoutDelegate { let dimensionLength:CGFloat let itemDataSource: CollectionViewDataSource<T> let delegate: ShowItemTapped? let show: Show // The extra height associated with _none_ image space in the cell, such as artwork metadata var internalPadding:CGFloat = 0 init(datasource: CollectionViewDataSource<T>, collectionView: UICollectionView, show: Show, delegate: ShowItemTapped?) { itemDataSource = datasource dimensionLength = collectionView.bounds.height self.delegate = delegate self.show = show super.init() let layout = ARCollectionViewMasonryLayout(direction: .Horizontal) layout.rank = 1 layout.dimensionLength = dimensionLength layout.itemMargins = CGSize(width: 40, height: 0) layout.contentInset = UIEdgeInsets(top: 0, left: 90, bottom: 0, right: 90) collectionView.delegate = self collectionView.collectionViewLayout = layout collectionView.setNeedsLayout() } func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: ARCollectionViewMasonryLayout!, variableDimensionForItemAtIndexPath indexPath: NSIndexPath!) -> CGFloat { let item = itemDataSource.itemForIndexPath(indexPath) guard let actualItem = item, image: Image = imageForItem(actualItem) else { // otherwise, ship a square return dimensionLength } return widthForImage(image, capped: collectionView.bounds.width) } func widthForImage(image: Image, capped: CGFloat) -> CGFloat { let width: CGFloat let ratio = image.aspectRatio ?? image.imageSize.width / image.imageSize.height width = (dimensionLength - internalPadding) * ratio return min(width, capped) } func imageForItem(item:T) -> Image? { // If it's an artwork grab the default image if var artwork = item as? Artwork, let defaultImage = artwork.defaultImage, let actualImage = defaultImage as? Image { return actualImage } else if let actualImage = item as? Image { // otherwise it is an image return actualImage } return nil } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { guard let item = itemDataSource.itemForIndexPath(indexPath) else { return } guard let image = imageForItem(item) else { return } if let cell = cell as? ImageCollectionViewCell { if image.imageFormatString == show.imageFormatString { // We can use the install shot from the ShowsOverview cache! let oldThumbnail = image.bestAvailableThumbnailURL() guard let newThumbnail = image.geminiThumbnailURLWithHeight(Int(dimensionLength)) else { return print("Could not generate a thumbnail for image") } cell.image.ar_setImageURL(newThumbnail, takeThisURLFromCacheFirst: oldThumbnail, size:image.imageSize) } else { cell.image.ar_setImage(image, height: dimensionLength) } } if let cell = cell as? ArtworkCollectionViewCell, let artwork = item as? Artwork { cell.artistNameLabel.text = artwork.oneLinerArtist() cell.titleLabel.attributedText = artwork.titleWithDate() cell.image.ar_setImage(image, height: dimensionLength) } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { guard let item = itemDataSource.itemForIndexPath(indexPath) else { return } if let artwork = item as? Artwork { delegate?.didTapArtwork(artwork) } } } class CollectionViewDataSource <T>: NSObject, UICollectionViewDataSource { let collectionView: UICollectionView let cellIdentifier: String let cache: SDWebImagePrefetcher let show: Show var items: [T]? init(_ collectionView: UICollectionView, cellIdentifier: String, show: Show, cache: SDWebImagePrefetcher) { self.collectionView = collectionView self.cellIdentifier = cellIdentifier self.cache = cache self.show = show super.init() collectionView.dataSource = self } func subscribeToRequest(request: Observable<[(T)]>?) { guard let request = request else { return } request.subscribe() { networkItems in guard let elements = networkItems.element else { return } let newItems = elements.sort(self.moveCachableImageToTop) if let items = self.items { self.items = items + newItems } else { self.items = newItems } self.collectionView.batch() { let previousItemsCount = self.collectionView.numberOfItemsInSection(0) let paths = (previousItemsCount ..< self.items!.count).map({ NSIndexPath(forRow: $0, inSection: 0) }) self.collectionView.insertItemsAtIndexPaths(paths) } self.precache(self.items) } } func itemForIndexPath(path: NSIndexPath) -> T? { return items?[path.row] } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) } // Sort func moveCachableImageToTop(lhs:T, rhs:T) -> Bool { if imageForItem(lhs)?.imageFormatString == show.imageFormatString { return true } return false } // Low priority image caching func precache(items:[T]?) { guard let items = items else { return } let images = items.map(imageForItem).flatMap { $0 } var urls = images.map { $0.bestThumbnailWithHeight(collectionView.bounds.height) }.flatMap { $0 } // I _feel_ like the precaching is getting in the way of showing the first install shot if let _ = items.first as? Image { urls.removeAtIndex(0) } cache.prefetchURLs(urls) } // As these two are separate generic classes, they can't really share this function, thus: duped. func imageForItem(item:T) -> Image? { // If it's an artwork grab the default image if var artwork = item as? Artwork, let defaultImage = artwork.defaultImage, let actualImage = defaultImage as? Image { return actualImage } else if let actualImage = item as? Image { // otherwise it is an image return actualImage } return nil } }
mit
45cd97cb0a780e7537840f7b2dfd05ec
34.555024
193
0.668416
5.107216
false
false
false
false
ibm-bluemix-mobile-services/bms-clientsdk-swift-push
Source/BMSResponse.swift
1
4840
/* *     Copyright 2016 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import UIKit import BMSCore // MARK: - Swift 3 & Swift 4 #if swift(>=3.0) /** This is the extension of `Response` class in the `BMSCore`. It is used to handle the responses from the push REST API calls. */ public extension Response { // MARK: Methods (Only for using in BMSPushClient) /** This methode will convert the response that get while calling the `retrieveSubscriptionsWithCompletionHandler` in `BMSPushClient' class into an array of Tags and send to the Client app. This will use the public property `responseText` in the `Response` Class. */ func subscriptions() -> NSMutableArray { let subscription = NSMutableArray() if let subscriptionDictionary = convertStringToDictionary(text: self.responseText!) as NSDictionary? { if let subscriptionArray:[[String:String]] = subscriptionDictionary.object(forKey: IMFPUSH_SUBSCRIPTIONS) as? [[String:String]] { let subscriptions = subscriptionArray.map {($0)[IMFPUSH_TAGNAME]!} subscription.addObjects(from: subscriptions) } } return subscription; } /** This methode will convert the response that get while calling the `subscribeToTags` in `BMSPushClient' class into an Dictionary of details and send to the Client app. This will use the public property `responseText` in the `Response` Class. */ func subscribeStatus() -> NSMutableDictionary { return getResponseDict() } /** This methode will convert the response that get while calling the `unsubscribeFromTags` in `BMSPushClient' class into an Dictionary of details and send to the Client app. This will use the public property `responseText` in the `Response` Class. */ func unsubscribeStatus() -> NSMutableDictionary { return getResponseDict() } /** This methode will convert the response that get while calling the `retrieveAvailableTagsWithCompletionHandler` in `BMSPushClient' class into an array and send to the Client app. This will use the public property `responseText` in the `Response` Class. */ func availableTags() -> NSMutableArray { let tags = NSMutableArray() if let tagsDictionary:NSDictionary = convertStringToDictionary(text: self.responseText!) as NSDictionary? { if let tag:[[String:String]] = tagsDictionary.object(forKey: IMFPUSH_TAGS) as? [[String:String]] { let tagsArray = tag.map {($0)[IMFPUSH_NAME]!} tags.addObjects(from: tagsArray) } } return tags; } private func convertStringToDictionary(text: String) -> [String:AnyObject]? { if let data = text.data(using: String.Encoding.utf8) { guard let result = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] else { return [:] } return result } return [:] } internal func getResponseDict() -> NSMutableDictionary { let finalDict = NSMutableDictionary() if let subscriptions:NSDictionary = convertStringToDictionary(text: self.responseText!) as NSDictionary? { if let arraySub:NSArray = subscriptions.object(forKey: IMFPUSH_SUBSCRIPTIONEXISTS) as? NSArray { finalDict.setObject(arraySub, forKey:IMFPUSH_SUBSCRIPTIONEXISTS as NSCopying) } if let dictionarySub:NSDictionary = subscriptions.object(forKey: IMFPUSH_TAGSNOTFOUND) as? NSDictionary { finalDict.setObject(dictionarySub, forKey:IMFPUSH_TAGSNOTFOUND as NSCopying) } if let arraySub:NSArray = subscriptions.object(forKey: IMFPUSH_SUBSCRIBED) as? NSArray { finalDict.setObject(arraySub, forKey:IMFPUSH_SUBSCRIPTIONS as NSCopying) } } return finalDict; } } #endif
apache-2.0
82f8041012e42dc3c8e6afcf738aa048
37.174603
190
0.631393
5.031381
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SpreadsheetView-master/Framework/Sources/Cell.swift
3
3210
// // Cell.swift // SpreadsheetView // // Created by Kishikawa Katsumi on 3/16/17. // Copyright © 2017 Kishikawa Katsumi. All rights reserved. // import UIKit open class Cell: UIView { public let contentView = UIView() public var backgroundView: UIView? { willSet { backgroundView?.removeFromSuperview() } didSet { guard let backgroundView = backgroundView else { return } backgroundView.frame = bounds backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] insertSubview(backgroundView, at: 0) } } public var selectedBackgroundView: UIView? { willSet { selectedBackgroundView?.removeFromSuperview() } didSet { guard let selectedBackgroundView = selectedBackgroundView else { return } selectedBackgroundView.frame = bounds selectedBackgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] selectedBackgroundView.alpha = 0 if let backgroundView = backgroundView { insertSubview(selectedBackgroundView, aboveSubview: backgroundView) } else { insertSubview(selectedBackgroundView, at: 0) } } } open var isHighlighted = false { didSet { selectedBackgroundView?.alpha = isHighlighted || isSelected ? 1 : 0 } } open var isSelected = false { didSet { selectedBackgroundView?.alpha = isSelected ? 1 : 0 } } public var gridlines = Gridlines(top: .default, bottom: .default, left: .default, right: .default) @available(*, deprecated: 0.6.3, renamed: "gridlines") public var grids: Gridlines { get { return gridlines } set { gridlines = grids } } public var borders = Borders(top: .none, bottom: .none, left: .none, right: .none) { didSet { hasBorder = borders.top != .none || borders.bottom != .none || borders.left != .none || borders.right != .none } } var hasBorder = false public internal(set) var reuseIdentifier: String? var indexPath: IndexPath! public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { backgroundColor = .white contentView.frame = bounds contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] insertSubview(contentView, at: 0) } open func prepareForReuse() {} func setSelected(_ selected: Bool, animated: Bool) { if animated { UIView.animate(withDuration: CATransaction.animationDuration()) { self.isSelected = selected } } else { isSelected = selected } } } extension Cell: Comparable { public static func <(lhs: Cell, rhs: Cell) -> Bool { return lhs.indexPath < rhs.indexPath } } final class BlankCell: Cell {}
mit
50a97b97836d21aa7469ff58d7df5493
26.904348
122
0.582424
5.200972
false
false
false
false
rutgerfarry/FreshFades
FreshFades/View Controllers/HaircutChoiceViewController.swift
1
2191
import UIKit class HaircutChoiceViewController: UIViewController { init() { super.init(nibName: nil, bundle: nil) title = "Schedule" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBOutlet weak var collectionView: UICollectionView! let haircutStyles = ["Fresh Fade", "Line-up", "Custom" ] let haircutPrices = [23, 15, 30] override func viewDidLoad() { super.viewDidLoad() collectionView.register(HaircutCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "HaircutCollectionViewCell") let collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.itemSize = CGSize(width: view.frame.width - 40, height: (view.frame.height - 150) / 3) collectionViewLayout.minimumLineSpacing = 20 collectionView.setCollectionViewLayout(collectionViewLayout, animated: false) } } extension HaircutChoiceViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HaircutCollectionViewCell", for: indexPath) if let cell = cell as? HaircutCollectionViewCell { cell.image = #imageLiteral(resourceName: "yeezy") cell.leftTextLabel.text = haircutStyles[indexPath.row] cell.rightTextLabel.text = "$\(haircutPrices[indexPath.row])" } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let scheduleViewController = ScheduleViewController() navigationController?.pushViewController(scheduleViewController, animated: true) } }
mit
be655c31ff72dc7f2c8e312d141274d1
34.33871
119
0.648562
5.90566
false
false
false
false
RayTW/Swift8ComicSDK
Swift8ComicSDK/Classes/JSnview.swift
2
4244
// // JSnview.swift // Pods // // 解析每集(話)漫畫圖片下載網址 // // Created by Ray on 2017/8/19. // // import Foundation import JavaScriptCore open class JSnview{ private var mSource : String? private var mCh : Int? private var mChs : Int = 0 private var mTi : Int = 0 private var mPs : Int = 0 //漫畫總頁數 private var mCs : String = "" private var mC : String = "" private static let Y : Int = 46; open func setSource(_ source : String){ mSource = source } /* * 取得集數編號,例如1、2、3… */ open func getCh() -> Int{ return mCh! } open func setCh(_ ch : String) -> Void{ mCh = Int(ch) } /* * 取得最新集數,例如最新第68號,此回傳值則為68 */ open func getChs() -> Int{ return mChs } open func setChs(_ chs : Int) -> Void{ mChs = chs } open func getTi() -> Int{ return mTi } open func setTi(_ ti : Int) -> Void{ mTi = ti } /* * 取得單集漫畫混淆過的編碼 */ open func getCs() -> String{ return mCs } open func setCs(_ cs : String) -> Void{ mCs = cs } //讀取1話(集、卷)全部漫畫圖片網址 open func setupPagesDownloadUrl() -> [String]{ return invokeJS(mSource!, JSnview.Y, mCh!) } open func invokeJS(_ js : String, _ y : Int, _ ch : Int) -> [String]{ let context = JSContext()! var str : String = StringUtility.substring(js, 0, StringUtility.indexOfInt(js, "var pt=")) str = StringUtility.replace(str, "ge('TheImg').src", "var src") let unuseScript : String = StringUtility.substring(str, "\'.jpg\';", "break;")! str = StringUtility.replace(str, unuseScript, "") var varSrc : String; if(StringUtility.indexOfInt(str, "ci=i;") > 0){ varSrc = StringUtility.substring(str, "ci=i;", "break;")! }else{ varSrc = StringUtility.substring(str, "ci = i;", "break;")! } varSrc = StringUtility.replace(str, "//img", "https://img") let getPageJS : String = String.init(format: buildGetPagesJS(), varSrc) str = StringUtility.replace(str, varSrc, "") str = StringUtility.replace(str, "break;", getPageJS) let script : String = "function sp2(ch, y){" + str + "} " + buildNviewJS() context.evaluateScript(script) //取出funciton sp2() let sp2Function = context.objectForKeyedSubscript("sp2") //呼叫javsccript的 sp2() function let jsvalue : JSValue = (sp2Function?.call(withArguments: [ch, y]))! let list = jsvalue.toArray() as! [String] return list; } private func buildGetPagesJS() -> String{ var buf : String = String(); buf.append("var result = [];") buf.append("for(var p = 1; p <= ps; p++){") buf.append("%@") buf.append("result.push(src);") buf.append("}") buf.append("return result;") return buf; } private func buildNviewJS() -> String{ var buf : String = String(); buf.append("function lc(l) {") buf.append("if (l.length != 2) return l;") buf.append("var az = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";") buf.append("var a = l.substring(0, 1);") buf.append("var b = l.substring(1, 2);") buf.append("if (a == \"Z\") return 8000 + az.indexOf(b);") buf.append("else return az.indexOf(a) * 52 + az.indexOf(b);}") buf.append("function su(a, b, c) {") buf.append("var e = (a + '').substring(b, b + c);") buf.append("return (e);") buf.append("}") buf.append("function nn(n) {") buf.append("return n < 10 ? '00' + n : n < 100 ? '0' + n : n;") buf.append("}") buf.append("function mm(p) {") buf.append("return (parseInt((p - 1) / 10) % 10) + (((p - 1) % 10) * 3)") buf.append("}") return buf; } }
mit
8c77eb6148aecfe00911503988b04697
26.581081
98
0.512249
3.444726
false
false
false
false
dolphilia/swift-calayer-randomnoise-example
02_no_animation/CALayerTest/MyView.swift
1
1151
// // MyView.swift // CALayerTest // // Created by dolphilia on 2016/01/16. // Copyright © 2016年 dolphilia. All rights reserved. // import Foundation import Cocoa // Import QuartzCore.h at the top of the file import QuartzCore class MyView:NSView { var mylayer = MyCALayer() override init(frame: NSRect) { super.init(frame: frame) } required init(coder: NSCoder) { super.init(coder: coder)! } override func awakeFromNib() { self.wantsLayer = true self.layer!.delegate = self //self.layer!.addSublayer(mylayer) self.layer! = mylayer } override func layout() { super.layout() mylayer.frame = CGRectMake(0, 0, 640, 480) //角丸 //mylayer.cornerRadius = 3.0; //mylayer.backgroundColor = NSColor.whiteColor().CGColor //mylayer.masksToBounds = true; } override func drawLayer(layer: (CALayer!), inContext ctx: (CGContext!)) { super.drawLayer(layer, inContext:ctx) } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) } }
mit
3752e700d63bf58eecf2476b218638ba
21.9
77
0.601399
4.028169
false
false
false
false
bromas/ActivityViewController
ActivityViewController/ActivityOperation.swift
1
1602
// // ActivityOperation.swift // ApplicationVCSample // // Created by Brian Thomas on 2/18/15. // Copyright (c) 2015 Brian Thomas. All rights reserved. // import Foundation import UIKit public enum ActivityOperationType { case none case animationOption case nonInteractiveTransition case transitioningDelegate case presented } public enum ActivityOperationRule { case new case any case previous } public struct ActivityOperation { internal var type = ActivityOperationType.animationOption internal var selectRule = ActivityOperationRule.any internal var animationOption = UIViewAnimationOptions.transitionCrossDissolve internal var animationDuration = 0.3 internal var nonInteractiveTranstionanimator : UIViewControllerAnimatedTransitioning! public var completionBlock : () -> Void = { } internal let activityIdentifier: String public init (rule: ActivityOperationRule = .any, identifier: String = "") { selectRule = rule activityIdentifier = identifier type = .none } public init (rule: ActivityOperationRule = .any, identifier: String, animator: UIViewControllerAnimatedTransitioning) { selectRule = rule activityIdentifier = identifier type = .nonInteractiveTransition nonInteractiveTranstionanimator = animator } public init (rule: ActivityOperationRule = .any, identifier: String, animationType: UIViewAnimationOptions, duration: Double) { selectRule = rule activityIdentifier = identifier type = .animationOption animationOption = animationType animationDuration = duration } }
mit
07cc843336a2a68f477146b8fdf40714
25.7
129
0.758427
5.269737
false
false
false
false
helloglance/betterbeeb
BetterBeeb/ReaderHostViewController.swift
1
8879
// // ReaderHostViewController.swift // BetterBeeb // // Created by Hudzilla on 15/10/2014. // Copyright (c) 2014 Paul Hudson. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import MessageUI import Social import UIKit class ReaderHostViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, MFMailComposeViewControllerDelegate { weak var section: Section! weak var story: Story! var headerBar: UIView! var sectionTitle: UILabel! var pageCounter: SlimPageControl! var pageController: UIPageViewController! override func loadView() { super.loadView() edgesForExtendedLayout = .None view.backgroundColor = UIColor.beebStoryBackground() headerBar = UIView() sectionTitle = UILabel() pageCounter = SlimPageControl() pageController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) headerBar.translatesAutoresizingMaskIntoConstraints = false sectionTitle.translatesAutoresizingMaskIntoConstraints = false pageCounter.translatesAutoresizingMaskIntoConstraints = false pageController.view.translatesAutoresizingMaskIntoConstraints = false headerBar.backgroundColor = UIColor.beebStoryBackground() pageController.dataSource = self pageController.delegate = self addChildViewController(pageController) view.addSubview(pageController.view) headerBar.addSubview(sectionTitle) headerBar.addSubview(pageCounter) view.addSubview(headerBar) let viewsDictionary = ["headerBar" : headerBar, "sectionTitle" : sectionTitle, "pageCounter" : pageCounter, "pageControllerView" : pageController.view] headerBar.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(==8)-[sectionTitle]-(>=1)-[pageCounter]-(==4)-|", options: [], metrics: nil, views: viewsDictionary)) headerBar.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[sectionTitle]|", options: [], metrics: nil, views: viewsDictionary)) headerBar.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[pageCounter]|", options: [], metrics: nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[headerBar]|", options: [], metrics: nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[pageControllerView]|", options: [], metrics: nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[headerBar(==22)][pageControllerView]|", options: [], metrics: nil, views: viewsDictionary)) } override func viewDidLoad() { super.viewDidLoad() // the original app has both font size adjust and share buttons, but our "Better Beeb" logo is bigger than theirs // so there isn't enough width for us to have font size adjustment let shareButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: Selector("shareTapped")) navigationItem.rightBarButtonItems = [shareButton] let attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(13)] sectionTitle.attributedText = NSAttributedString(string: section.title.uppercaseString, attributes: attrs) pageCounter.numberOfPages = section.stories.count pageCounter.pageIndicatorTintColor = UIColor.beebPagingDotsGrey() pageCounter.currentPageIndicatorTintColor = UIColor.beebRed() pageCounter.userInteractionEnabled = false if let currentIndex = section.stories.indexOf( story) { self.pageCounter.currentPage = currentIndex } else { self.pageCounter.currentPage = -1 } let vc = ReaderContentViewController() vc.story = story pageController.setViewControllers([vc], direction: .Forward, animated: false, completion: nil) } func adjustTextSizeTapped() { // Not implemented. } func shareTapped() { let ac = UIAlertController(title: title, message: nil, preferredStyle: .ActionSheet) ac.addAction(UIAlertAction(title: "Email", style: .Default, handler: shareByEmail)) ac.addAction(UIAlertAction(title: "Twitter", style: .Default, handler: shareByTwitter)) ac.addAction(UIAlertAction(title: "Facebook", style: .Default, handler: shareByFacebook)) ac.addAction(UIAlertAction(title: "Copy web link", style: .Default, handler: copyWebLink)) ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func shareByEmail(action: UIAlertAction!) { if MFMailComposeViewController.canSendMail() { let vc = MFMailComposeViewController() vc.mailComposeDelegate = self vc.setSubject("BBC News: \(story.title)") let body = "I saw this story on the Better Beeb iPhone app and thought you should see it:\n\n\(story.title)\n\nRead more: \(story.linkHref)\n\n\n***Disclaimer***\nThe BBC is not responsible for the content of this e-mail, and anything written in this e-mail does not necessarily reflect the BBC's views or opinions. Please note that neither the e-mail address nor name of the sender have been verified." vc.setMessageBody(body, isHTML: false) presentViewController(vc, animated:true, completion: nil) } else { let ac = UIAlertController(title: "No email account", message: "Please configure an email account on your device before sharing by email.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } } func shareByTwitter(action: UIAlertAction!) { let vc = SLComposeViewController(forServiceType: SLServiceTypeTwitter) vc.addURL(NSURL(string: story.linkHref)) vc.setInitialText(story.title) presentViewController(vc, animated: true, completion: nil) } func shareByFacebook(action: UIAlertAction!) { let vc = SLComposeViewController(forServiceType: SLServiceTypeFacebook) vc.addURL(NSURL(string: story.linkHref)) vc.setInitialText(story.title) presentViewController(vc, animated: true, completion: nil) } func copyWebLink(action: UIAlertAction!) { let pasteboard = UIPasteboard.generalPasteboard() pasteboard.URL = NSURL(string: story.linkHref) } func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){ controller.dismissViewControllerAnimated(true, completion: nil) } // MARK: - UIPageViewController data source func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let contentViewController = viewController as! ReaderContentViewController if let currentIndex = section.stories.indexOf( contentViewController.story) { if currentIndex > 0 { let vc = ReaderContentViewController() vc.story = section.stories[currentIndex - 1] return vc } } return nil } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let contentViewController = viewController as! ReaderContentViewController if let currentIndex = section.stories.indexOf( contentViewController.story) { if currentIndex < section.stories.count - 1 { let vc = ReaderContentViewController() vc.story = section.stories[currentIndex + 1] return vc } } return nil } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool){ if !completed { return } let currentVC = self.pageController.viewControllers!.last as! ReaderContentViewController if let currentIndex = section.stories.indexOf( currentVC.story) { self.pageCounter.currentPage = currentIndex } else { self.pageCounter.currentPage = -1 } } }
mit
e8de2221551de8b2dfb5a20f32f7fc5f
42.312195
406
0.774524
4.567387
false
false
false
false
natecook1000/swift
test/SILGen/enum_raw_representable_objc.swift
2
1257
// RUN: %target-swift-emit-silgen -enable-sil-ownership -emit-sorted-sil -enable-objc-interop -disable-objc-attr-requires-foundation-module %s | %FileCheck %s // RUN: %target-swift-emit-silgen -enable-sil-ownership -emit-sorted-sil -enable-objc-interop -disable-objc-attr-requires-foundation-module -enable-resilience %s | %FileCheck -check-prefix=CHECK-RESILIENT %s @objc public enum CLike: Int { case a, b, c } // CHECK-LABEL: sil [serialized] @$S27enum_raw_representable_objc5CLikeO0B5ValueACSgSi_tcfC // CHECK-LABEL: sil [serialized] @$S27enum_raw_representable_objc5CLikeO0B5ValueSivg // CHECK-DAG: [[RESULT_BOX:%.+]] = alloc_stack $Int // CHECK-DAG: [[INPUT_BOX:%.+]] = alloc_stack $CLike // CHECK: [[RAW_TYPE:%.+]] = metatype $@thick Int.Type // CHECK: [[CAST_FUNC:%.+]] = function_ref @$Ss13unsafeBitCast_2toq_x_q_mtr0_lF // CHECK: = apply [[CAST_FUNC]]<CLike, Int>([[RESULT_BOX]], [[INPUT_BOX]], [[RAW_TYPE]]) // CHECK: [[RESULT:%.+]] = load [trivial] [[RESULT_BOX]] // CHECK: return [[RESULT]] // CHECK: end sil function '$S27enum_raw_representable_objc5CLikeO0B5ValueSivg' // CHECK-RESILIENT-DAG: sil @$S27enum_raw_representable_objc5CLikeO0B5ValueSivg // CHECK-RESILIENT-DAG: sil @$S27enum_raw_representable_objc5CLikeO0B5ValueACSgSi_tcfC
apache-2.0
91eec5197a1da67f043f84e4f8222605
58.857143
207
0.719968
3.036232
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostEditorAnalyticsSession.swift
1
5617
import Foundation struct PostEditorAnalyticsSession { private let sessionId = UUID().uuidString let postType: String let blogID: NSNumber? let blogType: String let contentType: String var started = false var currentEditor: Editor var hasUnsupportedBlocks = false var outcome: Outcome? = nil private let startTime = DispatchTime.now().uptimeNanoseconds init(editor: Editor, post: AbstractPost) { currentEditor = editor postType = post.analyticsPostType ?? "unsupported" blogID = post.blog.dotComID blogType = post.blog.analyticsType.rawValue contentType = ContentType(post: post).rawValue } mutating func start(unsupportedBlocks: [String] = [], canViewEditorOnboarding: Bool = false, galleryWithImageBlocks: Bool? = nil) { assert(!started, "An editor session was attempted to start more than once") hasUnsupportedBlocks = !unsupportedBlocks.isEmpty let properties = startEventProperties(with: unsupportedBlocks, canViewEditorOnboarding: canViewEditorOnboarding, galleryWithImageBlocks: galleryWithImageBlocks) WPAppAnalytics.track(.editorSessionStart, withProperties: properties) started = true } private func startEventProperties(with unsupportedBlocks: [String], canViewEditorOnboarding: Bool, galleryWithImageBlocks: Bool?) -> [String: Any] { // On Android, we are tracking this in milliseconds, which seems like a good enough time scale // Let's make sure to round the value and send an integer for consistency let startupTimeNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime let startupTimeMilliseconds = Int(Double(startupTimeNanoseconds) / 1_000_000) var properties: [String: Any] = [ Property.startupTime: startupTimeMilliseconds ] // Tracks custom event types can't be arrays so we need to convert this to JSON if let data = try? JSONSerialization.data(withJSONObject: unsupportedBlocks, options: .fragmentsAllowed) { let blocksJSON = String(data: data, encoding: .utf8) properties[Property.unsupportedBlocks] = blocksJSON } properties[Property.canViewEditorOnboarding] = canViewEditorOnboarding if let galleryWithImageBlocks = galleryWithImageBlocks { properties[Property.unstableGalleryWithImageBlocks] = "\(galleryWithImageBlocks)" } else { properties[Property.unstableGalleryWithImageBlocks] = "unknown" } return properties.merging(commonProperties, uniquingKeysWith: { $1 }) } mutating func `switch`(editor: Editor) { currentEditor = editor WPAppAnalytics.track(.editorSessionSwitchEditor, withProperties: commonProperties) } mutating func forceOutcome(_ newOutcome: Outcome) { // We're allowing an outcome to be force in a few specific cases: // - If a post was published, that should be the outcome no matter what happens later // - If a post is saved, that should be the outcome unless it's published later // - Otherwise, we'll use whatever outcome is set when the session ends switch (outcome, newOutcome) { case (_, .publish), (nil, .save): self.outcome = newOutcome default: break } } func end(outcome endOutcome: Outcome, canViewEditorOnboarding: Bool = false) { let outcome = self.outcome ?? endOutcome var properties: [String: Any] = [ Property.outcome: outcome.rawValue ].merging(commonProperties, uniquingKeysWith: { $1 }) properties[Property.canViewEditorOnboarding] = canViewEditorOnboarding WPAppAnalytics.track(.editorSessionEnd, withProperties: properties) } } private extension PostEditorAnalyticsSession { enum Property { static let blogID = "blog_id" static let blogType = "blog_type" static let contentType = "content_type" static let editor = "editor" static let hasUnsupportedBlocks = "has_unsupported_blocks" static let unsupportedBlocks = "unsupported_blocks" static let postType = "post_type" static let outcome = "outcome" static let sessionId = "session_id" static let template = "template" static let startupTime = "startup_time_ms" static let canViewEditorOnboarding = "can_view_editor_onboarding" static let unstableGalleryWithImageBlocks = "unstable_gallery_with_image_blocks" } var commonProperties: [String: String] { return [ Property.editor: currentEditor.rawValue, Property.contentType: contentType, Property.postType: postType, Property.blogID: blogID?.stringValue, Property.blogType: blogType, Property.sessionId: sessionId, Property.hasUnsupportedBlocks: hasUnsupportedBlocks ? "1" : "0", ].compactMapValues { $0 } } } extension PostEditorAnalyticsSession { enum Editor: String { case gutenberg case stories case classic case html } enum ContentType: String { case new case gutenberg case classic init(post: AbstractPost) { if post.isContentEmpty() { self = .new } else if post.containsGutenbergBlocks() { self = .gutenberg } else { self = .classic } } } enum Outcome: String { case cancel case discard case save case publish } }
gpl-2.0
f6fe5c438ebffee46ccc69dbc1357a93
37.737931
168
0.664234
4.988455
false
false
false
false
abertelrud/swift-package-manager
Sources/PackagePlugin/ArgumentExtractor.swift
2
3418
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 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 // //===----------------------------------------------------------------------===// /// A rudimentary helper for extracting options and flags from a string list representing command line arguments. The idea is to extract all known options and flags, leaving just the positional arguments. This does not handle well the case in which positional arguments (or option argument values) happen to have the same name as an option or a flag. It only handles the long `--<name>` form of options, but it does respect `--` as an indication that all remaining arguments are positional. public struct ArgumentExtractor { private var args: [String] private let literals: [String] /// Initializes a ArgumentExtractor with a list of strings from which to extract flags and options. If the list contains `--`, any arguments that follow it are considered to be literals. public init(_ arguments: [String]) { // Split the array on the first `--`, if there is one. Everything after that is a literal. let parts = arguments.split(separator: "--", maxSplits: 1, omittingEmptySubsequences: false) self.args = Array(parts[0]) self.literals = Array(parts.count == 2 ? parts[1] : []) } /// Extracts options of the form `--<name> <value>` or `--<name>=<value>` from the remaining arguments, and returns the extracted values. public mutating func extractOption(named name: String) -> [String] { var values: [String] = [] var idx = 0 while idx < args.count { var arg = args[idx] if arg == "--\(name)" { args.remove(at: idx) if idx < args.count { let val = args[idx] values.append(val) args.remove(at: idx) } } else if arg.starts(with: "--\(name)=") { arg.removeFirst(2 + name.count + 1) values.append(arg) args.remove(at: idx) } else { idx += 1 } } return values } /// Extracts flags of the form `--<name>` from the remaining arguments, and returns the count. public mutating func extractFlag(named name: String) -> Int { var count = 0 var idx = 0 while idx < args.count { let arg = args[idx] if arg == "--\(name)" { args.remove(at: idx) count += 1 } else { idx += 1 } } return count } /// Returns any unextracted flags or options (based strictly on whether remaining arguments have a "--" prefix). public var unextractedOptionsOrFlags: [String] { return args.filter{ $0.hasPrefix("--") } } /// Returns all remaining arguments, including any literals after the first `--` if there is one. public var remainingArguments: [String] { return args + literals } }
apache-2.0
2adb16b771f687395d7b24fd26f4e0cd
42.820513
490
0.568754
4.827684
false
false
false
false
ivlevAstef/DITranquillity
Sources/Core/API/Extensions/SwiftLazy.swift
1
4436
// // SwiftLazy.swift // DITranquillity // // Created by Alexander Ivlev on 09.04.2018. // Copyright © 2018 Alexander Ivlev. All rights reserved. // import SwiftLazy extension Lazy: SpecificType { static var delayed: Bool { return true } static var type: DIAType { return Value.self } public convenience init(file: String = #file, line: UInt = #line) { self.init { () -> Value in fatalError("Please inject this property from DI in file: \(file.fileName) on line: \(line). Lazy type: \(Value.self) ") } } convenience init(_ container: DIContainer, _ factory: @escaping (_ arguments: AnyArguments?) -> Any?) { self.init { () -> Value in return gmake(by: factory(nil)) } } } extension Provider: SpecificType { static var delayed: Bool { return true } static var type: DIAType { return Value.self } public convenience init(file: String = #file, line: UInt = #line) { self.init { () -> Value in fatalError("Please inject this property from DI in file: \(file.fileName) on line: \(line). Provider type: \(Value.self) ") } } convenience init(_ container: DIContainer, _ factory: @escaping (_ arguments: AnyArguments?) -> Any?) { self.init { () -> Value in return gmake(by: factory(nil)) } } } // Providers with args extension Provider1: SpecificType { static var delayed: Bool { return true } static var type: DIAType { return Value.self } public convenience init(file: String = #file, line: UInt = #line) { self.init { _ -> Value in fatalError("Please inject this property from DI in file: \(file.fileName) on line: \(line). Provider type: \(Value.self) ") } } convenience init(_ container: DIContainer, _ factory: @escaping (_ arguments: AnyArguments?) -> Any?) { self.init { arg1 -> Value in return gmake(by: factory(AnyArguments(for: Value.self, args: arg1))) } } } extension Provider2: SpecificType { static var delayed: Bool { return true } static var type: DIAType { return Value.self } public convenience init(file: String = #file, line: UInt = #line) { self.init { _, _ -> Value in fatalError("Please inject this property from DI in file: \(file.fileName) on line: \(line). Provider type: \(Value.self) ") } } convenience init(_ container: DIContainer, _ factory: @escaping (_ arguments: AnyArguments?) -> Any?) { self.init { arg1, arg2 -> Value in return gmake(by: factory(AnyArguments(for: Value.self, args: arg1, arg2))) } } } extension Provider3: SpecificType { static var delayed: Bool { return true } static var type: DIAType { return Value.self } public convenience init(file: String = #file, line: UInt = #line) { self.init { _, _, _ -> Value in fatalError("Please inject this property from DI in file: \(file.fileName) on line: \(line). Provider type: \(Value.self) ") } } convenience init(_ container: DIContainer, _ factory: @escaping (_ arguments: AnyArguments?) -> Any?) { self.init { arg1, arg2, arg3 -> Value in return gmake(by: factory(AnyArguments(for: Value.self, args: arg1, arg2, arg3))) } } } extension Provider4: SpecificType { static var delayed: Bool { return true } static var type: DIAType { return Value.self } public convenience init(file: String = #file, line: UInt = #line) { self.init { _, _, _, _ -> Value in fatalError("Please inject this property from DI in file: \(file.fileName) on line: \(line). Provider type: \(Value.self) ") } } convenience init(_ container: DIContainer, _ factory: @escaping (_ arguments: AnyArguments?) -> Any?) { self.init { arg1, arg2, arg3, arg4 -> Value in return gmake(by: factory(AnyArguments(for: Value.self, args: arg1, arg2, arg3, arg4))) } } } extension Provider5: SpecificType { static var delayed: Bool { return true } static var type: DIAType { return Value.self } public convenience init(file: String = #file, line: UInt = #line) { self.init { _, _, _, _, _ -> Value in fatalError("Please inject this property from DI in file: \(file.fileName) on line: \(line). Provider type: \(Value.self) ") } } convenience init(_ container: DIContainer, _ factory: @escaping (_ arguments: AnyArguments?) -> Any?) { self.init { arg1, arg2, arg3, arg4, arg5 -> Value in return gmake(by: factory(AnyArguments(for: Value.self, args: arg1, arg2, arg3, arg4, arg5))) } } }
mit
a288c1f8cf75e92cf352f112ef60bcf8
33.379845
129
0.648929
3.611564
false
false
false
false
ZamzamInc/ZamzamKit
Sources/ZamzamUI/Sheets/BottomSheet.swift
1
11565
// // BottomSheet.swift // ZamzamUI // // Created by Basem Emara on 2021-08-29. // Copyright © 2021 Zamzam Inc. All rights reserved. // import SwiftUI #if os(iOS) @available(iOS, obsoleted: 16.0) private struct BottomSheet<Content: View>: UIViewControllerRepresentable { @Binding var isPresented: Bool let detents: [UISheetPresentationController.Detent] let prefersGrabberVisible: Bool let content: (() -> Content)? let onDismiss: (() -> Void)? func makeCoordinator() -> Coordinator { Coordinator(parent: self) } func makeUIViewController(context: Context) -> UIViewController { let controller = UIViewController() controller.view.backgroundColor = .clear return controller } func updateUIViewController(_ uiViewController: UIViewController, context: Context) { guard isPresented else { guard uiViewController.presentedViewController == context.coordinator.controller else { return } uiViewController.presentedViewController?.dismiss(animated: true, completion: onDismiss) return } guard let content = content?(), uiViewController.presentedViewController == nil else { return } let hostingController = UIHostingController(rootView: content) hostingController.presentationController?.delegate = context.coordinator if let presentationController = hostingController.presentationController as? UISheetPresentationController { presentationController.detents = detents presentationController.prefersGrabberVisible = prefersGrabberVisible } // Store reference to compare later for dismissal in multi bottom sheet scenarios context.coordinator.controller = hostingController uiViewController.present(hostingController, animated: true) } class Coordinator: NSObject, UISheetPresentationControllerDelegate { private let parent: BottomSheet var controller: UIViewController? init(parent: BottomSheet) { self.parent = parent } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { guard parent.isPresented else { return } parent.isPresented = false parent.onDismiss?() } } } /// A type that represents a height where a sheet naturally rests. public enum BottomSheetDetents { case medium case large var iOS15: UISheetPresentationController.Detent { switch self { case .medium: return .medium() case .large: return .large() } } @available(iOS 16, *) var iOS16: PresentationDetent { switch self { case .medium: return .medium case .large: return .large } } } public extension View { /// Presents a sheet when a binding to a `Boolean` value that you provide is true. /// /// struct ShowLicenseAgreement: View { /// @State private var isShowingSheet = false /// /// var body: some View { /// Button { /// isShowingSheet.toggle() /// } label: { /// Text("Show License Agreement") /// } /// .bottomSheet(isPresented: $isShowingSheet, onDismiss: didDismiss) { /// VStack { /// Text("License Agreement") /// .font(.title) /// .padding(50) /// Text("Terms and conditions go here.") /// .padding(50) /// Button("Dismiss") { /// isShowingSheet.toggle() /// } /// } /// } /// } /// /// func didDismiss() { /// // Handle the dismissing action. /// } /// } /// /// Bottom sheet presentation specify a sheet's size based on a detent, a height where a sheet naturally rests. /// /// - Parameters: /// - isPresented: A binding to a `Boolean` value that determines whether to present /// the sheet that you create in the modifier's `content` closure. /// - detents: An object that represents a height where a sheet naturally rests. /// - prefersDragIndicator: A Boolean value that determines whether the sheet shows a grabber at the top. /// - onDismiss: The closure to execute when dismissing the sheet. /// - content: A closure that returns the content of the sheet. @ViewBuilder func bottomSheet<Content: View>( isPresented: Binding<Bool>, detents: Set<BottomSheetDetents> = [.medium, .large], prefersDragIndicator: Bool? = nil, onDismiss: (() -> Void)? = nil, @ViewBuilder content: @escaping () -> Content ) -> some View { modifier { if #available(iOS 16, *) { $0.sheet(isPresented: isPresented, onDismiss: onDismiss) { content() .presentationDetents(Set(detents.map(\.iOS16))) .modifier(let: prefersDragIndicator) { content, value in content.presentationDragIndicator(value ? .visible : .hidden) } } } else { $0.background( BottomSheet( isPresented: isPresented, detents: detents.map(\.iOS15), prefersGrabberVisible: prefersDragIndicator ?? true, content: content, onDismiss: onDismiss ) ) } } } } public extension View { /// Presents a bottom sheet using the given item as a data source for the sheet's content. /// /// Use this method when you need to present a bottom sheet view with content /// from a custom data source. The example below shows a custom data source /// `InventoryItem` that the `content` closure uses to populate the display /// the bottom sheet shows to the user: /// /// struct ShowPartDetail: View { /// @State private var inventoryItem: InventoryItem? /// /// var body: some View { /// List((1..<6)) { index in /// Button("Part Details #\(index)") { /// inventoryItem = InventoryItem( /// id: "\(index)", /// partNumber: "Z-1234-\(index)", /// quantity: .random(in: 0..<100), /// name: "Widget \(index)" /// ) /// } /// } /// .bottomSheet(item: $inventoryItem, onDismiss: didDismiss) { item in /// List { /// Text("Part Number: \(item.partNumber)") /// Text("Name: \(item.name)") /// Text("Quantity On-Hand: \(item.quantity)") /// Button("Dismiss") { /// inventoryItem = nil /// } /// .frame(maxWidth: .infinity) /// } /// } /// } /// /// func didDismiss() { /// // Handle the dismissing action. /// } /// /// struct InventoryItem: Identifiable { /// var id: String /// let partNumber: String /// let quantity: Int /// let name: String /// } /// } /// /// - Parameters: /// - item: A binding to an optional source of truth for the sheet. /// When `item` is non-`nil`, the system passes the item's content to /// the modifier's closure. You display this content in a sheet that you /// create that the system displays to the user. If `item` changes, /// the system dismisses the sheet and replaces it with a new one /// using the same process. /// - detents: An object that represents a height where a sheet naturally rests. /// - prefersDragIndicator: A Boolean value that determines whether the sheet shows a grabber at the top. /// - onDismiss: The closure to execute when dismissing the sheet. /// - content: A closure returning the content of the sheet. @ViewBuilder func bottomSheet<Item, Content>( item: Binding<Item?>, detents: Set<BottomSheetDetents> = [.medium, .large], prefersDragIndicator: Bool? = nil, onDismiss: (() -> Void)? = nil, @ViewBuilder content: @escaping (Item) -> Content ) -> some View where Item: Identifiable, Content: View { bottomSheet( isPresented: Binding<Bool>( get: { item.wrappedValue != nil }, set: { guard !$0 else { return } item.wrappedValue = nil } ), detents: detents, prefersDragIndicator: prefersDragIndicator, onDismiss: onDismiss, content: { item.wrappedValue.map(content) } ) } } // MARK: - Previews #if DEBUG struct BottomSheet_Previews: PreviewProvider { static var previews: some View { Sample1View() Sample2View() } private struct Sample1View: View { @State private var dismissedStatus = "Content here..." @State private var isShowingSheet = false var body: some View { Button { isShowingSheet.toggle() } label: { Text("Show License Agreement") } .bottomSheet(isPresented: $isShowingSheet) { VStack { Text("License Agreement") .font(.title) .padding(50) Text("Terms and conditions go here.") .padding(50) Button("Dismiss") { isShowingSheet.toggle() } } } } } private struct Sample2View: View { @State private var inventoryItem: InventoryItem? var body: some View { List((1..<6)) { index in Button("Part Details #\(index)") { inventoryItem = InventoryItem( id: "\(index)", partNumber: "Z-1234-\(index)", quantity: .random(in: 0..<100), name: "Widget \(index)" ) } } .bottomSheet(item: $inventoryItem) { item in List { Text("Part Number: \(item.partNumber)") Text("Name: \(item.name)") Text("Quantity On-Hand: \(item.quantity)") Button("Dismiss") { inventoryItem = nil } .frame(maxWidth: .infinity) } } } struct InventoryItem: Identifiable { var id: String let partNumber: String let quantity: Int let name: String } } } #endif #endif
mit
4e8c8102ef997537d7f6ee892700bbd1
35.36478
116
0.514614
5.225486
false
false
false
false
tjw/swift
test/SILGen/multi_file.swift
1
2937
// RUN: %target-swift-frontend -module-name multi_file -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s func markUsed<T>(_ t: T) {} // CHECK-LABEL: sil hidden @$S10multi_file12rdar16016713{{[_0-9a-zA-Z]*}}F func rdar16016713(_ r: Range) { // CHECK: [[LIMIT:%[0-9]+]] = function_ref @$S10multi_file5RangeV5limitSivg : $@convention(method) (Range) -> Int // CHECK: {{%[0-9]+}} = apply [[LIMIT]]({{%[0-9]+}}) : $@convention(method) (Range) -> Int markUsed(r.limit) } // CHECK-LABEL: sil hidden @$S10multi_file26lazyPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F func lazyPropertiesAreNotStored(_ container: LazyContainer) { var container = container // CHECK: {{%[0-9]+}} = function_ref @$S10multi_file13LazyContainerV7lazyVarSivg : $@convention(method) (@inout LazyContainer) -> Int markUsed(container.lazyVar) } // CHECK-LABEL: sil hidden @$S10multi_file29lazyRefPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F func lazyRefPropertiesAreNotStored(_ container: LazyContainerClass) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $LazyContainerClass): // CHECK: {{%[0-9]+}} = class_method [[ARG]] : $LazyContainerClass, #LazyContainerClass.lazyVar!getter.1 : (LazyContainerClass) -> () -> Int, $@convention(method) (@guaranteed LazyContainerClass) -> Int markUsed(container.lazyVar) } // CHECK-LABEL: sil hidden @$S10multi_file25finalVarsAreDevirtualizedyyAA18FinalPropertyClassCF func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $FinalPropertyClass): // CHECK: ref_element_addr [[ARG]] : $FinalPropertyClass, #FinalPropertyClass.foo markUsed(obj.foo) // CHECK: class_method [[ARG]] : $FinalPropertyClass, #FinalPropertyClass.bar!getter.1 markUsed(obj.bar) } // rdar://18448869 // CHECK-LABEL: sil hidden @$S10multi_file34finalVarsDontNeedMaterializeForSetyyAA27ObservingPropertyFinalClassCF func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) { obj.foo += 1 // CHECK: function_ref @$S10multi_file27ObservingPropertyFinalClassC3fooSivg // CHECK: function_ref @$S10multi_file27ObservingPropertyFinalClassC3fooSivs } // rdar://18503960 // Ensure that we type-check the materializeForSet accessor from the protocol. class HasComputedProperty: ProtocolWithProperty { var foo: Int { get { return 1 } set {} } } // CHECK-LABEL: sil hidden [transparent] @$S10multi_file19HasComputedPropertyC3fooSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK-LABEL: sil private [transparent] [thunk] @$S10multi_file19HasComputedPropertyCAA012ProtocolWithE0A2aDP3fooSivmTW : $@convention(witness_method: ProtocolWithProperty) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
apache-2.0
bc5bcbf4f3cd6ed7979cf631a9f33ff3
54.415094
313
0.743275
3.551391
false
false
false
false
mlpqaz/V2ex
ZZV2ex/Pods/Ji/Source/Ji.swift
3
10009
// // Ji.swift // Ji // // Created by Honghao Zhang on 2015-07-21. // Copyright (c) 2015 Honghao Zhang (张宏昊) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation public typealias 戟 = Ji /// Ji document open class Ji { /// A flag specifies whether the data is XML or not. internal var isXML: Bool = true /// The XML/HTML data. open fileprivate(set) var data: Data? /// The encoding used by in this document. open fileprivate(set) var encoding: String.Encoding = String.Encoding.utf8 public typealias htmlDocPtr = xmlDocPtr /// The xmlDocPtr for this document open fileprivate(set) var xmlDoc: xmlDocPtr? = nil /// Alias for xmlDoc open fileprivate(set) var htmlDoc: htmlDocPtr? { get { return xmlDoc } set { xmlDoc = newValue } } // MARK: - Init /** Initializes a Ji document object with the supplied data, encoding and boolean flag. - parameter data: The XML/HTML data. - parameter encoding: The encoding used by data. - parameter isXML: Whether this is a XML data, true for XML, false for HTML. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public required init?(data: Data?, encoding: String.Encoding, isXML: Bool) { if let data = data, data.count > 0 { self.isXML = isXML self.data = data self.encoding = encoding let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count) defer { bytes.deallocate(capacity: data.count) } data.copyBytes(to: bytes, count: data.count) let cBuffer = UnsafeRawPointer(bytes).assumingMemoryBound(to: CChar.self) let cSize = CInt(data.count) let cfEncoding = CFStringConvertNSStringEncodingToEncoding(encoding.rawValue) let cfEncodingAsString: CFString = CFStringConvertEncodingToIANACharSetName(cfEncoding) let cEncoding: UnsafePointer<CChar>? = CFStringGetCStringPtr(cfEncodingAsString, 0) if isXML { let options = CInt(XML_PARSE_RECOVER.rawValue) xmlDoc = xmlReadMemory(cBuffer, cSize, nil, cEncoding, options) } else { let options = CInt(HTML_PARSE_RECOVER.rawValue | HTML_PARSE_NOWARNING.rawValue | HTML_PARSE_NOERROR.rawValue) htmlDoc = htmlReadMemory(cBuffer, cSize, nil, cEncoding, options) } if xmlDoc == nil { return nil } } else { return nil } } /** Initializes a Ji document object with the supplied data and boolean flag, using NSUTF8StringEncoding. - parameter data: The XML/HTML data. - parameter isXML: Whether this is a XML data, true for XML, false for HTML. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(data: Data?, isXML: Bool) { self.init(data: data, encoding: String.Encoding.utf8, isXML: isXML) } // MARK: - Data Init /** Initializes a Ji document object with the supplied XML data and encoding. - parameter xmlData: The XML data. - parameter encoding: The encoding used by data. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(xmlData: Data, encoding: String.Encoding) { self.init(data: xmlData, encoding: encoding, isXML: true) } /** Initializes a Ji document object with the supplied XML data, using NSUTF8StringEncoding. - parameter xmlData: The XML data. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(xmlData: Data) { self.init(data: xmlData, isXML: true) } /** Initializes a Ji document object with the supplied HTML data and encoding. - parameter htmlData: The HTML data. - parameter encoding: The encoding used by data. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(htmlData: Data, encoding: String.Encoding) { self.init(data: htmlData, encoding: encoding, isXML: false) } /** Initializes a Ji document object with the supplied HTML data, using NSUTF8StringEncoding. - parameter htmlData: The HTML data. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(htmlData: Data) { self.init(data: htmlData, isXML: false) } // MARK: - URL Init /** Initializes a Ji document object with the contents of supplied URL, encoding and boolean flag. - parameter url: The URL from which to read data. - parameter encoding: The encoding used by data. - parameter isXML: Whether this is a XML data URL, true for XML, false for HTML. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(contentsOfURL url: URL, encoding: String.Encoding, isXML: Bool) { let data = try? Data(contentsOf: url) self.init(data: data, encoding: encoding, isXML: isXML) } /** Initializes a Ji document object with the contents of supplied URL, and boolean flag, using NSUTF8StringEncoding. - parameter url: The URL from which to read data. - parameter isXML: Whether this is a XML data URL, true for XML, false for HTML. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(contentsOfURL url: URL, isXML: Bool) { self.init(contentsOfURL: url, encoding: String.Encoding.utf8, isXML: isXML) } /** Initializes a Ji document object with the contents of supplied XML URL, using NSUTF8StringEncoding. - parameter xmlURL: The XML URL from which to read data. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(xmlURL: URL) { self.init(contentsOfURL: xmlURL, isXML: true) } /** Initializes a Ji document object with the contents of supplied HTML URL, using NSUTF8StringEncoding. - parameter htmlURL: The HTML URL from which to read data. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(htmlURL: URL) { self.init(contentsOfURL: htmlURL, isXML: false) } // MARK: - String Init /** Initializes a Ji document object with a XML string and it's encoding. - parameter xmlString: XML string. - parameter encoding: The encoding used by xmlString. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(xmlString: String, encoding: String.Encoding) { let data = xmlString.data(using: encoding, allowLossyConversion: false) self.init(data: data, encoding: encoding, isXML: true) } /** Initializes a Ji document object with a HTML string and it's encoding. - parameter htmlString: HTML string. - parameter encoding: The encoding used by htmlString. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(htmlString: String, encoding: String.Encoding) { let data = htmlString.data(using: encoding, allowLossyConversion: false) self.init(data: data, encoding: encoding, isXML: false) } /** Initializes a Ji document object with a XML string, using NSUTF8StringEncoding. - parameter xmlString: XML string. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(xmlString: String) { let data = xmlString.data(using: String.Encoding.utf8, allowLossyConversion: false) self.init(data: data, isXML: true) } /** Initializes a Ji document object with a HTML string, using NSUTF8StringEncoding. - parameter htmlString: HTML string. - returns: The initialized Ji document object or nil if the object could not be initialized. */ public convenience init?(htmlString: String) { let data = htmlString.data(using: String.Encoding.utf8, allowLossyConversion: false) self.init(data: data, isXML: false) } // MARK: - Deinit deinit { xmlFreeDoc(xmlDoc) } // MARK: - Public methods /// Root node of this Ji document object. open lazy var rootNode: JiNode? = { guard let rootNodePointer = xmlDocGetRootElement(self.xmlDoc) else { return nil } return JiNode(xmlNode: rootNodePointer, jiDocument: self) }() /** Perform XPath query on this document. - parameter xPath: XPath query string. - returns: An array of JiNode or nil if rootNode is nil. An empty array will be returned if XPath matches no nodes. */ open func xPath(_ xPath: String) -> [JiNode]? { return self.rootNode?.xPath(xPath) } } // MARK: - Equatable extension Ji: Equatable { } public func ==(lhs: Ji, rhs: Ji) -> Bool { return lhs.xmlDoc == rhs.xmlDoc } // MARK: - CustomStringConvertible extension Ji: CustomStringConvertible { public var description: String { return rootNode?.rawContent ?? "nil" } } // MARK: - CustomDebugStringConvertible extension Ji: CustomDebugStringConvertible { public var debugDescription: String { return description } }
apache-2.0
42c2212d481fc0b9a25adf833617511e
31.365696
116
0.728027
3.883883
false
false
false
false
bradhilton/August
Sources/Task/Timer.swift
1
566
// // Timer.swift // August // // Created by Bradley Hilton on 5/20/16. // Copyright © 2016 Brad Hilton. All rights reserved. // struct Timer { var time: TimeInterval { guard let timestamp = timestamp else { return allotedTime } return allotedTime + Date().timeIntervalSince(timestamp) } var allotedTime: TimeInterval = 0 var timestamp: Date? mutating func resume() { timestamp = timestamp ?? Date() } mutating func suspend() { allotedTime = time timestamp = nil } }
mit
e5c651100969de4556734ac7a363bd5f
19.178571
67
0.59823
4.154412
false
false
false
false
ykyouhei/KYDrawerController
KYDrawerController/Classes/KYDrawerController.swift
1
18566
/* Copyright (c) 2015 Kyohei Yamaguchi. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit @objc public protocol KYDrawerControllerDelegate { @objc optional func drawerController(_ drawerController: KYDrawerController, willChangeState state: KYDrawerController.DrawerState) @objc optional func drawerController(_ drawerController: KYDrawerController, didChangeState state: KYDrawerController.DrawerState) @available(*, deprecated, renamed: "drawerController(_:didChangeState:)") @objc optional func drawerController(_ drawerController: KYDrawerController, stateChanged state: KYDrawerController.DrawerState) } open class KYDrawerController: UIViewController, UIGestureRecognizerDelegate { /**************************************************************************/ // MARK: - Types /**************************************************************************/ @objc public enum DrawerDirection: Int { case left, right } @objc public enum DrawerState: Int { case opened, closed } /**************************************************************************/ // MARK: - Properties /**************************************************************************/ @IBInspectable public var containerViewMaxAlpha: CGFloat = 0.2 @IBInspectable public var drawerAnimationDuration: TimeInterval = 0.25 @IBInspectable public var mainSegueIdentifier: String? @IBInspectable public var drawerSegueIdentifier: String? private var _drawerConstraint: NSLayoutConstraint! private var _drawerWidthConstraint: NSLayoutConstraint! private var _panStartLocation = CGPoint.zero private var _panDelta: CGFloat = 0 lazy private var _containerView: UIView = { let view = UIView(frame: self.view.frame) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor(white: 0.0, alpha: 0) view.addGestureRecognizer(self.containerViewTapGesture) return view }() /// Returns `true` if `beginAppearanceTransition()` has been called with `true` as the first parameter, and `false` /// if the first parameter is `false`. Returns `nil` if appearance transition is not in progress. private var _isAppearing: Bool? public var screenEdgePanGestureEnabled = true public private(set) lazy var screenEdgePanGesture: UIScreenEdgePanGestureRecognizer = { let gesture = UIScreenEdgePanGestureRecognizer( target: self, action: #selector(KYDrawerController.handlePanGesture(_:)) ) switch self.drawerDirection { case .left: gesture.edges = .left case .right: gesture.edges = .right } gesture.delegate = self return gesture }() public private(set) lazy var panGesture: UIPanGestureRecognizer = { let gesture = UIPanGestureRecognizer( target: self, action: #selector(KYDrawerController.handlePanGesture(_:)) ) gesture.delegate = self return gesture }() public private(set) lazy var containerViewTapGesture: UITapGestureRecognizer = { let gesture = UITapGestureRecognizer( target: self, action: #selector(KYDrawerController.didtapContainerView(_:)) ) gesture.delegate = self return gesture }() public weak var delegate: KYDrawerControllerDelegate? public var drawerDirection: DrawerDirection = .left { didSet { switch drawerDirection { case .left: screenEdgePanGesture.edges = .left case .right: screenEdgePanGesture.edges = .right } let tmp = drawerViewController drawerViewController = tmp } } public var drawerState: DrawerState { get { return _containerView.isHidden ? .closed : .opened } set { setDrawerState(newValue, animated: false) } } @IBInspectable public var drawerWidth: CGFloat = 280 { didSet { _drawerWidthConstraint?.constant = drawerWidth } } public var displayingViewController: UIViewController? { switch drawerState { case .closed: return mainViewController case .opened: return drawerViewController } } public var mainViewController: UIViewController! { didSet { let isVisible = (drawerState == .closed) if let oldController = oldValue { oldController.willMove(toParent: nil) if isVisible { oldController.beginAppearanceTransition(false, animated: false) } oldController.view.removeFromSuperview() if isVisible { oldController.endAppearanceTransition() } oldController.removeFromParent() } guard let mainViewController = mainViewController else { return } addChild(mainViewController) if isVisible { mainViewController.beginAppearanceTransition(true, animated: false) } mainViewController.view.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(mainViewController.view, at: 0) let viewDictionary = ["mainView" : mainViewController.view!] view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[mainView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[mainView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) if isVisible { mainViewController.endAppearanceTransition() } mainViewController.didMove(toParent: self) } } public var drawerViewController : UIViewController? { didSet { let isVisible = (drawerState == .opened) if let oldController = oldValue { oldController.willMove(toParent: nil) if isVisible { oldController.beginAppearanceTransition(false, animated: false) } oldController.view.removeFromSuperview() if isVisible { oldController.endAppearanceTransition() } oldController.removeFromParent() } guard let drawerViewController = drawerViewController else { return } addChild(drawerViewController) if isVisible { drawerViewController.beginAppearanceTransition(true, animated: false) } drawerViewController.view.layer.shadowColor = UIColor.black.cgColor drawerViewController.view.layer.shadowOpacity = 0.4 drawerViewController.view.layer.shadowRadius = 5.0 drawerViewController.view.translatesAutoresizingMaskIntoConstraints = false _containerView.addSubview(drawerViewController.view) let itemAttribute: NSLayoutConstraint.Attribute let toItemAttribute: NSLayoutConstraint.Attribute switch drawerDirection { case .left: itemAttribute = .right toItemAttribute = .left case .right: itemAttribute = .left toItemAttribute = .right } _drawerWidthConstraint = NSLayoutConstraint( item: drawerViewController.view, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1, constant: drawerWidth ) drawerViewController.view.addConstraint(_drawerWidthConstraint) _drawerConstraint = NSLayoutConstraint( item: drawerViewController.view, attribute: itemAttribute, relatedBy: NSLayoutConstraint.Relation.equal, toItem: _containerView, attribute: toItemAttribute, multiplier: 1, constant: 0 ) _containerView.addConstraint(_drawerConstraint) let viewDictionary = ["drawerView" : drawerViewController.view!] _containerView.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[drawerView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) _containerView.layoutIfNeeded() if isVisible { drawerViewController.endAppearanceTransition() } drawerViewController.didMove(toParent: self) } } /**************************************************************************/ // MARK: - initialize /**************************************************************************/ public init(drawerDirection: DrawerDirection, drawerWidth: CGFloat) { super.init(nibName: nil, bundle: nil) self.drawerDirection = drawerDirection self.drawerWidth = drawerWidth } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /**************************************************************************/ // MARK: - Life Cycle /**************************************************************************/ override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let viewDictionary = ["_containerView": _containerView] view.addGestureRecognizer(screenEdgePanGesture) view.addGestureRecognizer(panGesture) view.addSubview(_containerView) view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[_containerView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[_containerView]-0-|", options: [], metrics: nil, views: viewDictionary ) ) _containerView.isHidden = true if let mainSegueID = mainSegueIdentifier { performSegue(withIdentifier: mainSegueID, sender: self) } if let drawerSegueID = drawerSegueIdentifier { performSegue(withIdentifier: drawerSegueID, sender: self) } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) displayingViewController?.beginAppearanceTransition(true, animated: animated) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) displayingViewController?.endAppearanceTransition() } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) displayingViewController?.beginAppearanceTransition(false, animated: animated) } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) displayingViewController?.endAppearanceTransition() } // We will manually call `mainViewController` or `drawerViewController`'s // view appearance methods. override open var shouldAutomaticallyForwardAppearanceMethods: Bool { get { return false } } /**************************************************************************/ // MARK: - Public Method /**************************************************************************/ public func setDrawerState(_ state: DrawerState, animated: Bool) { delegate?.drawerController?(self, willChangeState: state) _containerView.isHidden = false let duration: TimeInterval = animated ? drawerAnimationDuration : 0 let isAppearing = state == .opened if _isAppearing != isAppearing { _isAppearing = isAppearing drawerViewController?.beginAppearanceTransition(isAppearing, animated: animated) mainViewController?.beginAppearanceTransition(!isAppearing, animated: animated) } UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in switch state { case .closed: self._drawerConstraint.constant = 0 self._containerView.backgroundColor = UIColor(white: 0, alpha: 0) case .opened: let constant: CGFloat switch self.drawerDirection { case .left: constant = self.drawerWidth case .right: constant = -self.drawerWidth } self._drawerConstraint.constant = constant self._containerView.backgroundColor = UIColor( white: 0 , alpha: self.containerViewMaxAlpha ) } self._containerView.layoutIfNeeded() }) { (finished: Bool) -> Void in if state == .closed { self._containerView.isHidden = true } self.drawerViewController?.endAppearanceTransition() self.mainViewController?.endAppearanceTransition() self._isAppearing = nil if let didChangeState = self.delegate?.drawerController(_:didChangeState:) { didChangeState(self, state) } else { self.delegate?.drawerController?(self, stateChanged: state) } } } /**************************************************************************/ // MARK: - Private Method /**************************************************************************/ @objc final func handlePanGesture(_ sender: UIGestureRecognizer) { _containerView.isHidden = false if sender.state == .began { _panStartLocation = sender.location(in: view) } let delta = CGFloat(sender.location(in: view).x - _panStartLocation.x) let constant : CGFloat let backGroundAlpha : CGFloat let drawerState : DrawerState switch drawerDirection { case .left: drawerState = _panDelta <= 0 ? .closed : .opened constant = min(_drawerConstraint.constant + delta, drawerWidth) backGroundAlpha = min( containerViewMaxAlpha, containerViewMaxAlpha*(abs(constant)/drawerWidth) ) case .right: drawerState = _panDelta >= 0 ? .closed : .opened constant = max(_drawerConstraint.constant + delta, -drawerWidth) backGroundAlpha = min( containerViewMaxAlpha, containerViewMaxAlpha*(abs(constant)/drawerWidth) ) } _drawerConstraint.constant = constant _containerView.backgroundColor = UIColor( white: 0, alpha: backGroundAlpha ) switch sender.state { case .changed: let isAppearing = drawerState != .opened if _isAppearing == nil { _isAppearing = isAppearing drawerViewController?.beginAppearanceTransition(isAppearing, animated: true) mainViewController?.beginAppearanceTransition(!isAppearing, animated: true) } _panStartLocation = sender.location(in: view) _panDelta = delta case .ended, .cancelled: setDrawerState(drawerState, animated: true) default: break } } @objc final func didtapContainerView(_ gesture: UITapGestureRecognizer) { setDrawerState(.closed, animated: true) } /**************************************************************************/ // MARK: - UIGestureRecognizerDelegate /**************************************************************************/ public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { switch gestureRecognizer { case panGesture: return drawerState == .opened case screenEdgePanGesture: return screenEdgePanGestureEnabled ? drawerState == .closed : false default: return touch.view == gestureRecognizer.view } } }
mit
0bbeabe5f21a2c0f909389de526dd5b2
36.659229
135
0.561349
6.304244
false
false
false
false
lyb5834/YBAttributeTextTapForSwfit
YBAttributeTextTapForSwfit/YBAttributeTextTapForSwfit.swift
2
10933
// // YBAttributeTextTapForSwfit.swift // YBAttributeTextTapForSwfit // // Created by LYB on 16/7/7. // Copyright © 2016年 LYB. All rights reserved. // import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } private var isTapAction : Bool? private var attributeStrings : [YBAttributeModel]? private var tapBlock : ((_ str : String ,_ range : NSRange ,_ index : Int) -> Void)? private var isTapEffect : Bool = true private var effectDic : Dictionary<String , NSAttributedString>? extension UILabel { // MARK: - Objects /// 是否打开点击效果,默认是打开 var enabledTapEffect : Bool { set { isTapEffect = newValue } get { return isTapEffect } } // MARK: - mainFunction /** 给文本添加点击事件 - parameter strings: 需要点击的字符串数组 - parameter tapAction: 点击事件回调 */ func yb_addAttributeTapAction( _ strings : [String] , tapAction : @escaping ((String , NSRange , Int) -> Void)) -> Void { yb_getRange(strings) tapBlock = tapAction } // MARK: - touchActions open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if isTapAction == false { return } let touch = touches.first let point = touch?.location(in: self) yb_getTapFrame(point!) { (String, NSRange, Int) -> Void in if tapBlock != nil { tapBlock! (String, NSRange , Int) } if isTapEffect { self.yb_saveEffectDicWithRange(NSRange) self.yb_tapEffectWithStatus(true) } } } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if isTapEffect { self.performSelector(onMainThread: #selector(self.yb_tapEffectWithStatus(_:)), with: nil, waitUntilDone: false) } } open override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) { if isTapEffect { self.performSelector(onMainThread: #selector(self.yb_tapEffectWithStatus(_:)), with: nil, waitUntilDone: false) } } override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if isTapAction == true { let result = yb_getTapFrame(point, result: { ( String, NSRange, Int) -> Void in }) if result == true { return self } } return super.hitTest(point, with: event) } // MARK: - getTapFrame @discardableResult fileprivate func yb_getTapFrame(_ point : CGPoint , result : ((_ str : String ,_ range : NSRange ,_ index : Int) -> Void)) -> Bool { let framesetter = CTFramesetterCreateWithAttributedString(self.attributedText!) var path = CGMutablePath() path.addRect(self.bounds, transform: CGAffineTransform.identity) var frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) let range = CTFrameGetVisibleStringRange(frame) if self.attributedText?.length > range.length { var m_font : UIFont let n_font = self.attributedText?.attribute(NSAttributedString.Key.font, at: 0, effectiveRange: nil) if n_font != nil { m_font = n_font as! UIFont }else if (self.font != nil) { m_font = self.font }else { m_font = UIFont.systemFont(ofSize: 17) } path = CGMutablePath() path.addRect(CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height + m_font.lineHeight), transform: CGAffineTransform.identity) frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) } let lines = CTFrameGetLines(frame) if lines == [] as CFArray { return false } let count = CFArrayGetCount(lines) var origins = [CGPoint](repeating: CGPoint.zero, count: count) CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), &origins) let transform = CGAffineTransform(translationX: 0, y: self.bounds.size.height).scaledBy(x: 1.0, y: -1.0); let verticalOffset = 0.0 for i : CFIndex in 0..<count { let linePoint = origins[i] let line = CFArrayGetValueAtIndex(lines, i) let lineRef = unsafeBitCast(line,to: CTLine.self) let flippedRect : CGRect = yb_getLineBounds(lineRef , point: linePoint) var rect = flippedRect.applying(transform) rect = rect.insetBy(dx: 0, dy: 0) rect = rect.offsetBy(dx: 0, dy: CGFloat(verticalOffset)) let style = self.attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: nil) var lineSpace : CGFloat = 0.0 if (style != nil) { lineSpace = (style as! NSParagraphStyle).lineSpacing }else { lineSpace = 0.0 } let lineOutSpace = (CGFloat(self.bounds.size.height) - CGFloat(lineSpace) * CGFloat(count - 1) - CGFloat(rect.size.height) * CGFloat(count)) / 2 rect.origin.y = lineOutSpace + rect.size.height * CGFloat(i) + lineSpace * CGFloat(i) if rect.contains(point) { let relativePoint = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY) var index = CTLineGetStringIndexForPosition(lineRef, relativePoint) var offset : CGFloat = 0.0 CTLineGetOffsetForStringIndex(lineRef, index, &offset) if offset > relativePoint.x { index = index - 1 } let link_count = attributeStrings?.count for j in 0 ..< link_count! { let model = attributeStrings![j] let link_range = model.range if NSLocationInRange(index, link_range!) { result(model.str!,model.range!,j) return true } } } } return false } fileprivate func yb_getLineBounds(_ line : CTLine , point : CGPoint) -> CGRect { var ascent : CGFloat = 0.0; var descent : CGFloat = 0.0; var leading : CGFloat = 0.0; let width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading) let height = ascent + fabs(descent) + leading return CGRect.init(x: point.x, y: point.y , width: CGFloat(width), height: height) } // MARK: - getRange fileprivate func yb_getRange(_ strings : [String]) -> Void { if self.attributedText?.length == 0 { return; } self.isUserInteractionEnabled = true isTapAction = true var totalString = self.attributedText?.string attributeStrings = []; for str : String in strings { let range = totalString?.range(of: str) if (range?.lowerBound != nil) { totalString = totalString?.replacingCharacters(in: range!, with: self.yb_getString(str.characters.count)) let model = YBAttributeModel() model.range = totalString?.nsRange(from: range!) model.str = str attributeStrings?.append(model) } } } fileprivate func yb_getString(_ count : Int) -> String { var string = "" for _ in 0 ..< count { string = string + " " } return string } // MARK: - tapEffect fileprivate func yb_saveEffectDicWithRange(_ range : NSRange) -> Void { effectDic = [:] let subAttribute = self.attributedText?.attributedSubstring(from: range) _ = effectDic?.updateValue(subAttribute!, forKey: NSStringFromRange(range)) } @objc fileprivate func yb_tapEffectWithStatus(_ status : Bool) -> Void { if isTapEffect { let attStr = NSMutableAttributedString.init(attributedString: self.attributedText!) let subAtt = NSMutableAttributedString.init(attributedString: (effectDic?.values.first)!) let range = NSRangeFromString(effectDic!.keys.first!) if status { subAtt.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.lightGray, range: NSMakeRange(0, subAtt.length)) attStr.replaceCharacters(in: range, with: subAtt) }else { attStr.replaceCharacters(in: range, with: subAtt) } self.attributedText = attStr } } } private class YBAttributeModel: NSObject { var range : NSRange? var str : String? } private extension String { func nsRange(from range: Range<String.Index>) -> NSRange { return NSRange(range,in : self) } func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } }
mit
f3ad2e9cba7334d022fb0c0dd7e50afc
31.884848
167
0.53861
4.772208
false
false
false
false
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Core/Utils/AsciiArt/AsciiPalette.swift
1
2370
// // AsciiPalette.swift // SwiftAsciiArt // // Created by Joshua Smith on 4/26/15. // Copyright (c) 2015 iJoshSmith. All rights reserved. // import Foundation import UIKit /** Provides a list of ASCII symbols sorted from darkest to brightest. */ class AsciiPalette { fileprivate let font: UIFont init(font: UIFont) { self.font = font } lazy var symbols: [String] = self.loadSymbols() fileprivate func loadSymbols() -> [String] { //return symbolsSortedByIntensityForAsciiCodes(32...126) // from ' ' to '~' return symbolsSortedByIntensityForAsciiCodes(0...255) // from ' ' to '~' } fileprivate func symbolsSortedByIntensityForAsciiCodes(_ codes: CountableClosedRange<Int>) -> [String] { let symbols = codes.map { self.symbolFromAsciiCode($0) }, symbolImages = symbols.map { UIImage.imageOfSymbol($0, self.font) }, whitePixelCounts = symbolImages.map { self.countWhitePixelsInImage($0) }, sortedSymbols = sortByIntensity(symbols, whitePixelCounts) return sortedSymbols } fileprivate func symbolFromAsciiCode(_ code: Int) -> String { return String(Character(UnicodeScalar(code)!)) } fileprivate func countWhitePixelsInImage(_ image: UIImage) -> Int { let dataProvider = image.cgImage?.dataProvider, pixelData = dataProvider?.data, pixelPointer = CFDataGetBytePtr(pixelData), byteCount = CFDataGetLength(pixelData), pixelOffsets = stride(from: 0, to: byteCount, by: Pixel.bytesPerPixel) return pixelOffsets.reduce(0) { (count, offset) -> Int in let r = pixelPointer?[offset + 0], g = pixelPointer?[offset + 1], b = pixelPointer?[offset + 2], isWhite = (r == 255) && (g == 255) && (b == 255) return isWhite ? count + 1 : count } } fileprivate func sortByIntensity(_ symbols: [String], _ whitePixelCounts: [Int]) -> [String] { let mappings = NSDictionary(objects: symbols, forKeys: whitePixelCounts as [NSCopying]), uniqueCounts = Set(whitePixelCounts), sortedCounts = uniqueCounts.sorted(), sortedSymbols = sortedCounts.map { mappings[$0] as! String } return sortedSymbols } }
mit
894d47d35941ab9281844e40d7813aa4
33.347826
106
0.618565
4.30127
false
false
false
false
mackoj/GOTiPad
GOTIpad/GameLogic/HouseHold.swift
1
1567
// // HouseHold.swift // GOTIpad // // Created by jeffreymacko on 29/12/2015. // Copyright © 2015 jeffreymacko. All rights reserved. // import UIKit struct Color : Codable { let colorHex : String } struct HouseHold { let name : String let color : Color let image : UIImage let houseHold : HouseHoldType var members : [HouseHoldMemberCard] = [] var pawns : [Pawn] = [] var orderTokens : [OrderToken] = [] var initialLands : [Land] = [] init(houseHold inputHouseHold : HouseHoldType) { houseHold = inputHouseHold switch inputHouseHold { case .stark: name = "Stark" color = Color(colorHex: "") image = #imageLiteral(resourceName: "GoT_Family_Stark_0") case .greyjoy: name = "Greyjoy" color = Color(colorHex: "") image = #imageLiteral(resourceName: "GoT_Family_Greyjoy_0") case .lennister: name = "Lennister" color = Color(colorHex: "") image = #imageLiteral(resourceName: "GoT_Family_Lannister_0") case .baratheon: name = "Baratheon" color = Color(colorHex: "") image = #imageLiteral(resourceName: "GoT_Family_Baratheon_0") case .martell: name = "Martell" color = Color(colorHex: "") image = #imageLiteral(resourceName: "GoT_Family_Martell_0") case .tyrell: name = "Tyrell" color = Color(colorHex: "") image = #imageLiteral(resourceName: "GoT_Family_Tyrell_0") } } } extension HouseHold { func hasAssignAllPossibleOrderToken() -> Bool { return false } }
mit
44e7921f3385d58b16b26ce7605c74e3
24.258065
67
0.621967
3.495536
false
false
false
false
uasys/swift
test/SILGen/optional.swift
3
4055
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s func testCall(_ f: (() -> ())?) { f?() } // CHECK: sil hidden @{{.*}}testCall{{.*}} // CHECK: bb0([[T0:%.*]] : @owned $Optional<@callee_owned () -> ()>): // CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]] // CHECK: [[T1:%.*]] = select_enum [[T0_COPY]] // CHECK-NEXT: cond_br [[T1]], [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]] // CHECK: [[NONE]]: // CHECK: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK: br [[NOTHING_BLOCK_EXIT:bb[0-9]+]] // If it does, project and load the value out of the implicitly unwrapped // optional... // CHECK: [[SOME]]: // CHECK-NEXT: [[FN0:%.*]] = unchecked_enum_data [[T0_COPY]] : $Optional<@callee_owned () -> ()>, #Optional.some!enumelt.1 // .... then call it // CHECK-NEXT: apply [[FN0]]() // CHECK: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK: br [[EXIT:bb[0-9]+]]( // (first nothing block) // CHECK: [[NOTHING_BLOCK_EXIT]]: // CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt // CHECK-NEXT: br [[EXIT]] // CHECK: } // end sil function '_T08optional8testCallyyycSgF' func testAddrOnlyCallResult<T>(_ f: (() -> T)?) { var f = f var x = f?() } // CHECK-LABEL: sil hidden @{{.*}}testAddrOnlyCallResult{{.*}} : $@convention(thin) <T> (@owned Optional<@callee_owned () -> @out T>) -> () // CHECK: bb0([[T0:%.*]] : @owned $Optional<@callee_owned () -> @out T>): // CHECK: [[F:%.*]] = alloc_box $<τ_0_0> { var Optional<@callee_owned () -> @out τ_0_0> } <T>, var, name "f" // CHECK-NEXT: [[PBF:%.*]] = project_box [[F]] // CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]] // CHECK: store [[T0_COPY]] to [init] [[PBF]] // CHECK: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: [[X:%.*]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>, var, name "x" // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK-NEXT: [[TEMP:%.*]] = init_enum_data_addr [[PBX]] // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PBF]] // Check whether 'f' holds a value. // CHECK: [[T1:%.*]] = select_enum_addr [[READ]] // CHECK-NEXT: cond_br [[T1]], bb2, bb1 // If so, pull out the value... // CHECK: bb2: // CHECK-NEXT: [[T1:%.*]] = unchecked_take_enum_data_addr [[READ]] // CHECK-NEXT: [[T0:%.*]] = load [copy] [[T1]] // CHECK-NEXT: end_access [[READ]] // ...evaluate the rest of the suffix... // CHECK-NEXT: apply [[T0]]([[TEMP]]) // ...and coerce to T? // CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}some // CHECK-NEXT: br bb3 // Continuation block. // CHECK: bb3 // CHECK-NEXT: destroy_value [[X]] // CHECK-NEXT: destroy_value [[F]] // CHECK-NEXT: destroy_value %0 // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() // Nothing block. // CHECK: bb4: // CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}none // CHECK-NEXT: br bb3 // <rdar://problem/15180622> func wrap<T>(_ x: T) -> T? { return x } // CHECK-LABEL: sil hidden @_T08optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F func wrap_then_unwrap<T>(_ x: T) -> T { // CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]] // CHECK: [[FAIL]]: // CHECK: unreachable // CHECK: [[OK]]: // CHECK: unchecked_take_enum_data_addr return wrap(x)! } // CHECK-LABEL: sil hidden @_T08optional10tuple_bind{{[_0-9a-zA-Z]*}}F func tuple_bind(_ x: (Int, String)?) -> String? { return x?.1 // CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]] // CHECK: [[NONNULL]]: // CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1 // CHECK-NOT: destroy_value [[STRING]] } // rdar://21883752 - We were crashing on this function because the deallocation happened // out of scope. // CHECK-LABEL: sil hidden @_T08optional16crash_on_deallocys10DictionaryVySiSaySiGGFfA_ func crash_on_dealloc(_ dict : [Int : [Int]] = [:]) { var dict = dict dict[1]?.append(2) }
apache-2.0
b0cc4388a36952a0ce9eb9c74f4adaf5
37.580952
139
0.564552
2.899785
false
false
false
false
RyoAbe/PARTNER
PARTNER/PARTNER/Core/Model/PFObject/PFObject+Partner.swift
1
5371
// // PFObject+Partner.swift // PARTNER // // Created by RyoAbe on 2015/03/21. // Copyright (c) 2015年 RyoAbe. All rights reserved. // import UIKit extension PFUser { class func currentMyProfile() -> PFMyProfile { return PFMyProfile(user: PFUser.currentUser()!) } class func currentPartner(partnerId: String) -> PFPartner? { if let pfObject = PFUser.query()!.getObjectWithId(partnerId) as? PFUser { return PFPartner(user: pfObject) } return nil } } class PFObjectBase { var pfObject: PFObject? init(object: PFObject) { self.pfObject = object } init(className: String){ self.pfObject = PFObject(className: className) } init(className: String, objectId: String) { self.pfObject = PFQuery.getObjectOfClass(className, objectId: objectId) } func save(error: NSErrorPointer) { pfObject!.save(error) } func saveInBackgroundWithBlock(block: (Bool, NSError?) -> Void) { pfObject!.saveInBackgroundWithBlock(block) } func saveEventually(block: (Bool, NSError?) -> Void) { pfObject!.saveEventually(block) } } class PFProfile: PFObjectBase { init(user: PFUser) { super.init(object: user) } var pfUser: PFUser { return pfObject as! PFUser } var objectId: String { return pfUser.objectId! } var isAuthenticated: Bool { return pfUser.isAuthenticated() } var username: String { get { return pfUser.username! } set { pfUser.username = newValue } } var hasPartner: Bool { return partner != nil } var profileImage: PFFile { get { return pfUser["profileImage"] as! PFFile } set { pfUser["profileImage"] = newValue } } var fbId: String { get { return pfUser["fbId"] as! String } set { pfUser["fbId"] = newValue } } var partner: PFUser? { get { let query = PFUser.query()! query.includeKey("partner") let user = query.getObjectWithId(objectId) as? PFUser if let p = user?["partner"] as? PFUser { return p } return nil } set { pfUser["partner"] = newValue != nil ? newValue : NSNull() } } var pfStatusPointers: [PFObject]? { return pfUser["statuses"] as? [PFObject] } var statuses: [PFStatus]? { if let statusPointers = pfStatusPointers { var statuses = [PFStatus]() for statusPointer in statusPointers { statuses.append(PFStatus(statusId: statusPointer.objectId!)) } return statuses } return [] } func appendStatus(status: PFStatus) { Logger.debug("pfStatusPointers=\(pfStatusPointers)") Logger.debug("pfStatusPointers.count=\(pfStatusPointers?.count)") if let pfPointerStatuses = pfStatusPointers { if MaxSatuses <= pfPointerStatuses.count { if let firstPointer = pfPointerStatuses.first { pfUser.removeObject(firstPointer, forKey: "statuses") pfUser.save() let pfStatus = PFStatus(statusId: firstPointer.objectId!) Logger.debug("RemoveTargetPFObject = \(pfStatus.pfObject!)") pfStatus.pfObject!.delete() } } } Logger.debug("AddTargetPFObject = \(status.pfObject)") pfUser.addObject(status.pfObject!, forKey: "statuses") pfUser.save() } func removeAllStatuses() { Logger.debug("pfStatusPointers=\(pfStatusPointers)") Logger.debug("pfStatusPointers.count=\(pfStatusPointers?.count)") if let pfStatusPointers = pfStatusPointers { if pfStatusPointers.count > 0 { pfUser.removeObjectsInArray(pfStatusPointers, forKey: "statuses") for statusPointer in pfStatusPointers { Logger.debug("remove target statusPointer=\(statusPointer)") let pfStatus = PFStatus(statusId: statusPointer.objectId!) pfStatus.pfObject?.delete() } } } } } class PFMyProfile: PFProfile { } class PFPartner: PFProfile { override var isAuthenticated: Bool { return true } } class PFStatus: PFObjectBase { init(){ super.init(className: "Status") } init(statusId: String) { super.init(className: "Status", objectId: statusId) } var types: StatusTypes? { get { if let type = pfObject?["type"] as? NSInteger { return StatusTypes(rawValue: type) } return nil } set { if let newValue = newValue { pfObject?.setObject(NSNumber(integer: newValue.rawValue), forKey: "type") return } pfObject?.setObject(NSNull(), forKey: "type") } } var date: NSDate? { get { if let date = pfObject?["date"] as? NSDate { return date } return nil } set { if let newValue = newValue { pfObject?.setObject(newValue, forKey: "date") return } pfObject?.setObject(NSNull(), forKey: "date") } } }
gpl-3.0
9ddd7c5fa23ae7991d7a7c1d8d383598
30.040462
89
0.568821
4.542301
false
false
false
false
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/DataSource/Database/JSONCityModelDataSource.swift
1
1842
// // CityModelDataSource.swift // travelMapMvvm // // Created by green on 15/9/18. // Copyright (c) 2015年 travelMapMvvm. All rights reserved. // import Foundation import ReactiveCocoa class JSONCityModelDataSource: CityModelDataSourceProtocol { // MARK: - 单例 class func shareInstance()->CityModelDataSourceProtocol{ struct YRSingleton{ static var predicate:dispatch_once_t = 0 static var instance:JSONCityModelDataSource? = nil } dispatch_once(&YRSingleton.predicate,{ YRSingleton.instance=JSONCityModelDataSource() }) return YRSingleton.instance! } func queryCityListByKeyword(keyword:String) -> RACSignal { return RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(NSEC_PER_SEC * 1)), dispatch_get_main_queue(), { () -> Void in let resultDic = ReadJsonClass.readJsonData("queryCityList") if resultDic.error == nil { if let data: AnyObject=resultDic.data { var list = [CityModel]() list <-- data[kData] subscriber.sendNext(list) subscriber.sendCompleted() } else { subscriber.sendError(ErrorEnum.JSONError.error) } } else { subscriber.sendError(resultDic.error!) } }) return nil }) } }
apache-2.0
96776fd5ee1a6e19f47979ea81ba57ea
30.135593
130
0.490196
5.631902
false
false
false
false
joemcbride/outlander-osx
src/Outlander/Scripting/ScriptContext.swift
1
15628
// // ScriptContext.swift // Scripter // // Created by Joseph McBride on 11/17/14. // Copyright (c) 2014 Joe McBride. All rights reserved. // import Foundation import OysterKit public class Stack<T> { var stack:[T] = [] public func push(item:T) { stack.append(item) } public func pop() -> T { return stack.removeLast() } public func lastItem() -> T? { return stack.last } public func hasItems() -> Bool { return stack.count > 0 } public func count() -> Int { return stack.count } public func clear() { stack.removeAll(keepCapacity: true) } } public struct GosubContext { var label:LabelToken var labelIndex:Int var returnLine:Int var returnIndex:Int var params:[String] var isGosub:Bool var marker:TokenSequence var current:AnyGenerator<Token> } public class ScriptContext { var tree:[Token] var marker:TokenSequence var results:Array<Token> var current:AnyGenerator<Token> var gosubContext:GosubContext? var gosubStack:Stack<GosubContext> var actionVars:[String:String] = [:] var regexVars:[String:String] = [:] private var lastTopIfResult = false private var lastToken:Token? private var variables:[String:String] = [:] private var params:[String] private var paramVars:[String:String] = [:] private var context:GameContext init(_ tree:[Token], context:GameContext, params:[String]) { self.tree = tree self.marker = TokenSequence() self.marker.tree = self.tree self.current = self.marker.generate() self.results = Array<Token>() self.gosubStack = Stack<GosubContext>() self.context = context self.params = params self.updateParamVars() } public func shiftParamVars() -> Bool { var res = false if let _ = self.params.first { self.params.removeAtIndex(0) self.updateParamVars() res = true } return res } private func updateParamVars() { self.paramVars = [:] var all = "" for param in self.params { if param.rangeOfString(" ") != nil { all += " \"\(param)\"" } else { all += " \(param)" } } self.paramVars["0"] = all.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) for (index, param) in self.params.enumerate() { self.paramVars["\(index+1)"] = param } let originalCount = self.params.count let maxArgs = 9 let diff = maxArgs - originalCount if(diff > 0) { let start = maxArgs - diff for index in start..<(maxArgs) { self.paramVars["\(index+1)"] = "" } } self.variables["argcount"] = "\(originalCount)" } public func varsForDisplay() -> [String] { var vars:[String] = [] for (key, value) in self.paramVars { vars.append("\(key): \(value)") } for (key, value) in self.variables { vars.append("\(key): \(value)") } return vars } public func execute() { // seq.currentIdx = 1 for t in marker { evalToken(t) } } public func getParamVar(identifier:String) -> String? { return self.paramVars[identifier] } public func getVariable(identifier:String) -> String? { return self.variables[identifier] } public func setVariable(identifier:String, value:String) { self.variables[identifier] = value } public func removeVariable(identifier:String) { self.variables.removeValueForKey(identifier) } public func localVarsCopy() -> [String:String] { let copy = self.variables return copy } public func gotoLabel(label:String, params:[String], previousLine:Int, isGosub:Bool = false) -> Bool { if isGosub && label.lowercaseString == "clear" { self.gosubStack.clear() return true } let returnIdx = self.marker.currentIdx let seq = TokenSequence() seq.tree = self.tree let cur = seq.generate() var found = false let trimmed = label.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString while let token = cur.next() { if let labelToken = token as? LabelToken where labelToken.characters.lowercaseString == trimmed { found = true if params.count > 0 || isGosub { let gosub = GosubContext( label: labelToken, labelIndex: self.marker.currentIdx, returnLine: previousLine, returnIndex:returnIdx, params: params, isGosub: isGosub, marker: self.marker, current: self.current) self.setRegexVars(params) if isGosub && self.gosubContext != nil && self.gosubContext!.isGosub { self.gosubStack.push(self.gosubContext!) } self.gosubContext = gosub if isGosub { self.gosubStack.push(gosub) } } break } } seq.currentIdx -= 1 if found { self.marker = seq self.current = cur } return found } public func setRegexVars(vars:[String]) { self.regexVars = [:] for (index, param) in vars.enumerate() { self.regexVars["\(index)"] = param } } public func popGosub() -> GosubContext? { if self.gosubStack.hasItems() { let last = self.gosubStack.pop() self.marker = last.marker self.current = last.current self.gosubContext = self.gosubStack.lastItem() return last } return nil } public func roundtime() -> Double? { return self.context.globalVars["roundtime"]?.toDouble() } public func next() -> Token? { let nextToken = self.current.next() if let token = nextToken { evalToken(token) } self.lastToken = nextToken return nextToken } public func evalToken(token:Token) { if(token is BranchToken) { let branchToken = token as! BranchToken if(!evalIf(branchToken)) { let last = self.marker.branchStack.lastItem()! if last.sequence.branchStack.hasItems() { last.sequence.branchStack.pop() } else { self.marker.branchStack.pop() } } } if token is EvalCommandToken { self.evalEvalCommand(token as! EvalCommandToken) } if !(token.name == "whitespace") { self.results.append(token) } } private func evalEvalCommand(token:EvalCommandToken) { let evaluator = ExpressionEvaluator() token.lastResult = evaluator.eval(self, token.expression, self.simplify) } private func evalIf(token:BranchToken) -> Bool { if let count = token.argumentCheck { let result = self.params.count >= count token.lastResult = ExpressionEvalResult( result:EvalResult.Boolean(val:result), info:"\(self.params.count) >= \(count) = \(result)", matchGroups: nil) return result } let lastBranchToken = self.lastToken as? BranchToken var lastBranchResult = false if let lastBToken = lastBranchToken { lastBranchResult = getBoolResult(lastBToken.lastResult?.result) } let evaluator = ExpressionEvaluator() if token.name == "if" && token.expression.count > 0 { let res = evaluator.eval(self, token.expression, self.simplify) token.lastResult = res lastTopIfResult = getBoolResult(res.result) if let groups = res.matchGroups { self.regexVars = [:] for (index, param) in groups.enumerate() { self.regexVars["\(index)"] = param } } return lastTopIfResult } else if token.name == "elseif" && !lastTopIfResult && lastBranchToken != nil && !lastBranchResult { if token.expression.count > 0 { let res = evaluator.eval(self, token.expression, self.simplify) token.lastResult = res if let groups = res.matchGroups { self.regexVars = [:] for (index, param) in groups.enumerate() { self.regexVars["\(index)"] = param } } return getBoolResult(res.result) } token.lastResult = ExpressionEvalResult(result:EvalResult.Boolean(val: true), info:"true", matchGroups:nil) return true } token.lastResult = ExpressionEvalResult(result:EvalResult.Boolean(val: false), info:"false", matchGroups:nil) return false } public func getBoolResult(result:EvalResult?) -> Bool { if result == nil { return false } switch(result!) { case .Boolean(let x): return x default: return false } } public func simplify(data:String) -> String { return VariableReplacer2() .simplify( data, self.context.globalVars, self.regexVars, self.actionVars, self.variables, self.paramVars ) } public func simplify(tokens:Array<Token>) -> String { var text = "" for t in tokens { if t.name == "quoted-string" { let res = self.simplify(t.characters) text += "\"\(res)\"" } else if let idx = t as? IndexerToken { let replaced = self.simplify(idx.variable) var options = replaced.componentsSeparatedByString("|") let indexer = Int(self.simplify(idx.indexer)) ?? -1 if indexer > -1 && options.count > indexer { text += options[indexer] } else { text += replaced } } else { text += t.characters } } return self.simplify(text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) } public func simplifyEach(tokens:Array<Token>) -> String { var result = "" for t in tokens { if t is WhiteSpaceToken { result += t.characters } else if t.name == "quoted-string" { let res = self.simplify(t.characters) result += "\"\(res)\"" } else if let idx = t as? IndexerToken { let replaced = self.simplify(idx.variable) var options = replaced.componentsSeparatedByString("|") let indexer = Int(self.simplify(idx.indexer)) ?? -1 if indexer > -1 && options.count > indexer { result += options[indexer] } else { result += replaced } } else { result += self.simplify(t.characters) } } return result } } struct BranchContext { var sequence:BranchTokenSequence var generator:AnyGenerator<Token> } class TokenSequence : SequenceType { var tree:[Token] var currentIdx:Int var branchStack:Stack<BranchContext> init () { currentIdx = -1 tree = [Token]() branchStack = Stack<BranchContext>() } func generate() -> AnyGenerator<Token> { return AnyGenerator(body: { if let b = self.branchStack.lastItem() { if let next = b.generator.next() { return next } else { self.branchStack.pop() } } let bodyToken = self.getNext() if let nextToken = bodyToken { if let branchToken = nextToken as? BranchToken { let seq = BranchTokenSequence(branchToken) let generator = seq.generate() self.branchStack.push(BranchContext(sequence: seq, generator: generator)) } return nextToken } else { return .None } }) } func getNext() -> Token? { var token:Token? self.currentIdx += 1 if(self.currentIdx > -1 && self.currentIdx < self.tree.count) { token = self.tree[self.currentIdx] } if let _ = token as? WhiteSpaceToken { token = getNext() } return token } } class BranchTokenSequence : SequenceType { var token:BranchToken var branchStack:Stack<BranchContext> var currentIndex:Int init (_ token:BranchToken) { self.token = token currentIndex = -1 branchStack = Stack<BranchContext>() } func generate() -> AnyGenerator<Token> { return AnyGenerator<Token>(body: { if let b = self.branchStack.lastItem() { if let next = b.generator.next() { return next } else { self.branchStack.pop() } } let bodyToken = self.getNext() if let nextToken = bodyToken { if let branchToken = nextToken as? BranchToken { let seq = BranchTokenSequence(branchToken) let generator = seq.generate() self.branchStack.push(BranchContext(sequence: seq, generator: generator)) return branchToken } return nextToken } else { return .None } }) } func getNext() -> Token? { var token:Token? self.currentIndex += 1 if(self.currentIndex < self.token.body.count) { token = self.token.body[self.currentIndex] } if let _ = token as? WhiteSpaceToken { token = getNext() } return token } }
mit
5b8f9e3b7d49748db55348cc986b368c
27.622711
119
0.496353
4.973902
false
false
false
false
loufranco/EventOMat
EventOMat/Views/HomeViewController.swift
1
1893
// // HomeViewController.swift // EventOMat // // Created by Louis Franco on 2/11/17. // Copyright © 2017 Lou Franco. All rights reserved. // import UIKit import SafariServices class HomeViewController: UIViewController { @IBOutlet var tableView: UITableView! // These are used by the table data source to configure cells. var cells: CellViewable! override func viewDidLoad() { super.viewDidLoad() cells = CellViewable(viewController: self, cells: [[ .largeText(text: "March 18th - 19th 2017"), .navigation(text: "Register", imageName: "icon-tickets", navigate: { [weak self] in let ticketSite = SFSafariViewController(url: URL(string: "https://ti.to/nerd/nerd-summit-2017")!) self?.present(ticketSite, animated: true, completion: nil) }), .navigation(text: "Location", imageName: "icon-location", navigate: { [weak self] in self?.performSegue(withIdentifier: "Location", sender: self) }), .navigation(text: "Schedule", imageName: "icon-schedule", navigate: { [weak self] in self?.performSegue(withIdentifier: "Schedule", sender: self) }), .navigation(text: "About us", imageName: "icon-about", navigate: { [weak self] in self?.performSegue(withIdentifier: "About", sender: self) }),]]) self.tableView.dataSource = cells self.tableView.delegate = cells } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = true } @IBAction func onTapCredits(_ sender: Any) { let credits = SFSafariViewController(url: URL(string: "http://loufranco.com/nerdsummit")!) self.present(credits, animated: true, completion: nil) } }
mit
03a3550045601ec6efa63880649b2ba2
36.098039
113
0.628964
4.430913
false
false
false
false
qihuang2/Game3
Game3/Scenes/TimeAttack.swift
1
11102
// // TimeAttack.swift // Game2 // // Created by Qi Feng Huang on 8/4/15. // Copyright (c) 2015 Qi Feng Huang. All rights reserved. // import SpriteKit class TimeAttack: GameScene { static var currentScore:Int = 0 private let currentTimeLabel:SKLabelNode = SKLabelNode(fontNamed: GAME_CONSTANTS.GAME_FONT!.fontName) private static var startingBestScore:Int = GAME_CONSTANTS.GAME_SCORE_KEEPER.getTimeAttackLevelsCompleted() static var timeLeft:Int = 25 init(size: CGSize) { TimeAttack.currentScore = 0 TimeAttack.timeLeft = 25 //25 seconds to beat level TimeAttack.changeInTime = -0.2 //give player a little time to adjust TimeAttack.startingBestScore = GAME_CONSTANTS.GAME_SCORE_KEEPER.getTimeAttackLevelsCompleted() super.init(size: size, level: Int(arc4random_uniform(26)+2)) } override init(size: CGSize, level: Int) { super.init(size: size, level: level) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - SETUP SCORE HUD override func setUpScoreHUD() { let retryButton: SKNode = buttonLayer.childNodeWithName("retry")! currentTimeLabel.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center currentTimeLabel.text = String(TimeAttack.timeLeft) currentTimeLabel.fontSize = (85) currentTimeLabel.setScale(SCALE_CONSTANT) currentTimeLabel.fontColor = COLORS_USED.RED currentTimeLabel.position = CGPoint(x: self.size.width * 0.5, y: retryButton.position.y - retryButton.frame.height * 0.8) scoreHUD.addChild(currentTimeLabel) let bestScoreLabel = SKLabelNode(fontNamed: GAME_CONSTANTS.GAME_FONT!.fontName) bestScoreLabel.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center bestScoreLabel.text = "\(TimeAttack.startingBestScore)" bestScoreLabel.fontSize = (60) bestScoreLabel.setScale(SCALE_CONSTANT) bestScoreLabel.fontColor = COLORS_USED.BLUE bestScoreLabel.position = CGPoint(x: currentTimeLabel.position.x + 2 * currentTimeLabel.frame.size.width, y: currentTimeLabel.position.y) scoreHUD.addChild(bestScoreLabel) let currScoreLabel = SKLabelNode(fontNamed: GAME_CONSTANTS.GAME_FONT!.fontName) currScoreLabel.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center currScoreLabel.text = "\(TimeAttack.currentScore)" currScoreLabel.fontSize = (60) currScoreLabel.setScale(SCALE_CONSTANT) currScoreLabel.fontColor = COLORS_USED.GREEN currScoreLabel.position = CGPoint(x: currentTimeLabel.position.x - 2 * currentTimeLabel.frame.size.width, y: currentTimeLabel.position.y) scoreHUD.addChild(currScoreLabel) } //back and retry buttons override func setUpInGameButtons(){ let retryButton = TouchesMovedButton(buttonTexture: textureAtlas.textureNamed("retry"), sceneFunction: restartGame) let backButton = TouchesMovedButton(buttonTexture: textureAtlas.textureNamed("back"), sceneFunction: mainMenu) backButton.position = CGPoint(x: self.size.width * 0.15, y: self.size.height * 0.92) backButton.setScale(SCALE_CONSTANT*0.65) retryButton.position = CGPoint(x: self.size.width * 0.85, y: backButton.position.y) retryButton.setScale(SCALE_CONSTANT*0.65) retryButton.name = "retry" buttonLayer.addChild(backButton) buttonLayer.addChild(retryButton) } //MARK: - UPDATE FUNCTIONS; CHECK WIN OR LOSE //ticks the clock down private var startTime:NSTimeInterval! static var changeInTime:NSTimeInterval = 0 override func update(currentTime: NSTimeInterval) { if getGameState() == .Playing{ //out of time if TimeAttack.timeLeft == 0{ changeToLoseState() runGameplayStopped() if GAME_CONSTANTS.gameSoundEffectOn { self.runAction(GameScene.POP_SOUND) } } //still playing else { if startTime == nil { startTime = currentTime } else { //if change in time greater than 1, decrement time TimeAttack.changeInTime += (currentTime - startTime) startTime = currentTime if TimeAttack.changeInTime >= 1 { TimeAttack.changeInTime = 0 currentTimeLabel.text = String(--TimeAttack.timeLeft) } } if didWin(){ //go to new scene winAction() } else if didLose(){ //restart current level restartGame() } } } } //presents next level private func winAction(){ changeToWinState() TimeAttack.timeLeft += (Int(currentLevel / 27) + 1) * 8 //add time depending on difficulty checkBestScore() //saves new best if new record achieved let currScene = self.scene! currScene.removeFromParent() let trans = SKTransition.moveInWithDirection(SKTransitionDirection.Down, duration: 0.5) let newScene = TimeAttack(size: self.size,level: getNextLevel()) newScene.scaleMode = .AspectFill view!.presentScene(newScene, transition: trans) } //saves score if new record achieved private func checkBestScore(){ if ++TimeAttack.currentScore > GAME_CONSTANTS.GAME_SCORE_KEEPER.getTimeAttackLevelsCompleted() { GAME_CONSTANTS.GAME_SCORE_KEEPER.incrementTimeAttackLevelsCompleted() SaveHighScore().archiveHighScore(scoreKeeper: GAME_CONSTANTS.GAME_SCORE_KEEPER) reportScoreToHighScore() } } //make level harder as player progresses private func getNextLevel()->Int{ let levelConstant:UInt32 if TimeAttack.currentScore > 12{ levelConstant = 174 } else if TimeAttack.currentScore > 9{ levelConstant = 149 } else if TimeAttack.currentScore > 6{ levelConstant = 99 } else if TimeAttack.currentScore > 4{ levelConstant = 74 } else if TimeAttack.currentScore > 2{ levelConstant = 49 } else{ levelConstant = 24 } return Int(arc4random_uniform(levelConstant)) + 2 } //MARK: - GAMEPLAY STOPPED FUNCTIONS //set up scene for when game ends override func setUpGameplayStoppedHUD() { gameplayStoppedTextTop.position = CGPoint(x: self.size.width * 0.5 , y: self.size.height * 0.75) gameplayStoppedTextTop.fontSize = (self.size.height / 20) gameplayStoppedTextTop.fontColor = COLORS_USED.RED gameplayStoppedTextBottom.fontSize = (gameplayStoppedTextTop.fontSize * 2) gameplayStoppedTextBottom.fontColor = COLORS_USED.BLACK gameplayStoppedHUD.addChild(gameplayStoppedTextBottom) gameplayStoppedHUD.addChild(gameplayStoppedTextTop) gameplayStoppedHUD.zPosition = 200 gameplayStoppedHUD.addChild(stoppedButtonLayer) stoppedButtonLayer.zPosition = 300 } //run game over override func runGameplayStopped(){ setUpLoseScene() gameplayStoppedTextTop.text = TimeAttack.currentScore > TimeAttack.startingBestScore ? "NEW BEST" : "Best : \(TimeAttack.startingBestScore)" gameplayStoppedTextBottom.position = CGPoint(x: gameplayStoppedTextTop.position.x, y: (gameplayStoppedTextTop.position.y - 3 * gameplayStoppedTextTop.frame.height)) gameplayStoppedTextBottom.text = "\(TimeAttack.currentScore)" gameplayStoppedHUD.alpha = 0 setUpGameOverButtons() self.addChild(gameplayStoppedHUD) gameplayStoppedHUD.runAction(SKAction.fadeInWithDuration(0.5)) setScreenShot() } private func setUpLoseScene(){ fadeGameLayer() removeButtonLayer() scoreHUD.removeFromParent() } //game ended buttons override func setUpGameOverButtons(){ let stoppedAtlas = SKTextureAtlas(named: "gameOverButtons") let retryLevelButton = TouchesMovedButton(buttonTexture: stoppedAtlas.textureNamed("retry1"), sceneFunction: startNewGame) retryLevelButton.setScale(SCALE_CONSTANT*1.5) retryLevelButton.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 0.3) stoppedButtonLayer.addChild(retryLevelButton) let mainMenuButton = TouchesMovedButton(buttonTexture: stoppedAtlas.textureNamed("home1"), sceneFunction: mainMenu) mainMenuButton.setScale(SCALE_CONSTANT*1.5) mainMenuButton.position = CGPoint(x: retryLevelButton.position.x + retryLevelButton.size.width / 2 - mainMenuButton.size.width / 2 , y: retryLevelButton.position.y + retryLevelButton.size.height * 1.1) stoppedButtonLayer.addChild(mainMenuButton) let controller = self.view!.window!.rootViewController as! GameViewController let shareButton = TouchesMovedButton(buttonTexture: stoppedAtlas.textureNamed("share1"), sceneFunction: {controller.shareButtonPressed(self.getGameScreenShot())}) shareButton.setScale(SCALE_CONSTANT * 1.5) shareButton.position = CGPoint(x: mainMenuButton.position.x - retryLevelButton.size.width / 2, y: mainMenuButton.position.y) stoppedButtonLayer.addChild(shareButton) } //retry the level; more time available override func restartGame() { changeToLoseState() let currScene = self.scene! currScene.removeFromParent() let trans = SKTransition.crossFadeWithDuration(0.4) let newScene = TimeAttack(size: self.size, level: self.currentLevel) newScene.scaleMode = .AspectFill if GAME_CONSTANTS.gameSoundEffectOn { self.runAction(GameScene.POP_SOUND) } view!.presentScene(newScene, transition: trans) } //restart game from beginning func startNewGame(){ let currScene = self.scene! currScene.removeFromParent() let trans = SKTransition.moveInWithDirection(SKTransitionDirection.Down, duration: 0.75) let newScene = TimeAttack(size: self.size) newScene.scaleMode = .AspectFill view!.presentScene(newScene, transition: trans) } //MARK: - PAUSE UNPAUSE GAMES //used when game paused so change in time gets corrected private func resetStartTime(){ if startTime != nil{ self.startTime = nil } } override func pauseGame() { super.pauseGame() resetStartTime() } }
mit
1223436614ae5c2122fd8be1b093a215
39.083032
209
0.644749
4.614298
false
false
false
false
wangdenkun/IOS_ZouSiQi
Chess.swift
1
478
// // Chess.swift // ZouSiQi // // Created by wdk on 15/7/13. // Copyright (c) 2015年 wdk. All rights reserved. // import Foundation import UIKit class Chess: NSObject { //那一方 var standPoint:String = "" //是否存在 var state:Bool = true //计算值 var value:Int = 0 init(standPoint : String,state : Bool,value : Int) { self.standPoint = standPoint self.state = state self.value = value } }
apache-2.0
693b6a25ae78ff69f8a316df739a087a
17.24
56
0.574561
3.257143
false
false
false
false
neoneye/SwiftyFORM
Source/FormItems/PrecisionSliderFormItem.swift
1
5738
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit /** # Inline precision slider ### Tap to expand/collapse ### Pinch to zoom for better precision ### Double-tap for zoom ### two-finger double-tap for unzoom Behind the scenes this creates a `PrecisionSlider`. This is not a standard Apple control. Please contact Simon Strandgaard if you have questions regarding it. */ public class PrecisionSliderFormItem: FormItem, CustomizableLabel { override func accept(visitor: FormItemVisitor) { visitor.visit(object: self) } public enum Style { /// User can use a pinch gesture to zoom in/out. case standard /// Always fully zoomed in, shows true values on the markers case simple } public var title: String = "" public var titleFont: UIFont = .preferredFont(forTextStyle: .body) public var titleTextColor: UIColor = Colors.text public var detailFont: UIFont = .preferredFont(forTextStyle: .body) public var detailTextColor: UIColor = Colors.secondaryText public var style: Style = .standard /** ## Prefix This is the prefix that appears before the precision number for associating semantics. e.g. "People: " -> People: 23 */ public var prefix = "" @discardableResult public func prefix(_ prefix: String) -> Self { self.prefix = prefix return self } /** ## Suffix This is the suffix that appears after the precision number, useful for apportioning a quantity to a value. e.g. " potatoes" -> 3.4 potatoes */ public var suffix = "" @discardableResult public func suffix(_ suffix: String) -> Self { self.suffix = suffix return self } /** ### Collapsed When the `behavior` is set to `Collapsed` then the precision slider starts out being hidden. The user has to tap the row to expand it. This will collapse other inline precision sliders that has `collapseWhenResigning=true`. This will not affect other inline precison sliders where `collapseWhenResigning=false`. ### Expanded When the `behavior` is set to `Expanded` then the precision slider starts out being visible. The user has to tap the row to collapse it. Also if `collapseWhenResigning=true` and another control becomes first respond then this will collapse it. When the keyboard appears this will collapse it. ### ExpandedAlways When the `behavior` is set to `ExpandedAlways` then the precision slider is always expanded. It cannot be collapsed. It is not affected by `becomeFirstResponder()` nor `resignFirstResponder()`. */ public enum Behavior { case collapsed case expanded case expandedAlways } public var behavior = Behavior.collapsed @discardableResult public func behavior(_ behavior: Behavior) -> Self { self.behavior = behavior return self } public var collapseWhenResigning = false @discardableResult public func shouldCollapseWhenResigning() -> Self { self.collapseWhenResigning = true return self } /** # Initial zoom factor Automatically determines the best zoom when `initialZoom` is nil When zoom is 0 that means no-zoom When zoom is +1 that means zoom-in x10 When zoom is -1 that means zoom-out x10 When zoom is +2 that means zoom-in x100 When zoom is -2 that means zoom-out x100 The zoom range is from -5 to +5. */ public var initialZoom: Float? { willSet { if let zoom = newValue { assert(zoom >= -10, "initialZoom is far outside the zoom-range") assert(zoom <= 10, "initialZoom is far outside the zoom-range") } } } @discardableResult public func initialZoom(_ initialZoom: Float) -> Self { self.initialZoom = initialZoom return self } /** # Number of decimal places The number can go from 0 to +5. */ public var decimalPlaces: UInt = 3 { willSet { assert(newValue <= 10, "PrecisionSlider cannot handle so many decimalPlaces. Too big a number.") } } @discardableResult public func decimalPlaces(_ decimalPlaces: UInt) -> Self { self.decimalPlaces = decimalPlaces return self } public var minimumValue: Int = 0 @discardableResult public func minimumValue(_ minimumValue: Int) -> Self { self.minimumValue = minimumValue return self } public var maximumValue: Int = 1000 @discardableResult public func maximumValue(_ maximumValue: Int) -> Self { self.maximumValue = maximumValue return self } public var zoomUI = false @discardableResult public func enableZoomUI() -> Self { self.zoomUI = true return self } typealias SyncBlock = (_ value: Int) -> Void var syncCellWithValue: SyncBlock = { (value: Int) in SwiftyFormLog("sync is not overridden") } internal var innerValue: Int = 0 public var value: Int { get { self.innerValue } set { self.updateValue(newValue) } } @discardableResult public func value(_ value: Int) -> Self { updateValue(value) return self } public func updateValue(_ value: Int) { innerValue = value syncCellWithValue(value) } public var actualValue: Double { let decimalScale: Double = pow(Double(10), Double(decimalPlaces)) return Double(innerValue) / decimalScale } public struct SliderDidChangeModel { public let value: Int public let valueUpdated: Bool public let zoom: Float public let zoomUpdated: Bool } public typealias SliderDidChangeBlock = (_ changeModel: SliderDidChangeModel) -> Void public var sliderDidChangeBlock: SliderDidChangeBlock = { (changeModel: SliderDidChangeModel) in SwiftyFormLog("not overridden") } public func sliderDidChange(_ changeModel: SliderDidChangeModel) { innerValue = changeModel.value sliderDidChangeBlock(changeModel) } }
mit
005a1995b3f23bb2755fbc01c8db77a1
23.417021
111
0.707389
3.927447
false
false
false
false
VincenzoFreeman/CATransition
CATransition/Classes/PhotoBrowser/PhotoBrowserCell.swift
1
1916
// // PhotoBrowserCell.swift // CATransition // // Created by wenzhiji on 16/4/28. // Copyright © 2016年 Manager. All rights reserved. // import UIKit import SDWebImage class PhotoBrowserCell: UICollectionViewCell { // MARK:- 懒加载属性 lazy var imageView = UIImageView() // 定义模型属性 var shop : ShopItem? { didSet { // nil校验 guard let urlString = shop?.q_pic_url else { return } // 获得小图 var smallImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString) // 如果没有小图就为占位图片 if smallImage == nil { smallImage = UIImage(named: "empty_picture") } // 计算ImageView的frame imageView.frame = calculateFrame(smallImage) // 设置大图 guard let bigImageString = shop?.z_pic_url else{ return } imageView.sd_setImageWithURL(NSURL(string: bigImageString), placeholderImage: smallImage, options: .RetryFailed) { (image , error, type, url) -> Void in self.imageView.frame = self.calculateFrame(image) } } } override init(frame: CGRect) { super.init(frame: frame) // 添加子控件 contentView.addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PhotoBrowserCell{ func calculateFrame(image : UIImage) -> CGRect{ // 计算imageView的frame let x : CGFloat = 0 let width = UIScreen.mainScreen().bounds.width let height = width / image.size.width * image.size.height let y = (UIScreen.mainScreen().bounds.height - height) * 0.5 return CGRectMake(x, y, width, height) } }
mit
b3c9f7c953769337ab6acc8f957918aa
29.932203
164
0.586849
4.551122
false
false
false
false
ReactiveKit/Bond
Playground-iOS.playground/Pages/UITableView+Signal+Diff.xcplaygroundpage/Contents.swift
1
1018
//: [Previous](@previous) ///: Before running the playground, make sure to build "Bond-iOS" and "PlaygroundSupport" ///: targets with any iOS Simulator as a destination. import Foundation import PlaygroundSupport import UIKit import Bond import ReactiveKit let tableView = UITableView() tableView.frame.size = CGSize(width: 300, height: 300) // Note: Open the assistant editor to see the table view PlaygroundPage.current.liveView = tableView PlaygroundPage.current.needsIndefiniteExecution = true // A signal that emits a value every 1 second let pulse = SafeSignal(sequence: 0..., interval: 1) // A signal of [String] let data = SafeSignal(sequence: [ ["A"], ["A", "B", "C"], ["A", "C"], ["C", "A"] ]) .zip(with: pulse) { data, _ in data } // add 1 second delay between events .diff() // diff each new array against the previous one data.bind(to: tableView, cellType: UITableViewCell.self) { (cell, string) in cell.textLabel?.text = string } //: [Next](@next)
mit
f09332a5554e2ea3cfa77f47806baba0
27.277778
89
0.680747
3.870722
false
false
false
false
zgorawski/YetAnotherImageGallery
YetAnotherImageGallery/UI/ImageListViewController.swift
1
2690
// // ImageListViewController.swift // YetAnotherImageGallery // // Created by Zbigniew Górawski on 21/02/2017. // Copyright © 2017 Zbigniew Górawski. All rights reserved. // import UIKit import AlamofireImage class ImageListViewController: UIViewController { // dependency // TODO: make it injectable fileprivate var imageListDataSource : ImageListTableDataSource! fileprivate let imageCache = AutoPurgingImageCache() // model fileprivate var selectedFeed: FlickrFeedItem? // outlets @IBOutlet weak var tableView: UITableView! // consts fileprivate let detailsSegueId = "ImageDetailsSegue" // MARK: IBActions @IBAction func onDateTakenTap(_ sender: UIBarButtonItem) { imageListDataSource.sortBy(.dateTaken) } @IBAction func onDatePublishedTap(_ sender: UIBarButtonItem) { imageListDataSource.sortBy(.datePublished) } } // TODO: move those extensions to sepratate files, if they grow too much // MARK: VC lifecycle extension ImageListViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. imageListDataSource = ImageListTableDataSource(tableView: tableView, imageCache: imageCache) tableView.delegate = self tableView.dataSource = imageListDataSource tableView.tableFooterView = UIView() // common hack to hide extra rows imageListDataSource.refreshData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.isNavigationBarHidden = false } } // MARK: - Navigation extension ImageListViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == detailsSegueId, let selectedFeed = selectedFeed, let vc = segue.destination as? ImageDetailsViewController else { return } vc.selectedFeed = selectedFeed vc.imageCache = imageCache } } extension ImageListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedFeed = imageListDataSource.getFeedItem(indexPath) performSegue(withIdentifier: detailsSegueId, sender: self) tableView.deselectRow(at: indexPath, animated: true) } }
mit
0b2978e75eca23ee2233fd2819169df4
27.284211
100
0.676963
5.450304
false
false
false
false
jeroendesloovere/swifter
SwifterCommon/SwifterTweets.swift
3
14391
// // SwifterTweets.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Swifter { /* GET statuses/retweets/:id Returns up to 100 of the first retweets of a given tweet. */ func getStatusesRetweetsWithID(id: Int, count: Int?, trimUser: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "statuses/retweets/\(id).json" var parameters = Dictionary<String, AnyObject>() if count { parameters["count"] = count! } if trimUser { parameters["trim_user"] = trimUser! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET statuses/show/:id Returns a single Tweet, specified by the id parameter. The Tweet's author will also be embedded within the tweet. See Embeddable Timelines, Embeddable Tweets, and GET statuses/oembed for tools to render Tweets according to Display Requirements. # About Geo If there is no geotag for a status, then there will be an empty <geo/> or "geo" : {}. This can only be populated if the user has used the Geotagging API to send a statuses/update. The JSON response mostly uses conventions laid out in GeoJSON. Unfortunately, the coordinates that Twitter renders are reversed from the GeoJSON specification (GeoJSON specifies a longitude then a latitude, whereas we are currently representing it as a latitude then a longitude). Our JSON renders as: "geo": { "type":"Point", "coordinates":[37.78029, -122.39697] } # Contributors If there are no contributors for a Tweet, then there will be an empty or "contributors" : {}. This field will only be populated if the user has contributors enabled on his or her account -- this is a beta feature that is not yet generally available to all. This object contains an array of user IDs for users who have contributed to this status (an example of a status that has been contributed to is this one). In practice, there is usually only one ID in this array. The JSON renders as such "contributors":[8285392]. */ func getStatusesShowWithID(id: Int, count: Int?, trimUser: Bool?, includeMyRetweet: Bool?, includeEntities: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "statuses/show.json" var parameters = Dictionary<String, AnyObject>() if count { parameters["count"] = count! } if trimUser { parameters["trim_user"] = trimUser! } if includeMyRetweet { parameters["include_my_retweet"] = includeMyRetweet! } if includeEntities { parameters["include_entities"] = includeEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* POST statuses/destroy/:id Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. Returns the destroyed status if successful. */ func postStatusesDestroyWithID(id: Int, trimUser: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "statuses/destroy/\(id).json" var parameters = Dictionary<String, AnyObject>() if trimUser { parameters["trim_user"] = trimUser! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* POST statuses/update Updates the authenticating user's current status, also known as tweeting. To upload an image to accompany the tweet, use POST statuses/update_with_media. For each update attempt, the update text is compared with the authenticating user's recent tweets. Any attempt that would result in duplication will be blocked, resulting in a 403 error. Therefore, a user cannot submit the same status twice in a row. While not rate limited by the API a user is limited in the number of tweets they can create at a time. If the number of updates posted by the user reaches the current allowed limit this method will return an HTTP 403 error. - Any geo-tagging parameters in the update will be ignored if geo_enabled for the user is false (this is the default setting for all users unless the user has enabled geolocation in their settings) - The number of digits passed the decimal separator passed to lat, up to 8, will be tracked so that the lat is returned in a status object it will have the same number of digits after the decimal separator. - Please make sure to use to use a decimal point as the separator (and not the decimal comma) for the latitude and the longitude - usage of the decimal comma will cause the geo-tagged portion of the status update to be dropped. - For JSON, the response mostly uses conventions described in GeoJSON. Unfortunately, the geo object has coordinates that Twitter renderers are reversed from the GeoJSON specification (GeoJSON specifies a longitude then a latitude, whereas we are currently representing it as a latitude then a longitude. Our JSON renders as: "geo": { "type":"Point", "coordinates":[37.78217, -122.40062] } - The coordinates object is replacing the geo object (no deprecation date has been set for the geo object yet) -- the difference is that the coordinates object, in JSON, is now rendered correctly in GeoJSON. - If a place_id is passed into the status update, then that place will be attached to the status. If no place_id was explicitly provided, but latitude and longitude are, we attempt to implicitly provide a place by calling geo/reverse_geocode. - Users will have the ability, from their settings page, to remove all the geotags from all their tweets en masse. Currently we are not doing any automatic scrubbing nor providing a method to remove geotags from individual tweets. See: - https://dev.twitter.com/notifications/multiple-media-entities-in-tweets - https://dev.twitter.com/docs/api/multiple-media-extended-entities */ func postStatusUpdate(status: String, inReplyToStatusID: Int?, lat: Double?, long: Double?, placeID: Double?, displayCoordinates: Bool?, trimUser: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { var path: String = "statuses/update.json" var parameters = Dictionary<String, AnyObject>() parameters["status"] = status if inReplyToStatusID { parameters["in_reply_to_status_id"] = inReplyToStatusID! } if placeID { parameters["place_id"] = placeID! parameters["display_coordinates"] = true } else if lat && long { parameters["lat"] = lat! parameters["long"] = long! parameters["display_coordinates"] = true } if trimUser { parameters["trim_user"] = trimUser! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func postStatusUpdate(status: String, media: NSData, inReplyToStatusID: Int?, lat: Double?, long: Double?, placeID: Double?, displayCoordinates: Bool?, trimUser: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { var path: String = "statuses/update_with_media.json" var parameters = Dictionary<String, AnyObject>() parameters["status"] = status parameters["media[]"] = media parameters[Swifter.DataParameters.dataKey] = "media[]" if inReplyToStatusID { parameters["in_reply_to_status_id"] = inReplyToStatusID! } if placeID { parameters["place_id"] = placeID! parameters["display_coordinates"] = true } else if lat && long { parameters["lat"] = lat! parameters["long"] = long! parameters["display_coordinates"] = true } if trimUser { parameters["trim_user"] = trimUser! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* POST statuses/retweet/:id Retweets a tweet. Returns the original tweet with retweet details embedded. - This method is subject to update limits. A HTTP 403 will be returned if this limit as been hit. - Twitter will ignore attempts to perform duplicate retweets. - The retweet_count will be current as of when the payload is generated and may not reflect the exact count. It is intended as an approximation. Returns Tweets (1: the new tweet) */ func postStatusRetweetWithID(id: Int, trimUser: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "statuses/retweet/\(id).json" var parameters = Dictionary<String, AnyObject>() if trimUser { parameters["trim_user"] = trimUser! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET statuses/oembed Returns information allowing the creation of an embedded representation of a Tweet on third party sites. See the oEmbed specification for information about the response format. While this endpoint allows a bit of customization for the final appearance of the embedded Tweet, be aware that the appearance of the rendered Tweet may change over time to be consistent with Twitter's Display Requirements. Do not rely on any class or id parameters to stay constant in the returned markup. */ func getStatusesOEmbedWithID(id: Int, url: NSURL, maxWidth: Int?, hideMedia: Bool?, hideThread: Bool?, omitScript: Bool?, align: String?, related: String?, lang: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "statuses/oembed" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id parameters["url"] = url if maxWidth { parameters["max_width"] = maxWidth! } if hideMedia { parameters["hide_media"] = hideMedia! } if hideThread { parameters["hide_thread"] = hideThread! } if omitScript { parameters["omit_scipt"] = omitScript! } if align { parameters["align"] = align! } if related { parameters["related"] = related! } if lang { parameters["lang"] = lang! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET statuses/retweeters/ids Returns a collection of up to 100 user IDs belonging to users who have retweeted the tweet specified by the id parameter. This method offers similar data to GET statuses/retweets/:id and replaces API v1's GET statuses/:id/retweeted_by/ids method. */ func getStatusesRetweetersWithID(id: Int, cursor: Int?, stringifyIDs: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "statuses/oembed" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if cursor { parameters["cursor"] = cursor! } if stringifyIDs { parameters["stringify_ids"] = cursor! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET statuses/lookup Returns fully-hydrated tweet objects for up to 100 tweets per request, as specified by comma-separated values passed to the id parameter. This method is especially useful to get the details (hydrate) a collection of Tweet IDs. GET statuses/show/:id is used to retrieve a single tweet object. */ func getStatusesLookupTweetIDs(tweetIDs: Int[], includeEntities: Bool?, map: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "statuses/lookup.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = tweetIDs.bridgeToObjectiveC().componentsJoinedByString(",") if includeEntities { parameters["include_entities"] = includeEntities! } if map { parameters["map"] = map! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } }
mit
87648be87ac0d018bf9db061eb4eba89
49.85159
397
0.685011
4.806613
false
false
false
false
zaneswafford/ProjectEulerSwift
ProjectEuler/Problem13.swift
1
948
// // Problem13.swift // ProjectEuler // // Created by Zane Swafford on 6/29/15. // Copyright (c) 2015 Zane Swafford. All rights reserved. // import Foundation func problem13WithBundle(bundle: NSBundle) -> Int { let numberFilePath = bundle.pathForResource("Problem13", ofType: "txt") if let p = numberFilePath { if let text = String(contentsOfFile: p, encoding: NSUTF8StringEncoding, error: nil) { // The result let numArray = text.componentsSeparatedByString("\n").map({ NSDecimalNumber(string: $0) }) var sum:NSDecimalNumber = 0 for num in numArray { sum = sum.decimalNumberByAdding(num) } let sumChars = Array(sum.stringValue) return String(sumChars[0..<10]).toInt()! } } return -1 } func problem13() -> Int { return problem13WithBundle(NSBundle.mainBundle()) }
bsd-2-clause
3dc0afae9e8feb9c7f84b82c5be300d0
26.114286
102
0.594937
4.348624
false
false
false
false
xiaomudegithub/viossvc
viossvc/Scenes/Chat/ChatInteractionViewController.swift
1
10857
// // ChatInteractionViewController.swift // viossvc // // Created by abx’s mac on 2016/12/1. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import XCGLogger private let sectionHeaderHeight : CGFloat = 50.0 class ChatInteractionViewController: BaseCustomListTableViewController,InputBarViewProcotol,ChatSessionProtocol{ let showTime = 300 @IBOutlet weak var inputBar: InputBarView! @IBOutlet weak var inputBarHeight: NSLayoutConstraint! @IBOutlet weak var inputBarBottom: NSLayoutConstraint! var chatUid:Int = 0 var chatName = "" override func viewDidLoad() { super.viewDidLoad() MobClick.event(AppConst.Event.order_chat) inputBar.registeredDelegate(self) self.title = chatName ChatSessionHelper.shared.openChatSession(self) updateUserInfo() didRequest() settingTableView() } func settingTableView() { tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag tableView.registerClass(ChatSectionView.classForCoder(), forHeaderFooterViewReuseIdentifier: "ChatSectionView") tableView.tableHeaderView = UIView(frame:CGRectMake(0,0,0,0.5)) } override func autoRefreshLoad() -> Bool { return false } private func updateUserInfo() { if chatUid != 0 { AppAPIHelper.userAPI().getUserInfo(chatUid, complete: { [weak self](model) in let userInfo = model as? UserInfoModel if userInfo != nil { self?.title = userInfo!.nickname ChatSessionHelper.shared.didReqeustUserInfoComplete(userInfo!) } }, error:nil) } } func receiveMsg(chatMsgModel: ChatMsgModel) { guard chatMsgModel.from_uid == chatUid || chatMsgModel.from_uid == CurrentUserHelper.shared.userInfo.uid else {return} dataSource?.append(chatMsgModel) tableView.reloadData() tableViewScrolToBottom() } func sessionUid() -> Int { return chatUid } override func didRequest() { let pageSize = 20 let offset = dataSource == nil ? 0 : dataSource!.count var array = ChatMsgHepler.shared.findHistoryMsg(chatUid, offset: offset , pageSize: pageSize) as [AnyObject] if array.count < pageSize { removeRefreshControl() } if dataSource != nil { array.appendContentsOf(dataSource!) } didRequestComplete(array) if offset == 0 { // _tableViewScrolToBottom(false) self.performSelector(#selector(self.tableViewScrolToBottom), withObject: nil, afterDelay: 0.1) } } override func isCalculateCellHeight() -> Bool { return true } override func tableView(tableView: UITableView, cellDataForRowAtIndexPath indexPath: NSIndexPath) -> AnyObject? { var datas:[AnyObject]? = dataSource; return (datas != nil && datas!.count > indexPath.section ) ? datas![indexPath.section] : nil; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return dataSource == nil ? 0 : dataSource!.count } override func tableView(tableView: UITableView, cellIdentifierForRowAtIndexPath indexPath: NSIndexPath) -> String? { let model = self.tableView(tableView, cellDataForRowAtIndexPath: indexPath) as! ChatMsgModel return model.from_uid == CurrentUserHelper.shared.uid ? "ChatWithISayCell" : "ChatWithAnotherSayCell" } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return isTimeToShow(section) ? sectionHeaderHeight : 0.1 } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1 } // func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // view.backgroundColor = UIColor.clearColor() // } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var headerView : ChatSectionView? if isTimeToShow(section) { let model = self.tableView(tableView, cellDataForRowAtIndexPath: NSIndexPath.init(forRow: 0, inSection: section)) as! ChatMsgModel headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("ChatSectionView") as? ChatSectionView headerView?.update(model) } return headerView } func isTimeToShow(index : Int) -> Bool { var isShow = false if dataSource != nil { if index == 0 { isShow = true }else { let currentModel = dataSource![index] as! ChatMsgModel let beforeModel = dataSource![index - 1] as! ChatMsgModel isShow = currentModel.msg_time - beforeModel.msg_time >= showTime } } return isShow } func inputBarDidKeyboardHide(inputBar inputBar: InputBarView, userInfo: [NSObject : AnyObject]?) { let duration = userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue let rawValue = (userInfo![UIKeyboardAnimationCurveUserInfoKey]?.integerValue)! << 16 let curve = UIViewAnimationOptions.init(rawValue: UInt(rawValue)) UIView.animateWithDuration(duration!, delay: 0, options: curve, animations: { [weak self]() in self!.inputBarChangeHeight(-1) }, completion: nil) } func inputBarDidKeyboardShow(inputBar inputBar: InputBarView, userInfo: [NSObject : AnyObject]?) { let height = CGRectGetHeight(userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue()) if (height > 0) { let heightTime = userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval UIView.animateWithDuration(heightTime, animations: { [weak self]() in self!.inputBarChangeHeight(height) }) } } func inputBarDidSendMessage(inputBar inputBar: InputBarView, message: String) { if !message.isEmpty { ChatMsgHepler.shared.sendMsg(chatUid, msg: message) } } func inputBarDidChangeHeight(inputBar inputBar: InputBarView, height: CGFloat) { inputBarHeight.constant = height; self.view.layoutIfNeeded() _tableViewScrolToBottom(true) } func inputBarChangeHeight(height : CGFloat) { inputBarBottom.constant = height self.view.layoutIfNeeded() if height > 0 { _tableViewScrolToBottom(false) } } func tableViewScrolToBottom() { if dataSource?.count > 0 { tableView.scrollToRowAtIndexPath(NSIndexPath.init(forRow: 0, inSection: dataSource!.count - 1), atScrollPosition: UITableViewScrollPosition.Top, animated: false) } } func _tableViewScrolToBottom(animated : Bool? = true){ if dataSource?.count > 0 { tableView.scrollToRowAtIndexPath(NSIndexPath.init(forRow: 0, inSection: dataSource!.count - 1), atScrollPosition: UITableViewScrollPosition.Top, animated: animated!) } } deinit { ChatSessionHelper.shared.closeChatSession() } } class ChatSectionView: UITableViewHeaderFooterView,OEZUpdateProtocol { // var label : UILabel = UILabel() let layerLeft : CALayer = CALayer() let layerRight : CALayer = CALayer() let stringLabel = UILabel.init() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) let color = AppConst.Color.C3 layerLeft.backgroundColor = color.CGColor layerRight.backgroundColor = color.CGColor self.layer.addSublayer(layerLeft) self.layer.addSublayer(layerRight) stringLabel.textAlignment = .Center stringLabel.font = UIFont.SIZE(11) stringLabel.textColor = color stringLabel.frame = CGRectMake(0, 0, UIScreen.width(), sectionHeaderHeight) self.addSubview(stringLabel) } func update(data: AnyObject!) { let model = data as! ChatMsgModel let string = model.formatMsgTime() as NSString stringLabel.text = string as String let strWidth = string.sizeWithAttributes([NSFontAttributeName : UIFont.SIZE(11)]).width let width = UIScreen.width() - 50 - strWidth let layerWidth = width > 120 ? 60 : (width - 20) / 2.0 let startX = (UIScreen.width() - strWidth - 50 - 2 * layerWidth) / 2.0 layerLeft.frame = CGRectMake(startX, (sectionHeaderHeight - 0.5) / 2.0, layerWidth, 0.5) layerRight.frame = CGRectMake(startX + layerWidth + strWidth + 50, (sectionHeaderHeight - 0.5) / 2.0, layerWidth, 0.5) } // init(frame: CGRect,model: ChatMsgModel) { // super.init(reuseIdentifier: "ChatSectionView") // // let label = detailTextLabel! //// self.addSubview(label) // label.textAlignment = .Center // label.font = UIFont.SIZE(11) // label.textColor = AppConst.Color.C3 // let string = model.formatMsgTime() as NSString // // label.text = string as String // // let strWidth = string.sizeWithAttributes([NSFontAttributeName : UIFont.SIZE(11)]).width // let width = UIScreen.width() - 50 - strWidth // let layerWidth = width > 120 ? 60 : (width - 20) / 2.0 // // let layer1 = CALayer() // layer1.backgroundColor = AppConst.Color.C3.CGColor // // let startX = (UIScreen.width() - strWidth - 50 - 2 * layerWidth) / 2.0 // layer1.frame = CGRectMake(startX, (frame.height - 0.5) / 2.0, layerWidth, 0.5) // // let layer2 = CALayer() // layer2.backgroundColor = AppConst.Color.C3.CGColor // // layer2.frame = CGRectMake(startX + layerWidth + strWidth + 50, (frame.height - 0.5) / 2.0, layerWidth, 0.5) // // self.layer.addSublayer(layer1) // self.layer.addSublayer(layer2) // // // } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
3e7c93c6ea192640faeb19882bc36eca
32.597523
177
0.61408
4.875112
false
false
false
false
alessiobrozzi/firefox-ios
Client/Frontend/Browser/FaviconManager.swift
2
6517
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared import Storage import WebImage import Deferred import Sync class FaviconManager: TabHelper { static let FaviconDidLoad = "FaviconManagerFaviconDidLoad" let profile: Profile! weak var tab: Tab? static let maximumFaviconSize = 1 * 1024 * 1024 // 1 MiB file size limit init(tab: Tab, profile: Profile) { self.profile = profile self.tab = tab if let path = Bundle.main.path(forResource: "Favicons", ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } } class func name() -> String { return "FaviconsManager" } func scriptMessageHandlerName() -> String? { return "faviconsMessageHandler" } fileprivate func loadFavicons(_ tab: Tab, profile: Profile, favicons: [Favicon]) -> Deferred<Maybe<[Favicon]>> { var deferreds: [() -> Deferred<Maybe<Favicon>>] deferreds = favicons.map { favicon in return { [weak tab] () -> Deferred<Maybe<Favicon>> in if let tab = tab, let url = URL(string: favicon.url), let currentURL = tab.url { return self.getFavicon(tab, iconUrl: url, currentURL: currentURL, icon: favicon, profile: profile) } else { return deferMaybe(FaviconError()) } } } return accumulate(deferreds) } func getFavicon(_ tab: Tab, iconUrl: URL, currentURL: URL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> { let deferred = Deferred<Maybe<Favicon>>() let manager = SDWebImageManager.shared() let options = tab.isPrivate ? [SDWebImageOptions.lowPriority, SDWebImageOptions.cacheMemoryOnly] : [SDWebImageOptions.lowPriority] let url = currentURL.absoluteString let site = Site(url: url, title: "") var fetch: SDWebImageOperation? fetch = manager?.downloadImage(with: iconUrl, options: SDWebImageOptions(options), progress: { (receivedSize, expectedSize) in if receivedSize > FaviconManager.maximumFaviconSize || expectedSize > FaviconManager.maximumFaviconSize { fetch?.cancel() } }, completed: { (img, err, cacheType, success, url) -> Void in let fav = Favicon(url: url!.absoluteString, date: Date(), type: icon.type) guard let img = img else { deferred.fill(Maybe(failure: FaviconError())) return } fav.width = Int(img.size.width) fav.height = Int(img.size.height) if !tab.isPrivate { if tab.favicons.isEmpty { self.makeFaviconAvailable(tab, atURL: currentURL, favicon: fav, withImage: img) } tab.favicons.append(fav) self.profile.favicons.addFavicon(fav, forSite: site).upon { _ in deferred.fill(Maybe(success: fav)) } } else { tab.favicons.append(fav) deferred.fill(Maybe(success: fav)) } }) return deferred } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { self.tab?.favicons.removeAll(keepingCapacity: false) if let tab = self.tab, let currentURL = tab.url { var favicons = [Favicon]() if let icons = message.body as? [String: Int] { for icon in icons { if let _ = URL(string: icon.0), let iconType = IconType(rawValue: icon.1) { let favicon = Favicon(url: icon.0, date: Date(), type: iconType) favicons.append(favicon) } } } loadFavicons(tab, profile: profile, favicons: favicons).uponQueue(DispatchQueue.main) { result in if let result = result.successValue { let faviconsReadOnly = favicons if result.count == 1 && faviconsReadOnly[0].type == .guess { // No favicon is indicated in the HTML self.noFaviconAvailable(tab, atURL: currentURL as URL) } } NotificationCenter.default.post(name: NSNotification.Name(rawValue: FaviconManager.FaviconDidLoad), object: tab) } } } func makeFaviconAvailable(_ tab: Tab, atURL url: URL, favicon: Favicon, withImage image: UIImage) { let helper = tab.getHelper(name: "SpotlightHelper") as? SpotlightHelper helper?.updateImage(image, forURL: url) } func noFaviconAvailable(_ tab: Tab, atURL url: URL) { let helper = tab.getHelper(name: "SpotlightHelper") as? SpotlightHelper helper?.updateImage(forURL: url) } } class FaviconError: MaybeErrorType { internal var description: String { return "No Image Loaded" } }
mpl-2.0
950a34466479d4e8da0c9b7c8926ce3e
45.219858
145
0.508209
5.701662
false
false
false
false
mshhmzh/firefox-ios
Client/Frontend/Widgets/SnackBar.swift
2
10396
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit import Shared class SnackBarUX { static var MaxWidth: CGFloat = 400 } /** * A specialized version of UIButton for use in SnackBars. These are displayed evenly * spaced in the bottom of the bar. The main convenience of these is that you can pass * in a callback in the constructor (although these also style themselves appropriately). * *``SnackButton(title: "OK", { _ in print("OK", terminator: "\n") })`` */ class SnackButton : UIButton { let callback: (bar: SnackBar) -> Void private var bar: SnackBar! /** * An image to show as the background when a button is pressed. This is currently a 1x1 pixel blue color */ lazy var highlightImg: UIImage = { let size = CGSize(width: 1, height: 1) return UIImage.createWithColor(size, color: UIConstants.HighlightColor) }() init(title: String, accessibilityIdentifier: String, callback: (bar: SnackBar) -> Void) { self.callback = callback super.init(frame: CGRectZero) setTitle(title, forState: .Normal) titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultMediumFont setBackgroundImage(highlightImg, forState: .Highlighted) setTitleColor(UIConstants.HighlightText, forState: .Highlighted) addTarget(self, action: #selector(SnackButton.onClick), forControlEvents: .TouchUpInside) self.accessibilityIdentifier = accessibilityIdentifier } override init(frame: CGRect) { self.callback = { bar in } super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func onClick() { callback(bar: bar) } } /** * Presents some information to the user. Can optionally include some buttons and an image. Usage: * * ``let bar = SnackBar(text: "This is some text in the snackbar.", * img: UIImage(named: "bookmark"), * buttons: [ * SnackButton(title: "OK", { _ in print("OK", terminator: "\n") }), * SnackButton(title: "Cancel", { _ in print("Cancel", terminator: "\n") }), * SnackButton(title: "Maybe", { _ in print("Maybe", terminator: "\n") }) * ] * )`` */ class SnackBar: UIView { let imageView: UIImageView let textLabel: UILabel let contentView: UIView let backgroundView: UIView let buttonsView: Toolbar private var buttons = [SnackButton]() // The Constraint for the bottom of this snackbar. We use this to transition it var bottom: Constraint? convenience init(text: String, img: UIImage?, buttons: [SnackButton]?) { var attributes = [String: AnyObject]() attributes[NSFontAttributeName] = DynamicFontHelper.defaultHelper.DefaultMediumFont attributes[NSBackgroundColorAttributeName] = UIColor.clearColor() let attrText = NSAttributedString(string: text, attributes: attributes) self.init(attrText: attrText, img: img, buttons: buttons) } init(attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) { imageView = UIImageView() textLabel = UILabel() contentView = UIView() buttonsView = Toolbar() backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) super.init(frame: CGRectZero) imageView.image = img textLabel.attributedText = attrText if let buttons = buttons { for button in buttons { addButton(button) } } setup() } private override init(frame: CGRect) { imageView = UIImageView() textLabel = UILabel() contentView = UIView() buttonsView = Toolbar() backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) super.init(frame: frame) } private func setup() { textLabel.backgroundColor = nil addSubview(backgroundView) addSubview(contentView) contentView.addSubview(imageView) contentView.addSubview(textLabel) addSubview(buttonsView) self.backgroundColor = UIColor.clearColor() buttonsView.drawTopBorder = true buttonsView.drawBottomBorder = false buttonsView.drawSeperators = true imageView.contentMode = UIViewContentMode.Left textLabel.font = DynamicFontHelper.defaultHelper.DefaultMediumFont textLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping textLabel.numberOfLines = 0 textLabel.backgroundColor = UIColor.clearColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let imageWidth: CGFloat if let img = imageView.image { imageWidth = img.size.width + UIConstants.DefaultPadding * 2 } else { imageWidth = 0 } self.textLabel.preferredMaxLayoutWidth = contentView.frame.width - (imageWidth + UIConstants.DefaultPadding) super.layoutSubviews() } private func drawLine(context: CGContextRef, start: CGPoint, end: CGPoint) { CGContextSetStrokeColorWithColor(context, UIConstants.BorderColor.CGColor) CGContextSetLineWidth(context, 1) CGContextMoveToPoint(context, start.x, start.y) CGContextAddLineToPoint(context, end.x, end.y) CGContextStrokePath(context) } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() drawLine(context!, start: CGPoint(x: 0, y: 1), end: CGPoint(x: frame.size.width, y: 1)) } /** * Called to check if the snackbar should be removed or not. By default, Snackbars persist forever. * Override this class or use a class like CountdownSnackbar if you want things expire * - returns: true if the snackbar should be kept alive */ func shouldPersist(tab: Tab) -> Bool { return true } override func updateConstraints() { super.updateConstraints() backgroundView.snp_remakeConstraints { make in make.bottom.left.right.equalTo(self) // Offset it by the width of the top border line so we can see the line from the super view make.top.equalTo(self).offset(1) } contentView.snp_remakeConstraints { make in make.top.left.right.equalTo(self).inset(EdgeInsetsMake(UIConstants.DefaultPadding, left: UIConstants.DefaultPadding, bottom: UIConstants.DefaultPadding, right: UIConstants.DefaultPadding)) } if let img = imageView.image { imageView.snp_remakeConstraints { make in make.left.centerY.equalTo(contentView) // To avoid doubling the padding, the textview doesn't have an inset on its left side. // Instead, it relies on the imageView to tell it where its left side should be. make.width.equalTo(img.size.width + UIConstants.DefaultPadding) make.height.equalTo(img.size.height + UIConstants.DefaultPadding) } } else { imageView.snp_remakeConstraints { make in make.width.height.equalTo(0) make.top.left.equalTo(self) make.bottom.lessThanOrEqualTo(contentView.snp_bottom) } } textLabel.snp_remakeConstraints { make in make.top.equalTo(contentView) make.left.equalTo(self.imageView.snp_right) make.trailing.equalTo(contentView) make.bottom.lessThanOrEqualTo(contentView.snp_bottom) } buttonsView.snp_remakeConstraints { make in make.top.equalTo(contentView.snp_bottom).offset(UIConstants.DefaultPadding) make.bottom.equalTo(self.snp_bottom) make.left.right.equalTo(self) if self.buttonsView.subviews.count > 0 { make.height.equalTo(UIConstants.SnackbarButtonHeight) } else { make.height.equalTo(0) } } } var showing: Bool { return alpha != 0 && self.superview != nil } /** * Helper for animating the Snackbar showing on screen. */ func show() { alpha = 1 bottom?.updateOffset(0) } /** * Helper for animating the Snackbar leaving the screen. */ func hide() { alpha = 0 var h = frame.height if h == 0 { h = UIConstants.ToolbarHeight } bottom?.updateOffset(h) } private func addButton(snackButton: SnackButton) { snackButton.bar = self buttonsView.addButtons(snackButton) buttonsView.setNeedsUpdateConstraints() } } /** * A special version of a snackbar that persists for at least a timeout. After that * it will dismiss itself on the next page load where this tab isn't showing. As long as * you stay on the current tab though, it will persist until you interact with it. */ class TimerSnackBar: SnackBar { private var prevURL: NSURL? = nil private var timer: NSTimer? = nil private var timeout: NSTimeInterval init(timeout: NSTimeInterval = 10, attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) { self.timeout = timeout super.init(attrText: attrText, img: img, buttons: buttons) } override init(frame: CGRect) { self.timeout = 0 super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func show() { self.timer = NSTimer(timeInterval: timeout, target: self, selector: #selector(TimerSnackBar.SELTimerDone), userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSDefaultRunLoopMode) super.show() } @objc func SELTimerDone() { self.timer = nil } override func shouldPersist(tab: Tab) -> Bool { if !showing { return timer != nil } return super.shouldPersist(tab) } }
mpl-2.0
e34766a7e999d420a0e80d42c804fd69
33.423841
200
0.645344
4.766621
false
false
false
false
Den-Ree/InstagramAPI
src/InstagramAPI/InstagramAPI/Example/ViewControllers/Root/RequestViewController.swift
2
28314
// // RequestViewController.swift // InstagramAPI // // Created by Sasha Kid on 12/25/16. // Copyright © 2016 ConceptOffice. All rights reserved. // import UIKit class RequestViewController: UIViewController { fileprivate var sectionsDataSource: [String?] = [] fileprivate var rowsDataSource: [[String?]] = [] @IBOutlet private weak var tableView: UITableView! { didSet { tableView.tableFooterView = UIView.init(frame: .zero) tableView.estimatedRowHeight = 50 tableView.rowHeight = UITableViewAutomaticDimension } } override func viewDidLoad() { super.viewDidLoad() self.title = "Requests" sectionsDataSource = ["User", "Relationship", "Media", "Comment", "Like", "Tag", "Location"] rowsDataSource = [["Self", "Recent of self", "User id", "Recent of user-id", "Liked", "Search"], ["Follows", "Followed by", "Requested by", "Relationship"], ["Media id", "Shortcode", "Search id"], ["Comments", "Comment id"], ["Likes"], ["Tag name", "Tag name recent", "Search"], ["Location id", "Location id recent", "Search"]] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension RequestViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return sectionsDataSource.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rowsDataSource[section].count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionsDataSource[section] as String! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RequestCell.self)) as! RequestCell cell.nameLabel.text = rowsDataSource[indexPath.section][indexPath.row] return cell } } extension RequestViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // TODO: Fix spagetti switch indexPath.section { case 0: //User switch indexPath.row { case 0: //Self let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "UserViewController") as! UserViewController controller.userParameter = .owner controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) break case 1: //Recent of self let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "UserMediaViewController") as! UserMediaViewController controller.type = .recent(nil) controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) break case 2: //User id let alertController = UIAlertController(title: "Enter user-id", message: "", preferredStyle: .alert) let goAction = UIAlertAction(title: "Go", style: .default, handler: {_ -> Void in let firstTextField = alertController.textFields![0] as UITextField let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "UserViewController") as! UserViewController controller.userParameter = InstagramUserRouter.UserParameter.id(firstTextField.text!) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {(_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "user-id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 3: //Recent of user-id let alertController = UIAlertController(title: "Enter user-id", message: "", preferredStyle: .alert) let goAction = UIAlertAction(title: "Go", style: .default, handler: {_ -> Void in let firstTextField = alertController.textFields![0] as UITextField let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "UserMediaViewController") as! UserMediaViewController controller.type = .recent(firstTextField.text) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {(_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "user-id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 4: //Liked let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "UserMediaViewController") as! UserMediaViewController controller.type = .liked controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) break case 5: //Search let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "UserSearchViewController") as! UserSearchViewController controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) break default: break } break case 1: //Relationship switch indexPath.row { case 0: //Follows let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "RelationshipTableViewController") as! RelationshipTableViewController controller.type = .follows controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) break case 1: // Followed by let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "RelationshipTableViewController") as! RelationshipTableViewController controller.type = .followedBy controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) break case 2: //Requested by let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "RelationshipTableViewController") as! RelationshipTableViewController controller.type = .requestedBy controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) break case 3: // Relationship let alertController = UIAlertController.init(title: "TargetUserId", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: {_ -> Void in let firstTextField = alertController.textFields?[0] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier:"RelationshipViewController") as! RelationshipViewController controller.targetUserId = firstTextField?.text controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {(_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "Target_user-id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break default: break } break case 2: //Media switch indexPath.row { case 0: //Media Id let alertController = UIAlertController.init(title: "MediaId", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let firstTextField = alertController.textFields?[0] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "MediaViewController") as! MediaViewController controller.mediaParameter = InstagramMediaRouter.MediaParameter.id((firstTextField?.text)!) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "media_id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) case 1: //Media Id with ShortCode let alertController = UIAlertController.init(title: "MediaIdShortCode", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let firstTextField = alertController.textFields?[0] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "MediaViewController") as! MediaViewController controller.mediaParameter = InstagramMediaRouter.MediaParameter.shortcode((firstTextField?.text)!) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "media id shortcode" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 2: //Media Search let alertController = UIAlertController.init(title: "MediaSearchId", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let longitudeTextField = alertController.textFields?[0] let latitudeTextField = alertController.textFields?[1] let distanceTextField = alertController.textFields?[2] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "MediaSearchViewController") as! MediaSearchViewController controller.parameter = InstagramMediaRouter.SearchMediaParameter(longitude: Double((longitudeTextField?.text)!)!, latitude: Double((latitudeTextField?.text)!)!, distance: Double((distanceTextField?.text)!)) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "longitude" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "latitude" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "distance" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break default: break } break case 3: //Comment switch indexPath.row { case 0: // Comments let alertController = UIAlertController.init(title: "MediaId", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let firstTextField = alertController.textFields?[0] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "CommentTableViewController") as! CommentTableViewController controller.mediaId = firstTextField?.text controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "media_id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 1: // CommentId let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "CommentIdViewController") as! CommentIdViewController self.navigationController?.pushViewController(controller, animated: true) controller.title = rowsDataSource[indexPath.section][indexPath.row] break default: break } break case 4: //Like switch indexPath.row { case 0: let alertController = UIAlertController.init(title: "MediaId", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let firstTextField = alertController.textFields?[0] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "LikeViewController") as! LikeViewController controller.mediaId = firstTextField?.text controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "media_id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) default: break } break case 5: //Tag switch indexPath.row { case 0: // Tags Name let alertController = UIAlertController.init(title: "TagName", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let firstTextField = alertController.textFields?[0] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "TagNameViewController") as! TagNameViewController controller.tagName = firstTextField?.text controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "tag_name" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 1: // Tags recent let alertController = UIAlertController.init(title: "Tags recent", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let tagNameTextField = alertController.textFields?[0] let maxTagIdTextField = alertController.textFields?[1] let minTagIdTextField = alertController.textFields?[2] let mediaCountTextField = alertController.textFields?[3] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "TagRecentViewController") as! TagRecentViewController controller.parameter = InstagramTagRouter.RecentMediaParameter(tagName: (tagNameTextField?.text)!, minId: minTagIdTextField?.text, maxId: maxTagIdTextField?.text, count: Int((mediaCountTextField?.text)!)) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "tag_name" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "max_tag_id" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "min_tag_id" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "count" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 2: //Search let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "UserSearchViewController") as! UserSearchViewController controller.title = rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) default: break } break case 6: //Location switch indexPath.row { case 0: //Location id let alertController = UIAlertController.init(title: "TagName", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let locationTextField = alertController.textFields?[0] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "LocationViewController") as! LocationViewController controller.locationId = locationTextField?.text self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "location_id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 1: // Location recent let alertController = UIAlertController.init(title: "Tags recent", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let locationIdTextField = alertController.textFields?[0] let minIdTextField = alertController.textFields?[1] let maxIdTextField = alertController.textFields?[2] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "LocationRecentViewController") as! LocationRecentViewController controller.locationParameter = InstagramLocationRouter.RecentMediaParameter(locationId: (locationIdTextField?.text)!, minId: minIdTextField?.text, maxId: maxIdTextField?.text) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "location_id" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "min_tag_id" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "max_tag_id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break case 2: // Location search let alertController = UIAlertController.init(title: "Tags recent", message: "", preferredStyle: .alert) let goAction = UIAlertAction.init(title: "Go", style: .default, handler: { _ -> Void in let latitudeTextField = alertController.textFields?[0] let longitudeTextField = alertController.textFields?[1] let distanceTextField = alertController.textFields?[2] let facebookIdTextField = alertController.textFields?[3] let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "LocationSearchViewController") as! LocationSearchViewController let latitude = NumberFormatter().number(from: (latitudeTextField?.text)!)?.doubleValue let longitude = NumberFormatter().number(from: (longitudeTextField?.text)!)?.doubleValue let distance = NumberFormatter().number(from: (distanceTextField?.text)!)?.doubleValue controller.locationSearchParameter = InstagramLocationRouter.SearchMediaParameter(longitude: longitude, latitude: latitude, distance: distance, facebookPlacesId: facebookIdTextField?.text) controller.title = self.rowsDataSource[indexPath.section][indexPath.row] self.navigationController?.pushViewController(controller, animated: true) }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "latitude" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "longitude" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "distance max = 750" } alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "facebook_places_id" } alertController.addAction(goAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) break default: break } break default: break } } }
mit
c53797c32a4324cf5a218904f995dc8f
50.106498
335
0.604563
5.832921
false
false
false
false
tombcz/numberthink
NumberThink/Logic.swift
1
9682
import Foundation import UIKit class Logic { // // Returns the peg word from the data file that exactly matches the given // number, so only expect an output if the number is between 0 and 99. // static func lookupWordForNumber(number: String) -> String { let words = Csv.readWords() for word in words.keys { if (words[word] == number) { return word; } } return ""; }; // // Returns the peg word phrase for the given number. For example, an input // of "123" would output "tin mow". This is done by stepping through pairs // of numbers from the beginning to the end and converting each pair into // a word until there is 1 (or none) left, which is then converted. This // minimizes the phrase length. // static func convertNumberToPhrase(number: String) -> Array<String> { var words = [String](); var index = 0 while(true) { // stop when we reach the end if index == number.characters.count { break } // convert the next two digits if we have them if index + 1 < number.characters.count { let pair = Logic.substring(string: number, fromIndex: index, toIndex: index+2)! let match = Logic.lookupWordForNumber(number:pair) words.append(match) index += 2 } else { // just one digit left so convert it let single = Logic.substring(string: number, fromIndex: index, toIndex: index+1)! let match = Logic.lookupWordForNumber(number:single) words.append(match) index += 1 } } return words }; // // Returns a list of strings that represent the sounds that make up // the given word. // static func convertWordToSounds(word: String) -> Array<String> { var sounds = [String]() var start = 0 while(true) { // stop when we reach the end of the word if(start >= word.characters.count) { break; } var digit = ""; var sound = Logic.substring(string:word, fromIndex: start, toIndex: start+1) if(Logic.isIgnored(s:sound!) == true) { start += 1 } else { // check for a 3-character sound if(start+2 < word.characters.count) { sound = Logic.substring(string:word, fromIndex: start, toIndex: start + 3); digit = Logic.digitForSound(s:sound!); if(digit != "") { start += 3; } } // check for 2-character if we didn't find a 3-character sound if(digit == "" && start+1 < word.characters.count) { sound = Logic.substring(string:word, fromIndex: start, toIndex: start + 2); digit = Logic.digitForSound(s:sound!); if(digit != "") { start += 2; } } // use the 1-character sound if we didn't find any 2- or 3-character sounds if(digit == "") { sound = Logic.substring(string: word, fromIndex: start, toIndex: start + 1) digit = Logic.digitForSound(s:sound!); start += 1; } } sounds.append(sound!) } return sounds } // // Returns true if the given srting (which should contain a single letter // is ignored in the Major System. // static func isIgnored(s: String) -> Bool { let c = s[s.index(s.startIndex, offsetBy: 0)] switch (c) { case "a": return true; case "e": return true; case "i": return true; case "o": return true; case "u": return true; case "w": return true; case "h": return true; case "y": return true; case " ": return true; case "_": return true; case "-": return true; default: return false; } } // // Returns the digit for the given sound. This isn't perfect since // we're just basing this off of letter combinations, but it works // for the peg words that are included in the app. // static func digitForSound(s:String) -> String { switch (s) { case "z": return "0"; case "s": return "0"; case "zz": return "0"; case "ss": return "0"; case "sy": return "0"; case "ce": return "0"; case "ci": return "0"; case "cy": return "0"; case "d": return "1"; case "t": return "1"; case "dd": return "1"; case "dy": return "1"; case "tt": return "1"; case "ty": return "1"; case "n": return "2"; case "nn": return "2"; case "kn": return "2"; case "m": return "3"; case "mb": return "3" case "mm": return "3" case "r": return "4"; case "rr": return "4"; case "l": return "5"; case "ll": return "5"; case "ly": return "5"; case "j": return "6"; case "jj": return "6"; case "sh": return "6"; case "ch": return "6"; case "ge": return "6"; case "gi": return "6"; case "gy": return "6"; case "tch": return "6"; case "k": return "7"; case "c": return "7"; case "g": return "7"; case "q": return "7"; case "kk": return "7"; case "ky": return "7"; case "ck": return "7"; case "cc": return "7"; case "gg": return "7"; case "qq": return "7"; case "qu": return "7"; case "f": return "8"; case "v": return "8"; case "ff": return "8"; case "fy": return "8"; case "vv": return "8"; case "vy": return "8"; case "ph": return "8"; case "p": return "9"; case "b": return "9"; case "pp": return "9"; case "py": return "9"; case "bb": return "9"; case "by": return "9"; default: return ""; } } static func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.characters.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } static func digitColor(digit:String) -> UIColor { switch digit { case "0": return Logic.hexStringToUIColor(hex:"#90CAF9"); case "1": return Logic.hexStringToUIColor(hex:"#81D4FA"); case "2": return Logic.hexStringToUIColor(hex:"#CE93D8"); case "3": return Logic.hexStringToUIColor(hex:"#9FA8DA"); case "4": return Logic.hexStringToUIColor(hex:"#F48FB1"); case "5": return Logic.hexStringToUIColor(hex:"#A5D6A7"); case "6": return Logic.hexStringToUIColor(hex:"#E6EE9C"); case "7": return Logic.hexStringToUIColor(hex:"#FFE082"); case "8": return Logic.hexStringToUIColor(hex:"#FFAB91"); case "9": return Logic.hexStringToUIColor(hex:"#EF9A9A"); default: return Logic.hexStringToUIColor(hex:"#EEEEEE"); } } static func substring(string: String, fromIndex: Int, toIndex: Int) -> String? { let startIndex = string.index(string.startIndex, offsetBy: fromIndex) let endIndex = string.index(string.startIndex, offsetBy: toIndex) return String(string[startIndex..<endIndex]) } static func primaryColor() -> UIColor { return hexStringToUIColor(hex: "#2C2C2C"); } static func activeBarColor() -> UIColor { return hexStringToUIColor(hex: "#333333"); } static func textColor() -> UIColor { return hexStringToUIColor(hex: "#EEEEEE"); } }
mit
87d8fce43754d9a40a7693fda97a80c8
27.560472
97
0.452592
4.58428
false
false
false
false
SimonFairbairn/Stormcloud
example/iOS example/SettingsViewController.swift
1
4958
// // SettingsViewController.swift // iCloud Extravaganza // // Created by Simon Fairbairn on 18/10/2015. // Copyright © 2015 Voyage Travel Apps. All rights reserved. // import UIKit import CoreData import Stormcloud class SettingsViewController: UIViewController, StormcloudViewController { var coreDataStack: CoreDataStack? { didSet { if let context = coreDataStack?.managedObjectContext { self.cloudAdder = CloudAdder(context: context) } } } var stormcloud: Stormcloud? var cloudAdder : CloudAdder? @IBOutlet var settingsSwitch1 : UISwitch! @IBOutlet var settingsSwitch2 : UISwitch! @IBOutlet var settingsSwitch3 : UISwitch! @IBOutlet var textField : UITextField! @IBOutlet var valueLabel : UILabel! @IBOutlet var valueStepper : UIStepper! @IBOutlet var cloudLabel : UILabel! func updateCount() { if let stack = coreDataStack { let clouds = stack.performRequestForTemplate(ICEFetchRequests.CloudFetch) self.cloudLabel.text = "Cloud Count: \(clouds.count)" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. NotificationCenter.default.addObserver(self, selector: #selector(updateDefaults), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: nil) self.prepareSettings() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.updateCount() } deinit { NotificationCenter.default.removeObserver(self) } } extension SettingsViewController { @objc func updateDefaults(note : NSNotification ) { defer { self.prepareSettings() } guard let reason = note.userInfo?[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int else { return } if reason == NSUbiquitousKeyValueStoreServerChange || reason == NSUbiquitousKeyValueStoreInitialSyncChange { guard let hasKeys = note.userInfo?[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] else { return } for key in hasKeys { let value = NSUbiquitousKeyValueStore.default.object(forKey: key) UserDefaults.standard.set(value, forKey: key) } } } func prepareSettings() { settingsSwitch1.isOn = UserDefaults.standard.bool(forKey: ICEDefaultsKeys.Setting1.rawValue) settingsSwitch2.isOn = UserDefaults.standard.bool(forKey: ICEDefaultsKeys.Setting2.rawValue) settingsSwitch3.isOn = UserDefaults.standard.bool(forKey: ICEDefaultsKeys.Setting3.rawValue) if let text = UserDefaults.standard.string(forKey: ICEDefaultsKeys.textValue.rawValue) { self.textField.text = text } self.valueStepper.value = Double(UserDefaults.standard.integer(forKey: ICEDefaultsKeys.stepperValue.rawValue)) self.valueLabel.text = "Add Clouds: \(Int(valueStepper.value))" } } extension SettingsViewController { @IBAction func addNewClouds( _ sender : UIButton ) { if let adder = self.cloudAdder, let stack = self.coreDataStack { let clouds = stack.performRequestForTemplate(ICEFetchRequests.CloudFetch) let total = Int(self.valueStepper.value) let runningTotal = clouds.count + 1 for i in 0 ..< total { adder.addCloudWithNumber(number: runningTotal + i, addRaindrops : false) } self.updateCount() } } @IBAction func settingsSwitchChanged( _ sender : UISwitch ) { var key : String? if let senderSwitch = sender.accessibilityLabel { if senderSwitch.contains("1") { key = ICEDefaultsKeys.Setting1.rawValue } else if senderSwitch.contains("2") { key = ICEDefaultsKeys.Setting2.rawValue } else if senderSwitch.contains("3") { key = ICEDefaultsKeys.Setting3.rawValue } } if let hasKey = key { UserDefaults.standard.set(sender.isOn, forKey: hasKey) } } @IBAction func stepperChanged( _ sender : UIStepper ) { self.valueLabel.text = "Add Clouds: \(Int(sender.value))" UserDefaults.standard.set(Int(sender.value), forKey: ICEDefaultsKeys.stepperValue.rawValue) } @IBAction func dismissCloudVC(_ sender : UIBarButtonItem ) { self.dismiss(animated: true, completion: nil) } } extension SettingsViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } func textFieldDidEndEditing(_ textField: UITextField) { UserDefaults.standard.set(textField.text, forKey: ICEDefaultsKeys.textValue.rawValue) } }
mit
b930f54c733206c8cf68812d74079c55
30.176101
161
0.654428
4.798645
false
false
false
false
TriangleLeft/Flashcards
ios/Flashcards/UI/Vocabular/VocabularyStrengthView.swift
1
1104
// // VocabularyStrengthView.swift // Flashcards // // Created by Aleksey Kurnosenko on 29.08.16. // Copyright © 2016 TriangleLeft. All rights reserved. // import UIKit @IBDesignable class VocabularyStrengthView: UIImageView { func setStrength(value:Int) { var color:UIColor? switch value { case 1: image = UIImage(named: "ic_signal_cellular_1_bar_black_24dp") color = UIColor.flashcardsRed() case 2: image = UIImage(named: "ic_signal_cellular_2_bar_black_24dp") color = UIColor.flashcardsOrange() case 3: image = UIImage(named: "ic_signal_cellular_3_bar_black_24dp") color = UIColor.flashcardsLime() case 4: image = UIImage(named: "ic_signal_cellular_4_bar_black_24dp") color = UIColor.flashcardsGreen() default: image = UIImage(named: "ic_signal_cellular_1_bar_black_24dp") color = UIColor.flashcardsRed() } image = image?.imageWithRenderingMode(.AlwaysTemplate) tintColor = color } }
apache-2.0
1ce962c17e113461aa059dcc0063e363
29.638889
73
0.608341
3.897527
false
false
false
false
ellited/Lieferando-Services
Lieferando Services/PlaceSearchController.swift
1
3407
// // PlaceSearchController.swift // Lieferando Services // // Created by Mikhail Rudenko on 10/06/2017. // Copyright © 2017 App-Smart. All rights reserved. // import UIKit import RxSwift import Kingfisher class PlaceSearchController: UITableViewController, UISearchResultsUpdating{ @IBOutlet weak var placeholderView:UIView? var viewModel:PlaceSearchViewModel? var searchController: UISearchController? override func viewDidLoad() { super.viewDidLoad() self.definesPresentationContext = true searchController = UISearchController.init(searchResultsController: nil) searchController?.searchResultsUpdater = self searchController?.dimsBackgroundDuringPresentation = false tableView.tableHeaderView = searchController?.searchBar tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 140 viewModel = PlaceSearchViewModel.init() _ = self.viewModel?.needUpdateList.asObservable().subscribe { e in if (self.viewModel?.needUpdateList.value == true) { self.tableView.reloadData() } if (self.viewModel?.placeArray.count)! > 2 { self.placeholderView?.isHidden = true } else { self.placeholderView?.isHidden = false } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel?.placeArray.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlaceListCell", for: indexPath) as! PlaceListCell let placeItem = self.viewModel?.placeArray[indexPath.row] cell.placeNameLabel?.text = placeItem?.name cell.placeAddressLabel?.text = self.viewModel?.getPlaceAddress(forIndex: indexPath.row) if let imageUrl = placeItem?.imageUrl{ cell.placeImageView?.kf.setImage(with: URL.init(string: imageUrl)) } else { cell.placeImageView?.image = nil } return cell } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if(self.searchController?.isActive)! { let placeItem = self.viewModel?.placeArray[indexPath.row] let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let vc: PlaceController = storyboard.instantiateViewController(withIdentifier: "PlaceController") as! PlaceController vc.placeItem = placeItem self.navigationController?.pushViewController(vc, animated: true) } } // MARK: - UISearchResultsUpdating func updateSearchResults(for searchController: UISearchController) { if let searchText = searchController.searchBar.text { self.viewModel?.filterPlaces(byString: searchText) } } }
apache-2.0
63b0ff5757355636da13b6f046f00c80
32.392157
129
0.644157
5.592775
false
false
false
false
gottesmm/swift
test/decl/protocol/req/associated_type_inference.swift
3
8348
// RUN: %target-typecheck-verify-swift protocol P0 { associatedtype Assoc1 : PSimple // expected-note{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}} // expected-note@-1{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}} // expected-note@-2{{unable to infer associated type 'Assoc1' for protocol 'P0'}} // expected-note@-3{{unable to infer associated type 'Assoc1' for protocol 'P0'}} func f0(_: Assoc1) func g0(_: Assoc1) } protocol PSimple { } extension Int : PSimple { } extension Double : PSimple { } struct X0a : P0 { // okay: Assoc1 == Int func f0(_: Int) { } func g0(_: Int) { } } struct X0b : P0 { // expected-error{{type 'X0b' does not conform to protocol 'P0'}} func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}} func g0(_: Double) { } // expected-note{{matching requirement 'g0' to this declaration inferred associated type to 'Double'}} } struct X0c : P0 { // okay: Assoc1 == Int func f0(_: Int) { } func g0(_: Float) { } func g0(_: Int) { } } struct X0d : P0 { // okay: Assoc1 == Int func f0(_: Int) { } func g0(_: Double) { } // viable, but no corresponding f0 func g0(_: Int) { } } struct X0e : P0 { // expected-error{{type 'X0e' does not conform to protocol 'P0'}} func f0(_: Double) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Double}} func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}} func g0(_: Double) { } func g0(_: Int) { } } struct X0f : P0 { // okay: Assoc1 = Int because Float doesn't conform to PSimple func f0(_: Float) { } func f0(_: Int) { } func g0(_: Float) { } func g0(_: Int) { } } struct X0g : P0 { // expected-error{{type 'X0g' does not conform to protocol 'P0'}} func f0(_: Float) { } // expected-note{{inferred type 'Float' (by matching requirement 'f0') is invalid: does not conform to 'PSimple'}} func g0(_: Float) { } // expected-note{{inferred type 'Float' (by matching requirement 'g0') is invalid: does not conform to 'PSimple'}} } struct X0h<T : PSimple> : P0 { func f0(_: T) { } } extension X0h { func g0(_: T) { } } struct X0i<T : PSimple> { } extension X0i { func g0(_: T) { } } extension X0i : P0 { } extension X0i { func f0(_: T) { } } // Protocol extension used to infer requirements protocol P1 { } extension P1 { final func f0(_ x: Int) { } final func g0(_ x: Int) { } } struct X0j : P0, P1 { } protocol P2 { associatedtype P2Assoc func h0(_ x: P2Assoc) } extension P2 where Self.P2Assoc : PSimple { final func f0(_ x: P2Assoc) { } // expected-note{{inferred type 'Float' (by matching requirement 'f0') is invalid: does not conform to 'PSimple'}} final func g0(_ x: P2Assoc) { } // expected-note{{inferred type 'Float' (by matching requirement 'g0') is invalid: does not conform to 'PSimple'}} } struct X0k : P0, P2 { func h0(_ x: Int) { } } struct X0l : P0, P2 { // expected-error{{type 'X0l' does not conform to protocol 'P0'}} func h0(_ x: Float) { } } // Prefer declarations in the type to those in protocol extensions struct X0m : P0, P2 { func f0(_ x: Double) { } func g0(_ x: Double) { } func h0(_ x: Double) { } } // Inference from properties. protocol PropertyP0 { associatedtype Prop : PSimple // expected-note{{unable to infer associated type 'Prop' for protocol 'PropertyP0'}} var property: Prop { get } } struct XProp0a : PropertyP0 { // okay PropType = Int var property: Int } struct XProp0b : PropertyP0 { // expected-error{{type 'XProp0b' does not conform to protocol 'PropertyP0'}} var property: Float // expected-note{{inferred type 'Float' (by matching requirement 'property') is invalid: does not conform to 'PSimple'}} } // Inference from subscripts protocol SubscriptP0 { associatedtype Index associatedtype Element : PSimple // expected-note{{unable to infer associated type 'Element' for protocol 'SubscriptP0'}} subscript (i: Index) -> Element { get } } struct XSubP0a : SubscriptP0 { subscript (i: Int) -> Int { get { return i } } } struct XSubP0b : SubscriptP0 { // expected-error{{type 'XSubP0b' does not conform to protocol 'SubscriptP0'}} subscript (i: Int) -> Float { get { return Float(i) } } // expected-note{{inferred type 'Float' (by matching requirement 'subscript') is invalid: does not conform to 'PSimple'}} } // Inference from properties and subscripts protocol CollectionLikeP0 { associatedtype Index associatedtype Element var startIndex: Index { get } var endIndex: Index { get } subscript (i: Index) -> Element { get } } struct SomeSlice<T> { } struct XCollectionLikeP0a<T> : CollectionLikeP0 { var startIndex: Int var endIndex: Int subscript (i: Int) -> T { get { fatalError("blah") } } subscript (r: Range<Int>) -> SomeSlice<T> { get { return SomeSlice() } } } // rdar://problem/21304164 public protocol Thenable { associatedtype T // expected-note{{protocol requires nested type 'T'}} func then(_ success: (_: T) -> T) -> Self } public class CorePromise<T> : Thenable { // expected-error{{type 'CorePromise<T>' does not conform to protocol 'Thenable'}} public func then(_ success: @escaping (_ t: T, _: CorePromise<T>) -> T) -> Self { return self.then() { (t: T) -> T in return success(t: t, self) } } } // rdar://problem/21559670 protocol P3 { associatedtype Assoc = Int associatedtype Assoc2 func foo(_ x: Assoc2) -> Assoc? } protocol P4 : P3 { } extension P4 { func foo(_ x: Int) -> Float? { return 0 } } extension P3 where Assoc == Int { func foo(_ x: Int) -> Assoc? { return nil } } struct X4 : P4 { } // rdar://problem/21738889 protocol P5 { associatedtype A = Int } struct X5<T : P5> : P5 { typealias A = T.A } protocol P6 : P5 { associatedtype A : P5 = X5<Self> } extension P6 where A == X5<Self> { } // rdar://problem/21774092 protocol P7 { associatedtype A associatedtype B func f() -> A func g() -> B } struct X7<T> { } extension P7 { func g() -> X7<A> { return X7() } } struct Y7<T> : P7 { func f() -> Int { return 0 } } struct MyAnySequence<Element> : MySequence { typealias SubSequence = MyAnySequence<Element> func makeIterator() -> MyAnyIterator<Element> { return MyAnyIterator<Element>() } } struct MyAnyIterator<T> : MyIteratorType { typealias Element = T } protocol MyIteratorType { associatedtype Element } protocol MySequence { associatedtype Iterator : MyIteratorType associatedtype SubSequence func foo() -> SubSequence func makeIterator() -> Iterator } extension MySequence { func foo() -> MyAnySequence<Iterator.Element> { return MyAnySequence() } } struct SomeStruct<Element> : MySequence { let element: Element init(_ element: Element) { self.element = element } func makeIterator() -> MyAnyIterator<Element> { return MyAnyIterator<Element>() } } // rdar://problem/21883828 - ranking of solutions protocol P8 { } protocol P9 : P8 { } protocol P10 { associatedtype A func foo() -> A } struct P8A { } struct P9A { } extension P8 { func foo() -> P8A { return P8A() } } extension P9 { func foo() -> P9A { return P9A() } } struct Z10 : P9, P10 { } func testZ10() -> Z10.A { var zA: Z10.A zA = P9A() return zA } // rdar://problem/21926788 protocol P11 { associatedtype A associatedtype B func foo() -> B } extension P11 where A == Int { func foo() -> Int { return 0 } } protocol P12 : P11 { } extension P12 { func foo() -> String { return "" } } struct X12 : P12 { typealias A = String } // Infinite recursion -- we would try to use the extension // initializer's argument type of 'Dough' as a candidate for // the associated type protocol Cookie { associatedtype Dough // expected-note@-1 {{protocol requires nested type 'Dough'; do you want to add it?}} init(t: Dough) } extension Cookie { init(t: Dough?) {} } struct Thumbprint : Cookie {} // expected-error@-1 {{type 'Thumbprint' does not conform to protocol 'Cookie'}} // Looking through typealiases protocol Vector { associatedtype Element typealias Elements = [Element] func process(elements: Elements) } struct Int8Vector : Vector { func process(elements: [Int8]) { } }
apache-2.0
c3cef7c5ac280abb0ff28f9455d88860
22.383754
179
0.653809
3.284028
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift
11
3917
// // UIControl+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension Reactive where Base: UIControl { /// Bindable sink for `enabled` property. public var isEnabled: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: self.base) { control, value in control.isEnabled = value } } /// Bindable sink for `selected` property. public var isSelected: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: self.base) { control, selected in control.isSelected = selected } } /// Reactive wrapper for target action pattern. /// /// - parameter controlEvents: Filter for observed event types. public func controlEvent(_ controlEvents: UIControlEvents) -> ControlEvent<Void> { let source: Observable<Void> = Observable.create { [weak control = self.base] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = control else { observer.on(.completed) return Disposables.create() } let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) { control in observer.on(.next()) } return Disposables.create(with: controlTarget.dispose) }.takeUntil(deallocated) return ControlEvent(events: source) } /// This is internal convenience method /// https://github.com/ReactiveX/RxSwift/issues/681 /// In case similar behavior is externally needed, one can use the following snippet /// /// ```swift /// extension UIControl { /// static func valuePublic<T, ControlType: UIControl>(_ control: ControlType, getter: @escaping (ControlType) -> T, setter: @escaping (ControlType, T) -> ()) -> ControlProperty<T> { /// let values: Observable<T> = Observable.deferred { [weak control] in /// guard let existingSelf = control else { /// return Observable.empty() /// } /// /// return (existingSelf as UIControl).rx.controlEvent([.allEditingEvents, .valueChanged]) /// .flatMap { _ in /// return control.map { Observable.just(getter($0)) } ?? Observable.empty() /// } /// .startWith(getter(existingSelf)) /// } /// return ControlProperty(values: values, valueSink: UIBindingObserver(UIElement: control) { control, value in /// setter(control, value) /// }) /// } ///} ///``` static func value<C: UIControl, T>(_ control: C, getter: @escaping (C) -> T, setter: @escaping (C, T) -> Void) -> ControlProperty<T> { let source: Observable<T> = Observable.create { [weak weakControl = control] observer in guard let control = weakControl else { observer.on(.completed) return Disposables.create() } observer.on(.next(getter(control))) let controlTarget = ControlTarget(control: control, controlEvents: [.allEditingEvents, .valueChanged]) { _ in if let control = weakControl { observer.on(.next(getter(control))) } } return Disposables.create(with: controlTarget.dispose) } .takeUntil((control as NSObject).rx.deallocated) let bindingObserver = UIBindingObserver(UIElement: control, binding: setter) return ControlProperty<T>(values: source, valueSink: bindingObserver) } } #endif
apache-2.0
e73235ffbf1b2b4d7114b10564a15755
35.943396
191
0.582993
4.913425
false
false
false
false
JadenGeller/Handbag
Sources/BagGenerator.swift
1
919
// // BagGenerator.swift // Handbag // // Created by Jaden Geller on 1/11/16. // Copyright © 2016 Jaden Geller. All rights reserved. // public struct BagGenerator<Element: Hashable>: GeneratorType { private var backing: [Element : Int] private var elementIndex: DictionaryIndex<Element, Int> private var duplicateIndex: Int internal init(_ backing: [Element : Int]) { self.backing = backing self.elementIndex = backing.startIndex self.duplicateIndex = 0 } public mutating func next() -> Element? { guard elementIndex < backing.endIndex else { return nil } while duplicateIndex >= backing[elementIndex].1 { elementIndex = elementIndex.successor() duplicateIndex = 0 guard elementIndex < backing.endIndex else { return nil } } duplicateIndex += 1 return backing[elementIndex].0 } }
mit
f1e2b47ef2da338aec33f7909cd2cd12
29.633333
69
0.643791
4.522167
false
false
false
false
mekentosj/BWWalkthrough
BWWalkthrough/BWWalkthroughPageViewController.swift
1
7549
/* The MIT License (MIT) Copyright (c) 2015 Yari D'areglia @bitwaker 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. */ // // BWWalkthroughPageViewController.swift // BWWalkthrough // // Created by Yari D'areglia on 17/09/14. // Copyright (c) 2014 Yari D'areglia. All rights reserved. // import UIKit /// The type of animation the walkthrough page is performing. enum WalkthroughAnimationType { /// A standard, linear animation case linear /// A curved animation case curve /// A zoom animation case zoom /// An in out animation. case inOut /** Allows for initialisation of a `WalkthroughAnimationType` from a `String`. Supported strings (case insensitive): - "Linear" - "Curve" - "Zoom" - "InOut" :param: string A string describing the desired animation type. :returns: A `WalkthroughAnimationType` matching the given string, or just a `Linear` animation if the string is unsupported. */ static func fromString(_ string: String) -> WalkthroughAnimationType { switch(string.lowercased()) { case "linear": return .linear case "curve": return .curve case "zoom": return .zoom case "inout": return .inOut default: return .linear } } } // MARK: Walkthrough Page View Controller Class /** **BWWalkthroughPageViewController** This is a `UIViewController` which adopts the `BWWalkthroughPage` protocol and allows for a default implementation of page behaviour for use in the `BWWalkthroughViewController`. Unless you have a specific reason not to, you should subclass this view controller if you want it to be a part of the `BWWalkthroughViewController`. If you do have a specific reason, feel free to simply adopt the `BWWalkthroughPage` protocol. */ class BWWalkthroughPageViewController: UIViewController, BWWalkthroughPage { // MARK: Properties - Animation /// The speed of the animation. @IBInspectable var animationSpeed = CGPoint(x: 0.0, y: 0.0); /// The variance in speed of the animation. @IBInspectable var animationSpeedVariance = CGPoint(x: 0.0, y: 0.0) /// The type of the animation. @IBInspectable var animationType = "Linear" /// Whether or not to animate the alpha value of the page. @IBInspectable var animateAlpha = false // MARK: Properties /// The delegate which allows for comunication back up to the walkthrough view controller. var delegate: WalkthroughPageDelegate? /// Speeds of the animation applied to our subviews, mapped to each subview. fileprivate var subviewSpeeds = [CGPoint]() override func viewDidLoad() { super.viewDidLoad() view.layer.masksToBounds = true // for each view we increase the animation speed appropriately and store it as a speed for that layer subviewSpeeds = view.subviews.map { _ in self.animationSpeed.x += self.animationSpeedVariance.x self.animationSpeed.y += self.animationSpeedVariance.y return self.animationSpeed } } // MARK: BWWalkthroughPage Functions func walkthroughDidScroll(_ position: CGFloat, offset: CGFloat) { for index in 0..<subviewSpeeds.count { // perform transition / scale / rotate animations switch WalkthroughAnimationType.fromString(animationType) { case WalkthroughAnimationType.linear: animationLinear(index, offset) case WalkthroughAnimationType.zoom: animationZoom(index, offset) case WalkthroughAnimationType.curve: animationCurve(index, offset) case WalkthroughAnimationType.inOut: animationInOut(index, offset) } // animate alpha if(animateAlpha) { animationAlpha(index, offset) } } } // MARK: Animations (WIP) /** Animate alpha of subviews based on the current offset of the walkthrough. :param: index The index of the view to animate. :param offset The current offset of the walkthrough. */ fileprivate func animationAlpha(_ index: Int, _ offset: CGFloat) { var offset = offset for subview in view.subviews { // if the offset is more than 1, we knock it down if (offset > 1.0) { offset = 1.0 + (1.0 - offset) } subview.alpha = (offset) } } fileprivate func animationCurve(_ index:Int, _ offset:CGFloat) { var transform = CATransform3DIdentity let x:CGFloat = (1.0 - offset) * 10 transform = CATransform3DTranslate(transform, (pow(x,3) - (x * 25)) * subviewSpeeds[index].x, (pow(x,3) - (x * 20)) * subviewSpeeds[index].y, 0 ) view.subviews[index].layer.transform = transform } fileprivate func animationZoom(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } let scale:CGFloat = (1.0 - tmpOffset) transform = CATransform3DScale(transform, 1 - scale , 1 - scale, 1.0) view.subviews[index].layer.transform = transform } fileprivate func animationLinear(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let mx:CGFloat = (1.0 - offset) * 100 transform = CATransform3DTranslate(transform, mx * subviewSpeeds[index].x, mx * subviewSpeeds[index].y, 0 ) view.subviews[index].layer.transform = transform } fileprivate func animationInOut(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var x:CGFloat = (1.0 - offset) * 20 var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } transform = CATransform3DTranslate(transform, (1.0 - tmpOffset) * subviewSpeeds[index].x * 100, (1.0 - tmpOffset) * subviewSpeeds[index].y * 100, 0) view.subviews[index].layer.transform = transform } }
mit
d1999ad4624e839b4cfa092c48fa64a5
35.298077
156
0.629885
4.777848
false
false
false
false
zhouguangjie/EVReflection
EVReflection/pod/EVReflection.swift
1
23151
// // EVReflection.swift // // Created by Edwin Vermeer on 28-09-14. // Copyright (c) 2014 EVICT BV. All rights reserved. // import Foundation import CloudKit /** Reflection methods */ final public class EVReflection { /** Create an object from a dictionary :param: dictionary The dictionary that will be converted to an object :param: anyobjectTypeString The string representation of the object type that will be created :return: The object that is created from the dictionary */ public class func fromDictionary(dictionary:NSDictionary, anyobjectTypeString: String) -> NSObject? { if var nsobject = swiftClassFromString(anyobjectTypeString) { nsobject = setPropertiesfromDictionary(dictionary, anyObject: nsobject) return nsobject } return nil } /** Set object properties from a dictionary :param: dictionary The dictionary that will be converted to an object :param: anyObject The object where the properties will be set :return: The object that is created from the dictionary */ public class func setPropertiesfromDictionary<T where T:NSObject>(dictionary:NSDictionary, anyObject: T) -> T { var (hasKeys, hasTypes) = toDictionary(anyObject) for (k, v) in dictionary { if var key = k as? String { var newValue: AnyObject? = dictionary[key]! if let type = hasTypes[key] { if type.hasPrefix("Swift.Array<") && newValue as? NSDictionary != nil { if var value = v as? [NSObject] { value.append(newValue! as! NSObject) newValue = value } } else if type != "NSDictionary" && newValue as? NSDictionary != nil { newValue = dictToObject(type, original:hasKeys[key] as! NSObject ,dict: newValue as! NSDictionary) } else if type.rangeOfString("<NSDictionary>") == nil && newValue as? [NSDictionary] != nil { newValue = dictArrayToObjectArray(type, array: newValue as! [NSDictionary]) as [NSObject] } } let keywords = ["self", "description", "class", "deinit", "enum", "extension", "func", "import", "init", "let", "protocol", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "do", "else", "fallthrough", "if", "in", "for", "return", "switch", "where", "while", "as", "dynamicType", "is", "new", "super", "Self", "Type", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", "associativity", "didSet", "get", "infix", "inout", "left", "mutating", "none", "nonmutating", "operator", "override", "postfix", "precedence", "prefix", "right", "set", "unowned", "unowned", "safe", "unowned", "unsafe", "weak", "willSet", "private", "public", "internal", "zone"] if contains(keywords, key) { key = "_\(key)" } var error: NSError? if anyObject.validateValue(&newValue, forKey: key, error: &error) { if newValue == nil || newValue as? NSNull != nil { anyObject.setValue(Optional.None, forKey: key) } else { // Let us put a number into a string property by taking it's stringValue if let typeInObject = hasTypes[key] { let (_, type) = valueForAny("", key: key, anyValue: newValue) if (typeInObject == "Swift.String" || typeInObject == "NSString") && type == "NSNumber" { if let convertedValue = newValue as? NSNumber { newValue = convertedValue.stringValue } } } // TODO: This will trigger setvalue for undefined key for specific types like enums, arrays of optionals or optional types. anyObject.setValue(newValue, forKey: key) } } } } return anyObject } /** Set sub object properties from a dictionary :param: type The object type that will be created :param: dict The dictionary that will be converted to an object :return: The object that is created from the dictionary */ private class func dictToObject<T where T:NSObject>(type:String, original:T ,dict:NSDictionary) -> T { var returnObject:NSObject = swiftClassFromString(type) returnObject = setPropertiesfromDictionary(dict, anyObject: returnObject) return returnObject as! T } /** Create an Array of objects from an array of dictionaries :param: type The object type that will be created :param: array The array of dictionaries that will be converted to the array of objects :return: The array of objects that is created from the array of dictionaries */ private class func dictArrayToObjectArray(type:String, array:[NSDictionary]) -> [NSObject] { var subtype = "EVObject" if (split(type) {$0 == "<"}).count > 1 { // Remove the Swift.Array prefix subtype = type.substringFromIndex((split(type) {$0 == "<"} [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) // Remove the optional prefix from the subtype if subtype.hasPrefix("Swift.Optional<") { subtype = subtype.substringFromIndex((split(subtype) {$0 == "<"} [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) } } var result = [NSObject]() for item in array { let arrayObject = self.dictToObject(subtype, original:swiftClassFromString(subtype), dict: item) result.append(arrayObject) } return result } /** Helper function that let us get the actual type of an object that is used inside an array :param: array The array of objects where we want the type of the object */ private class func getArrayObjectType<T where T:NSObject>(array:[T]) -> String { return NSStringFromClass(T().dynamicType) as String } /** Convert an object to a dictionary :param: theObject The object that will be converted to a dictionary :return: The dictionary that is created from theObject plus a dictionary of propery types. */ public class func toDictionary(theObject: NSObject) -> (NSDictionary, Dictionary<String,String>) { let reflected = reflect(theObject) return reflectedSub(theObject, reflected: reflected) } /** for parsing an object to a dictionary. including properties from it's super class (recursive) :param: reflected The object parsed using the reflect method. :return: The dictionary that is created from the object plus an dictionary of property types. */ private class func reflectedSub(theObject:Any, reflected: MirrorType) -> (NSDictionary, Dictionary<String, String>) { var propertiesDictionary : NSMutableDictionary = NSMutableDictionary() var propertiesTypeDictionary : Dictionary<String,String> = Dictionary<String,String>() for i in 0..<reflected.count { let property = reflected[i] let key: String = property.0 let mirrorType = property.1 let value = mirrorType.value var valueType:String = "" if key != "super" || i != 0 { var (unboxedValue: AnyObject, valueType: String) = valueForAny(theObject, key: key, anyValue: value) if unboxedValue as? EVObject != nil { let (dict, _) = toDictionary(unboxedValue as! NSObject) propertiesDictionary.setValue(dict, forKey: key) } else if let array = unboxedValue as? [EVObject] { var tempValue = [NSDictionary]() for av in array { let (dict, type) = toDictionary(av) tempValue.append(dict) } unboxedValue = tempValue propertiesDictionary.setValue(unboxedValue, forKey: key) } else { propertiesDictionary.setValue(unboxedValue, forKey: key) } propertiesTypeDictionary[key] = valueType } else { let (addProperties,_) = reflectedSub(value, reflected: mirrorType) for (k, v) in addProperties { propertiesDictionary.setValue(v, forKey: k as! String) } } } return (propertiesDictionary, propertiesTypeDictionary) } /** Dump the content of this object :param: theObject The object that will be loged */ public class func logObject(theObject: NSObject) { NSLog(description(theObject)) } /** Return a string representation of this object :param: theObject The object that will be loged :return: The string representation of the object */ public class func description(theObject: NSObject) -> String { var description: String = swiftStringFromClass(theObject) + " {\n hash = \(theObject.hash)\n" let (hasKeys, hasTypes) = toDictionary(theObject) for (key, value) in hasKeys { description = description + " key = \(key), value = \(value)\n" } description = description + "}\n" return description } /** Return a Json string representation of this object :param: theObject The object that will be loged :return: The string representation of the object */ public class func toJsonString(theObject: NSObject) -> String { var (dict,_) = EVReflection.toDictionary(theObject) dict = convertDictionaryForJsonSerialization(dict) var error:NSError? = nil if var jsonData = NSJSONSerialization.dataWithJSONObject(dict , options: .PrettyPrinted, error: &error) { if var jsonString = NSString(data:jsonData, encoding:NSUTF8StringEncoding) { return jsonString as String } } return "" } /** Clean up dictionary so that it can be converted to json */ private class func convertDictionaryForJsonSerialization(dict: NSDictionary) -> NSDictionary { for (key, value) in dict { dict.setValue(convertValueForJsonSerialization(value), forKey: key as! String) } return dict } /** Clean up a value so that it can be converted to json */ private class func convertValueForJsonSerialization(value : AnyObject) -> AnyObject { switch(value) { case let stringValue as NSString: return stringValue case let numberValue as NSNumber: return numberValue case let nullValue as NSNull: return nullValue case let arrayValue as NSArray: var tempArray: NSMutableArray = NSMutableArray() for value in arrayValue { tempArray.addObject(convertValueForJsonSerialization(value)) } return tempArray case let ok as NSDictionary: return convertDictionaryForJsonSerialization(ok) case let dateValue as NSDate: var dateFormatter = NSDateFormatter() return dateFormatter.stringFromDate(dateValue) case let recordIdValue as CKRecordID: return recordIdValue.recordName default: return "\(value)" } } /** Return a dictionary representation for the json string :param: json The json string that will be converted :return: The dictionary representation of the json */ public class func dictionaryFromJson(json: String?) -> Dictionary<String, AnyObject> { if json == nil { return Dictionary<String, AnyObject>() } var error:NSError? = nil if let jsonData = json!.dataUsingEncoding(NSUTF8StringEncoding) { if let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? Dictionary<String, AnyObject> { return jsonDic } } return Dictionary<String, AnyObject>() } /** Return an array representation for the json string :param: json The json string that will be converted :return: The array of dictionaries representation of the json */ public class func arrayFromJson<T where T:EVObject>(type:T, json: String?) -> [T] { if json == nil { return [T]() } var error:NSError? = nil if let jsonData = json!.dataUsingEncoding(NSUTF8StringEncoding) { if let jsonDic: [Dictionary<String, AnyObject>] = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [Dictionary<String, AnyObject>] { return jsonDic.map({T(dictionary: $0)}) } } return [T]() } /** Create a hashvalue for the object :param: theObject The object for what you want a hashvalue :return: the hashvalue for the object */ public class func hashValue(theObject: NSObject) -> Int { let (hasKeys, hasTypes) = toDictionary(theObject) return Int(map(hasKeys) {$1}.reduce(0) {(31 &* $0) &+ $1.hash}) } /** Get the swift Class type from a string :param: className The string representation of the class (name of the bundle dot name of the class) :return: The Class type */ public class func swiftClassTypeFromString(className: String) -> AnyClass! { if className.hasPrefix("_TtC") { return NSClassFromString(className) } var classStringName = className if className.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch) == nil { var appName = getCleanAppName() classStringName = "\(appName).\(className)" } return NSClassFromString(classStringName) } /** Get the app name from the 'Bundle name' and if that's empty, then from the 'Bundle identifier' otherwise we assume it's a EVReflection unit test and use that bundle identifier :return: A cleaned up name of the app. */ private class func getCleanAppName()-> String { var bundle = NSBundle.mainBundle() var appName = bundle.infoDictionary?["CFBundleName"] as? String ?? "" if appName == "" { if bundle.bundleIdentifier == nil { bundle = NSBundle(forClass: EVReflection().dynamicType) } appName = (split(bundle.bundleIdentifier!){$0 == "."}).last ?? "" } var cleanAppName = appName.stringByReplacingOccurrencesOfString(" ", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) return cleanAppName } /** Get the swift Class from a string :param: className The string representation of the class (name of the bundle dot name of the class) :return: The Class type */ public class func swiftClassFromString(className: String) -> NSObject! { if className == "NSObject" { return NSObject() } let x: AnyClass! = swiftClassTypeFromString(className) if let anyobjectype : AnyObject.Type = swiftClassTypeFromString(className) { if let nsobjectype : NSObject.Type = anyobjectype as? NSObject.Type { var nsobject: NSObject = nsobjectype() return nsobject } } return nil } /** Get the class name as a string from a swift class :param: theObject An object for whitch the string representation of the class will be returned :return: The string representation of the class (name of the bundle dot name of the class) */ public class func swiftStringFromClass(theObject: NSObject) -> String! { var appName = getCleanAppName() let classStringName: String = NSStringFromClass(theObject.dynamicType) let classWithoutAppName: String = classStringName.stringByReplacingOccurrencesOfString(appName + ".", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) if classWithoutAppName.rangeOfString(".") != nil { NSLog("Warning! Your Bundle name should be the name of your target (set it to $(PRODUCT_NAME))") return (split(classWithoutAppName){$0 == "."}).last! } return classWithoutAppName } /** Encode any object :param: theObject The object that we want to encode. :param: aCoder The NSCoder that will be used for encoding the object. */ public class func encodeWithCoder(theObject: NSObject, aCoder: NSCoder) { let (hasKeys, hasTypes) = toDictionary(theObject) for (key, value) in hasKeys { aCoder.encodeObject(value, forKey: key as! String) } } /** Decode any object :param: theObject The object that we want to decode. :param: aDecoder The NSCoder that will be used for decoding the object. */ public class func decodeObjectWithCoder(theObject: NSObject, aDecoder: NSCoder) { let (hasKeys, hasTypes) = toDictionary(theObject) for (key, value) in hasKeys { if aDecoder.containsValueForKey(key as! String) { var newValue: AnyObject? = aDecoder.decodeObjectForKey(key as! String) if !(newValue is NSNull) { if theObject.validateValue(&newValue, forKey: key as! String, error: nil) { theObject.setValue(newValue, forKey: key as! String) } } } } } /** Compare all fields of 2 objects :param: lhs The first object for the comparisson :param: rhs The second object for the comparisson :return: true if the objects are the same, otherwise false */ public class func areEqual(lhs: NSObject, rhs: NSObject) -> Bool { if swiftStringFromClass(lhs) != swiftStringFromClass(rhs) { return false; } let (lhsdict,_) = toDictionary(lhs) let (rhsdict,_) = toDictionary(rhs) for (key, value) in rhsdict { if let compareTo: AnyObject = lhsdict[key as! String] { if !compareTo.isEqual(value) { return false } } else { return false } } return true } /** Helper function to convert an Any to AnyObject :param: anyValue Something of type Any is converted to a type NSObject :return: The NSOBject that is created from the Any value plus the type of that value */ public class func valueForAny(parentObject:Any, key:String, anyValue: Any) -> (AnyObject, String) { var theValue = anyValue var valueType = "" let mi: MirrorType = reflect(theValue) if mi.disposition == .Optional { if mi.count == 0 { var subtype: String = "\(mi)" subtype = subtype.substringFromIndex((split(subtype) {$0 == "<"} [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) return (NSNull(), subtype) } theValue = mi[0].1.value valueType = "\(mi[0].1.valueType)" } else if mi.disposition == .Aggregate { //TODO: See if new Swift version can make using the EVRaw* protocols obsolete if let value = theValue as? EVRawString { return (value.rawValue, "\(mi.valueType)") } if let value = theValue as? EVRawInt { return (NSNumber(int: Int32(value.rawValue)), "\(mi.valueType)") } if let value = theValue as? EVRaw { if let returnValue = value.anyRawValue as? String { return (returnValue, "\(mi.valueType)") } } } else if mi.disposition == .IndexContainer { valueType = "\(mi.valueType)" if valueType.hasPrefix("Swift.Array<Swift.Optional<") { //TODO: See if new Swift version can make using the EVArrayConvertable protocol obsolete if let arrayConverter = parentObject as? EVArrayConvertable { let convertedValue = arrayConverter.convertArray(key, array: theValue) return (convertedValue, valueType) } else { println("An object with a property of type Array with optional objects should implement the EVArrayConvertable protocol.") } } } else { valueType = "\(mi.valueType)" } switch(theValue) { case let numValue as NSNumber: return (numValue, "NSNumber") case let doubleValue as Double: return (NSNumber(double: doubleValue), "NSNumber") case let floatValue as Float: return (NSNumber(float: floatValue), "NSNumber") case let longValue as Int64: return (NSNumber(longLong: longValue), "NSNumber") case let longValue as UInt64: return (NSNumber(unsignedLongLong: longValue), "NSNumber") case let intValue as Int32: return (NSNumber(int: intValue), "NSNumber") case let intValue as UInt32: return (NSNumber(unsignedInt: intValue), "NSNumber") case let intValue as Int16: return (NSNumber(short: intValue), "NSNumber") case let intValue as UInt16: return (NSNumber(unsignedShort: intValue), "NSNumber") case let intValue as Int8: return (NSNumber(char: intValue), "NSNumber") case let intValue as UInt8: return (NSNumber(unsignedChar: intValue), "NSNumber") case let intValue as Int: return (NSNumber(integer: intValue), "NSNumber") case let intValue as UInt: return (NSNumber(unsignedLong: intValue), "NSNumber") case let stringValue as String: return (stringValue as NSString, "NSString") case let boolValue as Bool: return (NSNumber(bool: boolValue), "NSNumber") case let anyvalue as NSObject: return (anyvalue, valueType) default: NSLog("ERROR: valueForAny unkown type \(theValue), type \(valueType)") return (NSNull(), "NSObject") // Could not happen } } }
mit
77be116c7977ce8dca6e3b392389191e
42.031599
712
0.596605
5.027362
false
false
false
false
strivingboy/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/Helper/CCSqlite/CCDataBase.swift
1
1243
// // CCDataBase.swift // CocoaChinaPlus // // Created by zixun on 15/9/27. // Copyright © 2015年 zixun. All rights reserved. // import Foundation import SQLite import ZXKit let CCDB = CCDataBase.sharedDB class CCDataBase: NSObject { static let sharedDB: CCDataBase = { return CCDataBase() }() private(set) var tableManager : CCTableManager! private(set) var connection : Connection! override init() { super.init() do{ //获取路径 let path = ZXPathForApplicationSupportResource(NSBundle.mainBundle().bundleIdentifier!) //创建文件 if !NSFileManager.defaultManager().fileExistsAtPath(path) { try NSFileManager.defaultManager().createDirectoryAtPath( path, withIntermediateDirectories: true, attributes: nil ) } //建立连接 self.connection = try Connection("\(path)/db.sqlite3") //建立数据库表 self.tableManager = CCTableManager(connection: self.connection) }catch { println("创建数据库失败!原因: \(error)") } } }
mit
85f7ea4f71ba60815fd48bc87d36db27
23.666667
99
0.568412
4.717131
false
false
false
false
nifty-swift/Nifty
Sources/randn.swift
2
6336
/*************************************************************************************************** * randn.swift * * This file provides normal random number functionality. * * Author: Philip Erickson * Creation Date: 11 Dec 2016 * * 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ /// Internal structure for generating normal random numbers. Makes use of UniformRandomGenerator in /// computing normal deviates /// /// Algorithm based on: /// Press, William H. "Numerical recipes 3rd edition: The art of scientific computing.", Cambridge /// university press, 2007. Chapter 7.3.9, pg 368-369. internal class NormalRandomGenerator { var mu: Double var sigma: Double var ugen: UniformRandomGenerator init(mu: Double, sigma: Double, ugen: UniformRandomGenerator) { self.mu = mu self.sigma = sigma self.ugen = ugen } func doub() -> Double { var u, v, x, y, q: Double repeat { u = self.ugen.doub() v = 1.7156 * (self.ugen.doub() - 0.5) x = u - 0.449871 y = abs(v) + 0.386595 q = x*x + y*(0.196*y - 0.25472*x) } while (q > 0.27597) && (q > 0.27846 || (v*v > -4.0*log(u)*u*u)) return self.mu + self.sigma*v/u } } // Global random number generator instance used for generation of uniform randoms, unless function // is called with the `threadSafe` option set. internal var g_NormalRandGen: NormalRandomGenerator? = nil //================================================================================================== // MARK: PUBLIC RANDN INTERFACE //================================================================================================== import Dispatch import Foundation /// Return a matrix of random numbers drawn from the specified normal distribution. /// /// - Note: If large amounts of random numbers are needed, it's more efficient to request one large /// matrix rather than many individual numbers. /// - Parameters: /// - rows: number of rows in matrix to generate /// - columns: number of columns in matrix to generate /// - mean: optionally specify a mean other than the default zero mean /// - std: optionally specify standard deviation other than the default unit /// - seed: optionally provide specific seed for generator. If threadSafe is set, this seed will /// not be applied to global generator, but to the temporary generator instance /// - threadSafe: if set to true, a new random generator instance will be created that will be /// be used and exist only for the duration of this call. Otherwise, global instance is used. public func randn(_ rows: Int, _ columns: Int, mean: Double = 0.0, std: Double = 1.0, seed: UInt64? = nil, threadSafe: Bool = false) -> Matrix<Double> { let totalSize = rows * columns precondition(rows > 0 && columns > 0, "Matrix dimensions must all be positive") precondition(std >= 0, "Standard deviation cannot be negative") // If not set to be thread safe, save time and use global generator. Otherwise, make new one. var curRandGen: NormalRandomGenerator if !threadSafe { // create or reseed global generator with given seed if let s = seed { let urg = UniformRandomGenerator(seed: s) curRandGen = NormalRandomGenerator(mu: mean, sigma: std, ugen: urg) g_UniformRandGen = urg g_NormalRandGen = curRandGen } // just use the current global generator if there is one, adjusting mean and std else if let gen = g_NormalRandGen { curRandGen = gen curRandGen.mu = mean curRandGen.sigma = std } // initialize global generator with default seed else { // Seed random number generator with all significant digits in current time. let urg = UniformRandomGenerator(seed: UInt64(Date().timeIntervalSince1970*1000000)) curRandGen = NormalRandomGenerator(mu: mean, sigma: std, ugen: urg) g_UniformRandGen = urg g_NormalRandGen = curRandGen } } else { if let ts = seed { let urg = UniformRandomGenerator(seed: ts) curRandGen = NormalRandomGenerator(mu: mean, sigma: std, ugen: urg) } else { threadLock.wait() let ts = threadSeed threadSeed = threadSeed.addingReportingOverflow(UInt64(Date().timeIntervalSince1970)).0 threadLock.signal() let urg = UniformRandomGenerator(seed: ts) curRandGen = NormalRandomGenerator(mu: mean, sigma: std, ugen: urg) } } // Grab as many normally distributed doubles as needed var randomData = [Double]() for _ in 0..<totalSize { randomData.append(curRandGen.doub()) } return Matrix(rows, columns, randomData) } public func randn(_ elements: Int, mean: Double = 0.0, std: Double = 1.0, seed: UInt64? = nil, threadSafe: Bool = false) -> Vector<Double> { let m = randn(1, elements, mean: mean, std: std, seed: seed, threadSafe: threadSafe) return Vector(m) } public func randn(mean: Double = 0.0, std: Double = 1.0, seed: UInt64? = nil, threadSafe: Bool = false) -> Double { let m = randn(1, 1, mean: mean, std: std, seed: seed, threadSafe: threadSafe) return m.data[0] } // Use this to atomically check and increment seed for thread-safe calls fileprivate var threadLock = DispatchSemaphore(value: 1) fileprivate var threadSeed = UInt64(Date().timeIntervalSince1970*2000000)
apache-2.0
852c55e8b8106c2dad1ca257ac7b388e
37.871166
107
0.604798
4.232465
false
false
false
false
exoplatform/exo-ios
Pods/Kingfisher/Sources/General/KF.swift
1
17579
// // KF.swift // Kingfisher // // Created by onevcat on 2020/09/21. // // Copyright (c) 2020 Wei Wang <[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. #if canImport(UIKit) import UIKit #endif #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit #endif #if canImport(WatchKit) import WatchKit #endif #if canImport(TVUIKit) import TVUIKit #endif /// A helper type to create image setting tasks in a builder pattern. /// Use methods in this type to create a `KF.Builder` instance and configure image tasks there. public enum KF { /// Creates a builder for a given `Source`. /// - Parameter source: The `Source` object defines data information from network or a data provider. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func source(_ source: Source?) -> KF.Builder { Builder(source: source) } /// Creates a builder for a given `Resource`. /// - Parameter resource: The `Resource` object defines data information like key or URL. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func resource(_ resource: Resource?) -> KF.Builder { source(resource?.convertToSource()) } /// Creates a builder for a given `URL` and an optional cache key. /// - Parameters: /// - url: The URL where the image should be downloaded. /// - cacheKey: The key used to store the downloaded image in cache. /// If `nil`, the `absoluteString` of `url` is used as the cache key. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func url(_ url: URL?, cacheKey: String? = nil) -> KF.Builder { source(url?.convertToSource(overrideCacheKey: cacheKey)) } /// Creates a builder for a given `ImageDataProvider`. /// - Parameter provider: The `ImageDataProvider` object contains information about the data. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func dataProvider(_ provider: ImageDataProvider?) -> KF.Builder { source(provider?.convertToSource()) } /// Creates a builder for some given raw data and a cache key. /// - Parameters: /// - data: The data object from which the image should be created. /// - cacheKey: The key used to store the downloaded image in cache. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func data(_ data: Data?, cacheKey: String) -> KF.Builder { if let data = data { return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey)) } else { return dataProvider(nil) } } } extension KF { /// A builder class to configure an image retrieving task and set it to a holder view or component. public class Builder { private let source: Source? #if os(watchOS) private var placeholder: KFCrossPlatformImage? #else private var placeholder: Placeholder? #endif public var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions) public let onFailureDelegate = Delegate<KingfisherError, Void>() public let onSuccessDelegate = Delegate<RetrieveImageResult, Void>() public let onProgressDelegate = Delegate<(Int64, Int64), Void>() init(source: Source?) { self.source = source } private var resultHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? { { switch $0 { case .success(let result): self.onSuccessDelegate(result) case .failure(let error): self.onFailureDelegate(error) } } } private var progressBlock: DownloadProgressBlock { { self.onProgressDelegate(($0, $1)) } } } } extension KF.Builder { #if !os(watchOS) /// Builds the image task request and sets it to an image view. /// - Parameter imageView: The image view which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to imageView: KFCrossPlatformImageView) -> DownloadTask? { imageView.kf.setImage( with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } /// Builds the image task request and sets it to an `NSTextAttachment` object. /// - Parameters: /// - attachment: The text attachment object which loads the task and should be set with the image. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to attachment: NSTextAttachment, attributedView: KFCrossPlatformView) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return attachment.kf.setImage( with: source, attributedView: attributedView, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #if canImport(UIKit) /// Builds the image task request and sets it to a button. /// - Parameters: /// - button: The button which loads the task and should be set with the image. /// - state: The button state to which the image should be set. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to button: UIButton, for state: UIControl.State) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setImage( with: source, for: state, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } /// Builds the image task request and sets it to the background image for a button. /// - Parameters: /// - button: The button which loads the task and should be set with the image. /// - state: The button state to which the image should be set. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func setBackground(to button: UIButton, for state: UIControl.State) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setBackgroundImage( with: source, for: state, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(UIKit) #if canImport(AppKit) && !targetEnvironment(macCatalyst) /// Builds the image task request and sets it to a button. /// - Parameter button: The button which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to button: NSButton) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setImage( with: source, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } /// Builds the image task request and sets it to the alternative image for a button. /// - Parameter button: The button which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func setAlternative(to button: NSButton) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setAlternateImage( with: source, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(AppKit) #endif // end of !os(watchOS) #if canImport(WatchKit) /// Builds the image task request and sets it to a `WKInterfaceImage` object. /// - Parameter interfaceImage: The watch interface image which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to interfaceImage: WKInterfaceImage) -> DownloadTask? { return interfaceImage.kf.setImage( with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(WatchKit) #if canImport(TVUIKit) /// Builds the image task request and sets it to a TV monogram view. /// - Parameter monogramView: The monogram view which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @available(tvOS 12.0, *) @discardableResult public func set(to monogramView: TVMonogramView) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return monogramView.kf.setImage( with: source, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(TVUIKit) } #if !os(watchOS) extension KF.Builder { #if os(iOS) || os(tvOS) /// Sets a placeholder which is used while retrieving the image. /// - Parameter placeholder: A placeholder to show while retrieving the image from its source. /// - Returns: A `KF.Builder` with changes applied. public func placeholder(_ placeholder: Placeholder?) -> Self { self.placeholder = placeholder return self } #endif /// Sets a placeholder image which is used while retrieving the image. /// - Parameter placeholder: An image to show while retrieving the image from its source. /// - Returns: A `KF.Builder` with changes applied. public func placeholder(_ image: KFCrossPlatformImage?) -> Self { self.placeholder = image return self } } #endif extension KF.Builder { #if os(iOS) || os(tvOS) /// Sets the transition for the image task. /// - Parameter transition: The desired transition effect when setting the image to image view. /// - Returns: A `KF.Builder` with changes applied. /// /// Kingfisher will use the `transition` to animate the image in if it is downloaded from web. /// The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. public func transition(_ transition: ImageTransition) -> Self { options.transition = transition return self } /// Sets a fade transition for the image task. /// - Parameter duration: The duration of the fade transition. /// - Returns: A `KF.Builder` with changes applied. /// /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web. /// The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. public func fade(duration: TimeInterval) -> Self { options.transition = .fade(duration) return self } #endif /// Sets whether keeping the existing image of image view while setting another image to it. /// - Parameter enabled: Whether the existing image should be kept. /// - Returns: A `KF.Builder` with changes applied. /// /// By setting this option, the placeholder image parameter of image view extension method /// will be ignored and the current image will be kept while loading or downloading the new image. /// public func keepCurrentImageWhileLoading(_ enabled: Bool = true) -> Self { options.keepCurrentImageWhileLoading = enabled return self } /// Sets whether only the first frame from an animated image file should be loaded as a single image. /// - Parameter enabled: Whether the only the first frame should be loaded. /// - Returns: A `KF.Builder` with changes applied. /// /// Loading an animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from an animated image. /// /// This option will be ignored if the target image is not animated image data. /// public func onlyLoadFirstFrame(_ enabled: Bool = true) -> Self { options.onlyLoadFirstFrame = enabled return self } /// Sets the image that will be used if an image retrieving task fails. /// - Parameter image: The image that will be used when something goes wrong. /// - Returns: A `KF.Builder` with changes applied. /// /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty) /// in place of requested one. It's useful when you don't want to show placeholder /// during loading time but wants to use some default image when requests will be failed. /// public func onFailureImage(_ image: KFCrossPlatformImage?) -> Self { options.onFailureImage = .some(image) return self } /// Enables progressive image loading with a specified `ImageProgressive` setting to process the /// progressive JPEG data and display it in a progressive way. /// - Parameter progressive: The progressive settings which is used while loading. /// - Returns: A `KF.Builder` with changes applied. public func progressiveJPEG(_ progressive: ImageProgressive? = .default) -> Self { options.progressiveJPEG = progressive return self } } // MARK: - Redirect Handler extension KF { /// Represents the detail information when a task redirect happens. It is wrapping necessary information for a /// `ImageDownloadRedirectHandler`. See that protocol for more information. public struct RedirectPayload { /// The related session data task when the redirect happens. It is /// the current `SessionDataTask` which triggers this redirect. public let task: SessionDataTask /// The response received during redirection. public let response: HTTPURLResponse /// The request for redirection which can be modified. public let newRequest: URLRequest /// A closure for being called with modified request. public let completionHandler: (URLRequest?) -> Void } }
lgpl-3.0
8d108ff32c34e0326f60fcede4e8d304
41.98044
116
0.662666
4.937921
false
false
false
false
plantain-00/demo-set
swift-demo/NewsCatcher/Ridge/Ridge/AttributesParser.swift
1
1383
// // AttributesParser.swift // Ridge // // Created by 姚耀 on 15/1/30. // Copyright (c) 2015年 姚耀. All rights reserved. // import Foundation class AttributesParser: ParserBase { override init(strings: [String], index: Int, endIndex: Int) { hasSlash = false super.init(strings: strings, index: index, endIndex: endIndex) } var attributes: [Attribute]? var hasSlash: Bool override func parse() { var meetEndOfAllAttributes = false do { skipSpaces() if strings[index] == StringStatic.slash && strings[index + 1] == StringStatic.largeThan { meetEndOfAllAttributes = true index += 2 hasSlash = true } else if strings[index] == StringStatic.largeThan { meetEndOfAllAttributes = true index++ } else { parseNextAttribute() } } while !meetEndOfAllAttributes && index < endIndex } private func parseNextAttribute() { let attributeParser = AttributeParser(strings: strings, index: index, endIndex: endIndex) attributeParser.parse() if attributes == nil { attributes = [] } attributes!.append(attributeParser.attribute!) index = attributeParser.index } }
mit
ee5df186fa31d498893f4d7a8ffe09d4
27.625
97
0.568099
4.622896
false
false
false
false
muukii0803/LightRoom
Playgrounds/Main.playground/Pages/Struct.xcplaygroundpage/Contents.swift
2
820
import UIKit import LightRoom let image1 = CIImage(image: [#Image(imageLiteral: "sample.jpg")#])! let image2 = CIImage(image: [#Image(imageLiteral: "sample3.jpg")#])! let color = CIColor(red: 1, green: 1, blue: 1, alpha: 0.1) let blendImage = LightRoom.Generator.ConstantColorGenerator(cropRect: image1.extent, color: color) let addition = LightRoom.CompositeOperation.AdditionCompositing() let overlay = LightRoom.CompositeOperation.OverlayBlendMode() let colorControl = LightRoom.ColorAdjustment.ColorControls(saturation: 0.5, brightness: 0, contrast: 1) let colorControl2 = LightRoom.ColorAdjustment.ColorControls(saturation: 0, brightness: 0, contrast: 1) image1 >>> colorControl --* addition blendImage >>> addition --* overlay image2 >>> colorControl2 >>> overlay overlay.outputImage
mit
b68cd00caa190bab945e54110fad8646
42.157895
103
0.74878
3.831776
false
false
false
false
emilstahl/swift
test/attr/attr_availability_osx.swift
13
2814
// RUN: %swift -parse -verify -parse-stdlib -target x86_64-apple-macosx10.10 %s @available(OSX, introduced=10.5, deprecated=10.8, obsoleted=10.9, message="you don't want to do that anyway") func doSomething() { } // expected-note @-1{{'doSomething()' was obsoleted in OS X 10.9}} doSomething() // expected-error{{'doSomething()' is unavailable: you don't want to do that anyway}} // Preservation of major.minor.micro @available(OSX, introduced=10.5, deprecated=10.8, obsoleted=10.9.1) func doSomethingElse() { } // expected-note @-1{{'doSomethingElse()' was obsoleted in OS X 10.9.1}} doSomethingElse() // expected-error{{'doSomethingElse()' is unavailable}} // Preservation of minor-only version @available(OSX, introduced=8.0, deprecated=8.5, obsoleted=10) func doSomethingReallyOld() { } // expected-note @-1{{'doSomethingReallyOld()' was obsoleted in OS X 10}} doSomethingReallyOld() // expected-error{{'doSomethingReallyOld()' is unavailable}} // Test deprecations in 10.10 and later @available(OSX, introduced=10.5, deprecated=10.10, message="Use another function") func deprecatedFunctionWithMessage() { } deprecatedFunctionWithMessage() // expected-warning{{'deprecatedFunctionWithMessage()' was deprecated in OS X 10.10: Use another function}} @available(OSX, introduced=10.5, deprecated=10.10) func deprecatedFunctionWithoutMessage() { } deprecatedFunctionWithoutMessage() // expected-warning{{'deprecatedFunctionWithoutMessage()' was deprecated in OS X 10.10}} @available(OSX, introduced=10.5, deprecated=10.10, message="Use BetterClass instead") class DeprecatedClass { } func functionWithDeprecatedParameter(p: DeprecatedClass) { } // expected-warning{{'DeprecatedClass' was deprecated in OS X 10.10: Use BetterClass instead}} @available(OSX, introduced=10.5, deprecated=10.11, message="Use BetterClass instead") class DeprecatedClassIn10_11 { } // Elements deprecated later than the minimum deployment target (which is 10.10, in this case) should not generate warnings func functionWithDeprecatedLaterParameter(p: DeprecatedClassIn10_11) { } // Unconditional platform unavailability @available(OSX, unavailable) func doSomethingNotOnOSX() { } // expected-note @-1{{'doSomethingNotOnOSX()' has been explicitly marked unavailable here}} doSomethingNotOnOSX() // expected-error{{'doSomethingNotOnOSX()' is unavailable}} @available(iOS, unavailable) func doSomethingNotOniOS() { } doSomethingNotOniOS() // okay // Unconditional platform deprecation @available(OSX, deprecated) func doSomethingDeprecatedOnOSX() { } doSomethingDeprecatedOnOSX() // expected-warning{{'doSomethingDeprecatedOnOSX()' is deprecated on OS X}} @available(iOS, deprecated) func doSomethingDeprecatedOniOS() { } doSomethingDeprecatedOniOS() // okay
apache-2.0
96b5c4a41c935efd5d35c1a2e657b3d6
37.547945
155
0.749467
3.96897
false
false
false
false
OrielBelzer/StepCoin
HDAugmentedRealityDemo/SettingsViewController.swift
1
2803
// // SettingsViewController.swift // StepCoin // // Created by Oriel Belzer on 1/7/2017. // Copyright © 2016 StepCoin. All rights reserved. // import UIKit import PopupDialog class SettingsViewController: UIViewController { @IBOutlet weak var debugModeSwitch: UISwitch! @IBOutlet weak var backButton: UIButton! let debugPasscode = "$1Eli70Oriel25!" let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (defaults.bool(forKey: "debugMode")) { self.debugModeSwitch.setOn(true, animated: true) } else { self.debugModeSwitch.setOn(false, animated: true) } } func switchIsChanged(mySwitch: UISwitch) { if mySwitch.isOn { print("debug switch is on") } else { print("debug switch is off") } } @IBAction func backButton(sender: UIButton) { self.dismiss(animated: true) { } //self.performSegue(withIdentifier: "MoveToProfileFromSettings", sender: self) } @IBAction func debugModeButtonTapped(sender: AnyObject) { if debugModeSwitch.isOn { print("Debug mode switched to on") let DebugModePassCodePopupView = DebugPasscodePopupViewController(nibName: "DebugPasscodePopupViewController", bundle: nil) let popup = PopupDialog(viewController: DebugModePassCodePopupView, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true) let okButton = DefaultButton(title: "OK") { if (DebugModePassCodePopupView.debugPasscodeTextField.text == self.debugPasscode) { //App is in debug mode - BE CARFUL WITH ADDING COINS !!!!! self.defaults.set(true, forKey: "debugMode") } else { self.debugModeSwitch.setOn(false, animated: true) let alertController = UIAlertController(title: "Wrong Passcode", message: "Plase try re-enter your debug mode passcode", preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) self.defaults.set(false, forKey: "debugMode") } } popup.addButtons([okButton]) present(popup, animated: true, completion: nil) } else { print("Debug mode switched to off") defaults.set(false, forKey: "debugMode") } } }
mit
239dafe089708fb102f192a048d79834
34.025
164
0.605996
4.814433
false
false
false
false
thomaskamps/SlideFeedback
SlideFeedback/Pods/Socket.IO-Client-Swift/Source/SocketExtensions.swift
4
4795
// // SocketExtensions.swift // Socket.IO-Client-Swift // // Created by Erik Little on 7/1/2016. // // 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 enum JSONError : Error { case notArray case notNSDictionary } extension Array { func toJSON() throws -> Data { return try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0)) } } extension CharacterSet { static var allowedURLCharacterSet: CharacterSet { return CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]\" {}").inverted } } extension NSDictionary { private static func keyValueToSocketIOClientOption(key: String, value: Any) -> SocketIOClientOption? { switch (key, value) { case let ("connectParams", params as [String: Any]): return .connectParams(params) case let ("cookies", cookies as [HTTPCookie]): return .cookies(cookies) case let ("extraHeaders", headers as [String: String]): return .extraHeaders(headers) case let ("forceNew", force as Bool): return .forceNew(force) case let ("forcePolling", force as Bool): return .forcePolling(force) case let ("forceWebsockets", force as Bool): return .forceWebsockets(force) case let ("handleQueue", queue as DispatchQueue): return .handleQueue(queue) case let ("log", log as Bool): return .log(log) case let ("logger", logger as SocketLogger): return .logger(logger) case let ("nsp", nsp as String): return .nsp(nsp) case let ("path", path as String): return .path(path) case let ("reconnects", reconnects as Bool): return .reconnects(reconnects) case let ("reconnectAttempts", attempts as Int): return .reconnectAttempts(attempts) case let ("reconnectWait", wait as Int): return .reconnectWait(wait) case let ("secure", secure as Bool): return .secure(secure) case let ("security", security as SSLSecurity): return .security(security) case let ("selfSigned", selfSigned as Bool): return .selfSigned(selfSigned) case let ("sessionDelegate", delegate as URLSessionDelegate): return .sessionDelegate(delegate) case let ("voipEnabled", enable as Bool): return .voipEnabled(enable) default: return nil } } func toSocketConfiguration() -> SocketIOClientConfiguration { var options = [] as SocketIOClientConfiguration for (rawKey, value) in self { if let key = rawKey as? String, let opt = NSDictionary.keyValueToSocketIOClientOption(key: key, value: value) { options.insert(opt) } } return options } } extension String { func toArray() throws -> [Any] { guard let stringData = data(using: .utf16, allowLossyConversion: false) else { return [] } guard let array = try JSONSerialization.jsonObject(with: stringData, options: .mutableContainers) as? [Any] else { throw JSONError.notArray } return array } func toNSDictionary() throws -> NSDictionary { guard let binData = data(using: .utf16, allowLossyConversion: false) else { return [:] } guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? NSDictionary else { throw JSONError.notNSDictionary } return json } func urlEncode() -> String? { return addingPercentEncoding(withAllowedCharacters: .allowedURLCharacterSet) } }
unlicense
c2f5f2164aeed9fa16da35ec6988f668
37.36
123
0.649635
4.775896
false
false
false
false
vnu/Flickz
Flickz/HTTPClient.swift
1
4192
// // HTTPClient.swift // Flickz // // Created by Vinu Charanya on 2/6/16. // Copyright © 2016 vnu. All rights reserved. // import UIKit import AFNetworking class HTTPClient { //moviesDB API KEY static let apiKey: String = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let baseUrl = "https://api.themoviedb.org/3/movie/" private let params = ["api_key": apiKey] func buildUrl(fetchType: String) -> String{ return "\(baseUrl)\(fetchType)?api_key=\(HTTPClient.apiKey)" } //Fetch using AFNetworking 3.0 AFHTTPSessionManager func fetch(resourceUrl:String, successCallback: ([Movie]) -> Void, error: ((NSError?) -> Void)?) { let manager = AFHTTPSessionManager(); //TODO: Figure out what progress is manager.GET(resourceUrl, parameters: params, progress: nil, success: { (operation ,responseObject) -> Void in if let results = responseObject!["results"] as? NSArray { var movies: [Movie] = [] for result in results as! [NSDictionary] { movies.append(Movie(jsonResult: result)) } successCallback(movies) } }, failure: { (operation, requestError) -> Void in if let errorCallback = error { errorCallback(requestError) } }) } //Fetch using NSURL SESSION (Not used. Keeping here for reference) func fetchNSURLSession(fetchUrl: String){ let url = NSURL(string: fetchUrl) let request = NSURLRequest(URL: url!) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:nil, delegateQueue:NSOperationQueue.mainQueue() ) let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (dataOrNil, response, error) in if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { NSLog("response: \(responseDictionary)") } } }); task.resume() } //TODO: Refactor this and move the fetch logic to HTTPClient func fetchPosterImage(movie: Movie, movieDetailPosterImage: UIImageView){ if let lowPosterURL = movie.lowResPosterURL(){ let lowResPosterURLRequest = NSURLRequest(URL: lowPosterURL) movieDetailPosterImage.setImageWithURLRequest(lowResPosterURLRequest, placeholderImage: nil, success: {(lowResPosterURLRequest, lowResPosterURLResponse, lowResPosterImage) -> Void in movieDetailPosterImage.alpha = 0.0 movieDetailPosterImage.image = lowResPosterImage UIView.animateWithDuration(0.3, animations: {() -> Void in movieDetailPosterImage.alpha = 1.0 }, completion: {(success) -> Void in if let highPosterURL = movie.highResPosterURL(){ let highResPosterURLRequest = NSURLRequest(URL: highPosterURL) movieDetailPosterImage.setImageWithURLRequest(highResPosterURLRequest, placeholderImage: nil, success: {(highResPosterURLRequest, highResPosterURLResponse, highResPosterImage) -> Void in movieDetailPosterImage.image = highResPosterImage; }, failure: { (highResPosterURLRequest, highResPosterURLResponse, error) -> Void in NSLog("High Res Image Request failed") }) } }) }, failure: { (lowResPosterURLRequest, lowResPosterURLResponse, error) -> Void in NSLog("Low Res Image Request failed") }) } } //Fetch Image }
mit
f54a4cf148e08c9b80c8af0ede88db3d
40.92
128
0.563111
5.471279
false
false
false
false
corchwll/amos-ss15-proj5_ios
MobileTimeAccounting/BusinessLogic/CSV/CSVBuilder.swift
1
4545
/* Mobile Time Accounting Copyright (C) 2015 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation class CSVBuilder { let SEPERATOR = ";" var rows = [[String]]() /* Adds a new row at the end of the future csv file. @methodtype Setter @pre Row items must be valid strings for csv file @post New row is added */ func addRow(row: String...) { rows.append(row) } /* Sets a new row at a given row index. @methodtype Setter @pre Row items must be valid strings for csv file @post New row is set at given index */ func setRow(rowIndex: Int, row: String...) { AppendEmptyRowsIfNeeded(rowIndex) rows[rowIndex] = row } /* Adds a new row item at the end of a given row. @methodtype Setter @pre Row item must be a valid strings for csv file @post New row item is added */ func addRowItem(rowIndex: Int, rowItem: String) { AppendEmptyRowsIfNeeded(rowIndex) rows[rowIndex].append(rowItem) } /* Sets a new row item at a given index in a given row. @methodtype Setter @pre Row items must be valid strings for csv file @post New row item is set */ func setRowItem(rowIndex: Int, rowItemIndex: Int, rowItem: String) { AppendEmptyRowsIfNeeded(rowIndex) AppendEmptyRowItemsIfNeeded(rowIndex, toIndex: rowItemIndex) rows[rowIndex][rowItemIndex] = rowItem } /* Adds empty rows(empty string arrays) up to a given index if there aren't already rows. @methodtype Command @pre Rows must be nil @post Empty rows are added */ private func AppendEmptyRowsIfNeeded(toIndex: Int) { for var index = rows.count; index <= toIndex; ++index { rows.append([String]()) } } /* Adds empty row items (strings) up to a given index in a row, but only if there aren't already row items set. @methodtype Command @pre Row items must be nil @post Empty row items are added */ private func AppendEmptyRowItemsIfNeeded(rowIndex: Int, toIndex: Int) { for var index = rows[rowIndex].count; index <= toIndex; ++index { rows[rowIndex].append("") } } /* Builds the csv string by converting rows into a csv format seperated by colons. @methodtype Helper @pre Rows are set @post Returns valid csv string */ func build()->String { var csvString = "" let columnCount = getColumnCount() for row in rows { csvString += "\(getCSVRow(row, size: columnCount))\n" } return csvString } /* Returns total column count, determined by the longest row in all rows. @methodtype Helper @pre Rows are set @post Returns total column count */ private func getColumnCount()->Int { var maxCount = 0 for row in rows { maxCount = row.count > maxCount ? row.count : maxCount } return maxCount } /* Returns a row converted into a csv string. @methodtype Convertion @pre Size must be greater than or equal current row size @post Returns row as csv string */ private func getCSVRow(row: [String], size: Int)->String { var csvRow = "" for column in 0..<size { csvRow += column < row.count ? "\(row[column])" + SEPERATOR : SEPERATOR } csvRow.removeAtIndex(csvRow.endIndex.predecessor()) return csvRow } }
agpl-3.0
c24b2839cf4adcd9b3e988afda0fd13f
25.277457
116
0.581298
4.739312
false
false
false
false
frimfram/Tabber
tips/AppDelegate.swift
1
2766
// // AppDelegate.swift // tips // // Created by Jean Ro on 12/14/14. // Copyright (c) 2014 codepath. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var lastBillAmount: String? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. var navigationBarAppearance = UINavigationBar.appearance() navigationBarAppearance.translucent = true navigationBarAppearance.tintColor = uicolorFromHex(0x000000) navigationBarAppearance.barTintColor = UIColor(red: 0, green: 1, blue: 110/256, alpha: 1) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func uicolorFromHex(rgbValue:UInt32)->UIColor{ let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:1.0) } }
mit
3dc69ea8e345b503c82a331727ceaa71
46.689655
285
0.73102
5.160448
false
false
false
false
richeterre/jumu-nordost-ios
JumuNordost/Stores/Store.swift
1
3589
// // Store.swift // JumuNordost // // Created by Martin Richter on 13/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import Argo import ReactiveCocoa import Result class Store: StoreType { private let baseURL: NSURL private let session: NSURLSession private let errorDomain = "StoreError" private enum StoreError: Int { case ParsingError } // MARK: - Lifecycle required init(baseURL: NSURL, apiKey: String) { self.baseURL = baseURL let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() sessionConfiguration.HTTPAdditionalHeaders = [ "X-Api-Key": apiKey ] self.session = NSURLSession(configuration: sessionConfiguration) } // MARK: - Contests func fetchContests(currentOnly currentOnly: Bool, timetablesPublic: Bool) -> SignalProducer<[Contest], NSError> { let queryItems = [ NSURLQueryItem(name: "current_only", value: queryValueForBool(currentOnly)), NSURLQueryItem(name: "timetables_public", value: queryValueForBool(timetablesPublic)) ] let request = requestForPath("contests", queryItems: queryItems) return session.rac_dataWithRequest(request) .attemptMap(decodeModels) } // MARK: - Performances func fetchPerformances(contest contest: Contest, venue: Venue, day: ContestDay) -> SignalProducer<[Performance], NSError> { let dateString = "\(day.year)-\(day.month)-\(day.day)" let queryItems = [ NSURLQueryItem(name: "venue_id", value: venue.id), NSURLQueryItem(name: "date", value: dateString) ] let path = String(format: "contests/%@/performances", arguments: [contest.id]) let request = requestForPath(path, queryItems: queryItems) return session.rac_dataWithRequest(request) .attemptMap(decodeModels) } func fetchPerformances(contest contest: Contest, contestCategory: ContestCategory, resultsPublic: Bool) -> SignalProducer<[Performance], NSError> { let queryItems = [ NSURLQueryItem(name: "contest_category_id", value: contestCategory.id), NSURLQueryItem(name: "results_public", value: queryValueForBool(resultsPublic)) ] let path = String(format: "contests/%@/performances", arguments: [contest.id]) let request = requestForPath(path, queryItems: queryItems) return session.rac_dataWithRequest(request) .attemptMap(decodeModels) } // MARK: - Private Helpers private func requestForPath(path: String, queryItems: [NSURLQueryItem] = []) -> NSURLRequest { let url = NSURL(string: path, relativeToURL: baseURL)! let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)! components.queryItems = queryItems return NSURLRequest(URL: components.URL!) } private func decodeModels<Model: Decodable where Model == Model.DecodedType>(data data: NSData, response: NSURLResponse) -> Result<[Model], NSError> { if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []), models: [Model] = decode(json) { return .Success(models) } else { let error = NSError(domain: errorDomain, code: StoreError.ParsingError.rawValue, userInfo: nil) return .Failure(error) } } } /// Returns an API-compatible value for the given boolean. func queryValueForBool(bool: Bool) -> String { return bool ? "1" : "0" }
mit
54722389abf3e86999f801127317b08e
33.171429
154
0.661371
4.564885
false
true
false
false
burhanaksendir/animated-tab-bar
RAMAnimatedTabBarController/Animations/TransitionAniamtions/RAMTransitionItemAnimation.swift
27
3365
// RAMTransitionItemAniamtions.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class RAMTransitionItemAniamtions : RAMItemAnimation { var transitionOptions : UIViewAnimationOptions! override init() { super.init() transitionOptions = UIViewAnimationOptions.TransitionNone } override func playAnimation(icon : UIImageView, textLabel : UILabel) { selectedColor(icon, textLabel: textLabel) UIView.transitionWithView(icon, duration: NSTimeInterval(duration), options: transitionOptions, animations: { }, completion: { _ in }) } override func deselectAnimation(icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor) { if let iconImage = icon.image { let renderImage = iconImage.imageWithRenderingMode(.AlwaysOriginal) icon.image = renderImage textLabel.textColor = defaultTextColor } } override func selectedState(icon : UIImageView, textLabel : UILabel) { selectedColor(icon, textLabel: textLabel) } func selectedColor(icon : UIImageView, textLabel : UILabel) { if let iconImage = icon.image where iconSelectedColor != nil { let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate) icon.image = renderImage icon.tintColor = iconSelectedColor } textLabel.textColor = textSelectedColor } } class RAMFlipLeftTransitionItemAniamtions : RAMTransitionItemAniamtions { override init() { super.init() transitionOptions = UIViewAnimationOptions.TransitionFlipFromLeft } } class RAMFlipRightTransitionItemAniamtions : RAMTransitionItemAniamtions { override init() { super.init() transitionOptions = UIViewAnimationOptions.TransitionFlipFromRight } } class RAMFlipTopTransitionItemAniamtions : RAMTransitionItemAniamtions { override init() { super.init() transitionOptions = UIViewAnimationOptions.TransitionFlipFromTop } } class RAMFlipBottomTransitionItemAniamtions : RAMTransitionItemAniamtions { override init() { super.init() transitionOptions = UIViewAnimationOptions.TransitionFlipFromBottom } }
mit
fc563d5057c86073c5d5bda14e1c11e6
30.745283
117
0.719168
5.137405
false
false
false
false