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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
novi/todoapi-example
|
todoapi/todoapi/main.swift
|
1
|
817
|
import MySQL
import Nest
import Inquiline
import Kunugi
// Provide DB options as following in Constants.swift
/*
struct DBOptions: ConnectionOption {
let host: String = "db.host.example"
let port: Int = 3306
let user: String = ""
let password: String = ""
let database: String = "test"
}
*/
let app = App()
app.use(BodyParser())
// List: http --verbose "localhost:3000/todo?count=100"
// Create: http --verbose localhost:3000/todo title=Hello
app.use( Route("/todo", TodoListController()) )
// Get: http --verbose localhost:3000/todo/1
// Put: http --verbose PUT localhost:3000/todo/1 title=World done:=false
// Delete: http --verbose DELETE localhost:3000/todo/1
app.use( Route("/todo/:id", TodoController()) )
app.prepare()
print("listening...")
serve(3000, app: app.application)
|
mit
|
ddd4d30479aa39f766de00fc97c215c8
| 18.926829 | 72 | 0.689106 | 3.376033 | false | false | false | false |
volodg/iAsync.cache
|
Pods/ReactiveKit/Sources/Optional.swift
|
16
|
1662
|
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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 protocol OptionalProtocol {
associatedtype Wrapped
var _unbox: Optional<Wrapped> { get }
init(nilLiteral: ())
init(_ some: Wrapped)
}
extension Optional: OptionalProtocol {
public var _unbox: Optional<Wrapped> {
return self
}
}
func ==<O: OptionalProtocol>(lhs: O, rhs: O) -> Bool
where O.Wrapped: Equatable {
return lhs._unbox == rhs._unbox
}
func !=<O: OptionalProtocol>(lhs: O, rhs: O) -> Bool
where O.Wrapped: Equatable {
return !(lhs == rhs)
}
|
mit
|
facd824bc90b366c58206ec3f5f5bd94
| 35.130435 | 81 | 0.720818 | 4.103704 | false | false | false | false |
SoneeJohn/WWDC
|
ConfCore/DateAdapter.swift
|
1
|
1261
|
//
// DateAdapter.swift
// WWDC
//
// Created by Guilherme Rambo on 07/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
public let ConfCoreDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
final class DateAdapter: Adapter {
typealias InputType = String
typealias OutputType = Date
func adapt(_ input: String) -> Result<Date, AdapterError> {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en-US")
formatter.timeZone = TimeZone.current
if let date = formatter.date(from: input) {
return .success(date)
} else {
return .error(.invalidData)
}
}
}
final class DateTimeAdapter: Adapter {
typealias InputType = String
typealias OutputType = Date
func adapt(_ input: String) -> Result<Date, AdapterError> {
let formatter = DateFormatter()
formatter.dateFormat = ConfCoreDateFormat
formatter.locale = Locale(identifier: "en-US")
formatter.timeZone = TimeZone.current
if let date = formatter.date(from: input) {
return .success(date)
} else {
return .error(.invalidData)
}
}
}
|
bsd-2-clause
|
6f4a5f2204f52d2a37e6c4a22049d675
| 25.808511 | 63 | 0.628571 | 4.329897 | false | false | false | false |
GreatfeatServices/gf-mobile-app
|
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/RxCocoa.swift
|
37
|
4029
|
//
// RxCocoa.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if os(iOS)
import UIKit
#endif
/// RxCocoa errors.
public enum RxCocoaError
: Swift.Error
, CustomDebugStringConvertible {
/// Unknown error has occurred.
case unknown
/// Invalid operation was attempted.
case invalidOperation(object: Any)
/// Items are not yet bound to user interface but have been requested.
case itemsNotYetBound(object: Any)
/// Invalid KVO Path.
case invalidPropertyName(object: Any, propertyName: String)
/// Invalid object on key path.
case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String)
/// Error during swizzling.
case errorDuringSwizzling
/// Casting error.
case castingError(object: Any, targetType: Any.Type)
}
// MARK: Debug descriptions
extension RxCocoaError {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error occurred."
case let .invalidOperation(object):
return "Invalid operation was attempted on `\(object)`."
case let .itemsNotYetBound(object):
return "Data source is set, but items are not yet bound to user interface for `\(object)`."
case let .invalidPropertyName(object, propertyName):
return "Object `\(object)` dosn't have a property named `\(propertyName)`."
case let .invalidObjectOnKeyPath(object, sourceObject, propertyName):
return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`."
case .errorDuringSwizzling:
return "Error during swizzling."
case .castingError(let object, let targetType):
return "Error casting `\(object)` to `\(targetType)`"
}
}
}
// MARK: Error binding policies
func bindingErrorToInterface(_ error: Swift.Error) {
let error = "Binding error to UI: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
}
// MARK: Abstract methods
func rxAbstractMethodWithMessage(_ message: String) -> Swift.Never {
rxFatalError(message)
}
func rxAbstractMethod() -> Swift.Never {
rxFatalError("Abstract method")
}
// MARK: casts or fatal error
// workaround for Swift compiler bug, cheers compiler team :)
func castOptionalOrFatalError<T>(_ value: Any?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOrFatalError<T>(_ value: AnyObject!, message: String) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError(message)
}
return result
}
func castOrFatalError<T>(_ value: Any!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError("Failure converting from \(value) to \(T.self)")
}
return result
}
// MARK: Error messages
let dataSourceNotSet = "DataSource not set"
let delegateNotSet = "Delegate not set"
// MARK: Shared with RxSwift
#if !RX_NO_MODULE
func rxFatalError(_ lastMessage: String) -> Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
#endif
|
apache-2.0
|
6f978b234e0ccfde377a4a8f01b533b9
| 26.216216 | 115 | 0.66708 | 4.373507 | false | false | false | false |
Harley-xk/Chrysan
|
Chrysan/Classes/Extensions.swift
|
1
|
947
|
//
// Extensions.swift
// Chrysan
//
// Created by Harley on 2016/11/14.
//
//
import Foundation
import UIKit
public extension UIView {
private struct AssociatedKeys {
static var chrysanViewKey = "Chrysan.ChrysanKey"
}
var chrysan: ChrysanView {
get {
var hud = objc_getAssociatedObject(self, &AssociatedKeys.chrysanViewKey) as? ChrysanView
if hud == nil {
hud = ChrysanView.chrysan(withView: self)
self.chrysan = hud!
}
return hud!
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.chrysanViewKey, newValue as ChrysanView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
public extension UIViewController {
var chrysan: ChrysanView {
get {
return view.chrysan
}
set {
view.chrysan = newValue
}
}
}
|
mit
|
f75916e81473debd8089264413dc4e1b
| 19.148936 | 135 | 0.556494 | 4.384259 | false | false | false | false |
dreamsxin/swift
|
test/Parse/type_expr.swift
|
3
|
6710
|
// RUN: %target-parse-verify-swift
// Types in expression contexts must be followed by a member access or
// constructor call.
struct Foo {
struct Bar {
init() {}
static var prop: Int = 0
static func meth() {}
func instMeth() {}
}
init() {}
static var prop: Int = 0
static func meth() {}
func instMeth() {}
}
protocol Zim {
associatedtype Zang
init()
// TODO class var prop: Int { get }
static func meth() {} // expected-error{{protocol methods may not have bodies}}
func instMeth() {} // expected-error{{protocol methods may not have bodies}}
}
protocol Bad {
init() {} // expected-error{{protocol initializers may not have bodies}}
}
struct Gen<T> {
struct Bar { // expected-error{{nested in generic type}}
init() {}
static var prop: Int { return 0 }
static func meth() {}
func instMeth() {}
}
init() {}
static var prop: Int { return 0 }
static func meth() {}
func instMeth() {}
}
func unqualifiedType() {
_ = Foo.self
_ = Foo.self
_ = Foo()
_ = Foo.prop
_ = Foo.meth
let _ : () = Foo.meth()
_ = Foo.instMeth
_ = Foo // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{10-10=()}} expected-note{{use '.self'}} {{10-10=.self}}
_ = Foo.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{11-22=self}}
_ = Bad // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}{{10-10=.self}}
}
func qualifiedType() {
_ = Foo.Bar.self
let _ : Foo.Bar.Type = Foo.Bar.self
let _ : Foo.Protocol = Foo.self // expected-error{{cannot use 'Protocol' with non-protocol type 'Foo'}}
_ = Foo.Bar()
_ = Foo.Bar.prop
_ = Foo.Bar.meth
let _ : () = Foo.Bar.meth()
_ = Foo.Bar.instMeth
_ = Foo.Bar // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{14-14=()}} expected-note{{use '.self'}} {{14-14=.self}}
_ = Foo.Bar.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{15-26=self}}
}
/* TODO allow '.Type' in expr context
func metaType() {
let ty = Foo.Type.self
let metaTy = Foo.Type.self
let badTy = Foo.Type
let badMetaTy = Foo.Type.dynamicType
}
*/
func genType() {
_ = Gen<Foo>.self
_ = Gen<Foo>()
_ = Gen<Foo>.prop
_ = Gen<Foo>.meth
let _ : () = Gen<Foo>.meth()
_ = Gen<Foo>.instMeth
// Misparses because generic parameter disambiguation rejects '>' not
// followed by '.' or '('
_ = Gen<Foo> // expected-error{{not a postfix unary operator}}
_ = Gen<Foo>.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{16-27=self}}
}
func genQualifiedType() {
_ = Gen<Foo>.Bar.self
_ = Gen<Foo>.Bar()
_ = Gen<Foo>.Bar.prop
_ = Gen<Foo>.Bar.meth
let _ : () = Gen<Foo>.Bar.meth()
_ = Gen<Foo>.Bar.instMeth
_ = Gen<Foo>.Bar // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{19-19=()}} expected-note{{use '.self'}} {{19-19=.self}}
_ = Gen<Foo>.Bar.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{20-31=self}}
}
func archetype<T: Zim>(_: T) {
_ = T.self
_ = T()
// TODO let prop = T.prop
_ = T.meth
let _ : () = T.meth()
_ = T // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{8-8=()}} expected-note{{use '.self'}} {{8-8=.self}}
_ = T.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{9-20=self}}
}
func assocType<T: Zim where T.Zang: Zim>(_: T) {
_ = T.Zang.self
_ = T.Zang()
// TODO _ = T.Zang.prop
_ = T.Zang.meth
let _ : () = T.Zang.meth()
_ = T.Zang // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{13-13=()}} expected-note{{use '.self'}} {{13-13=.self}}
_ = T.Zang.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{14-25=self}}
}
class B {
class func baseMethod() {}
}
class D: B {
class func derivedMethod() {}
}
func derivedType() {
let _: B.Type = D.self
_ = D.baseMethod
let _ : () = D.baseMethod()
let _: D.Type = D.self
_ = D.derivedMethod
let _ : () = D.derivedMethod()
let _: B.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}}
let _: D.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}}
let _: D.Type.Type = D.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{26-37=self}}
}
// Referencing a nonexistent member or constructor should not trigger errors
// about the type expression.
func nonexistentMember() {
let cons = Foo("this constructor does not exist") // expected-error{{argument passed to call that takes no arguments}}
let prop = Foo.nonexistent // expected-error{{type 'Foo' has no member 'nonexistent'}}
let meth = Foo.nonexistent() // expected-error{{type 'Foo' has no member 'nonexistent'}}
}
protocol P {}
func meta_metatypes() {
let _: P.Protocol = P.self
_ = P.Type.self
_ = P.Protocol.self
_ = P.Protocol.Protocol.self // expected-error{{cannot use 'Protocol' with non-protocol type 'P.Protocol'}}
_ = P.Protocol.Type.self
_ = B.Type.self
}
// https://bugs.swift.org/browse/SR-502
func testFunctionCollectionTypes() {
_ = [(Int) -> Int]()
_ = [(Int, Int) -> Int]()
_ = [(x: Int, y: Int) -> Int]()
// Make sure associativity is correct
let a = [(Int) -> (Int) -> Int]()
let b: Int = a[0](5)(4)
_ = [String: (Int) -> Int]()
_ = [String: (Int, Int) -> Int]()
_ = [1 -> Int]() // expected-error{{expected type before '->'}}
_ = [Int -> 1]() // expected-error{{expected type after '->'}}
// Should parse () as void type when before or after arrow
_ = [() -> Int]()
_ = [(Int) -> ()]()
_ = [(Int) throws -> Int]()
_ = [(Int) -> throws Int]() // expected-error{{'throws' may only occur before '->'}}
_ = [Int throws Int]() // expected-error{{'throws' may only occur before '->'}}
let _ = (Int) -> Int // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments after the type to construct a value of the type}} expected-note{{use '.self' to reference the type object}}
let _ = 2 + () -> Int // expected-error{{expected type before '->'}}
let _ = () -> (Int, Int).2 // expected-error{{expected type after '->'}}
}
|
apache-2.0
|
cc9b66904e4db2abba3b9e7bd6fca969
| 32.55 | 237 | 0.620566 | 3.392315 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Pods/OAuthSwift/Sources/OAuth1Swift.swift
|
3
|
7895
|
//
// OAuth1Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
open class OAuth1Swift: OAuthSwift {
/// If your oauth provider doesn't provide `oauth_verifier`
/// set this value to true (default: false)
open var allowMissingOAuthVerifier: Bool = false
/// Optionally add callback URL to authorize Url (default: false)
open var addCallbackURLToAuthorizeURL: Bool = false
var consumerKey: String
var consumerSecret: String
var requestTokenUrl: String
var authorizeUrl: String
var accessTokenUrl: String
// MARK: init
public init(consumerKey: String, consumerSecret: String, requestTokenUrl: String, authorizeUrl: String, accessTokenUrl: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.requestTokenUrl = requestTokenUrl
self.authorizeUrl = authorizeUrl
self.accessTokenUrl = accessTokenUrl
super.init(consumerKey: consumerKey, consumerSecret: consumerSecret)
self.client.credential.version = .oauth1
}
public convenience override init(consumerKey: String, consumerSecret: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, requestTokenUrl: "", authorizeUrl: "", accessTokenUrl: "")
}
public convenience init?(parameters: ConfigParameters) {
guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"],
let requestTokenUrl = parameters["requestTokenUrl"], let authorizeUrl = parameters["authorizeUrl"], let accessTokenUrl = parameters["accessTokenUrl"] else {
return nil
}
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret,
requestTokenUrl: requestTokenUrl,
authorizeUrl: authorizeUrl,
accessTokenUrl: accessTokenUrl)
}
open var parameters: ConfigParameters {
return [
"consumerKey": consumerKey,
"consumerSecret": consumerSecret,
"requestTokenUrl": requestTokenUrl,
"authorizeUrl": authorizeUrl,
"accessTokenUrl": accessTokenUrl
]
}
// MARK: functions
// 0. Start
@discardableResult
open func authorize(withCallbackURL callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
self.postOAuthRequestToken(callbackURL: callbackURL, success: { [unowned self] credential, _, _ in
self.observeCallback { [weak self] url in
guard let this = self else { OAuthSwift.retainError(failure); return }
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString
}
if let fragment = url.fragment, !fragment.isEmpty {
responseParameters += fragment.parametersFromQueryString
}
if let token = responseParameters["token"] {
responseParameters["oauth_token"] = token
}
if let token = responseParameters["oauth_token"], !token.isEmpty {
this.client.credential.oauthToken = token.safeStringByRemovingPercentEncoding
if let oauth_verifier = responseParameters["oauth_verifier"] {
this.client.credential.oauthVerifier = oauth_verifier.safeStringByRemovingPercentEncoding
} else {
if !this.allowMissingOAuthVerifier {
failure?(OAuthSwiftError.configurationError(message: "Missing oauth_verifier. Maybe use allowMissingOAuthVerifier=true"))
return
}
}
this.postOAuthAccessTokenWithRequestToken(success: success, failure: failure)
} else {
failure?(OAuthSwiftError.missingToken)
return
}
}
// 2. Authorize
if let token = credential.oauthToken.urlQueryEncoded {
var urlString = self.authorizeUrl + (self.authorizeUrl.contains("?") ? "&" : "?")
urlString += "oauth_token=\(token)"
if self.addCallbackURLToAuthorizeURL {
urlString += "&oauth_callback=\(callbackURL.absoluteString)"
}
if let queryURL = URL(string: urlString) {
self.authorizeURLHandler.handle(queryURL)
} else {
failure?(OAuthSwiftError.encodingError(urlString: urlString))
}
} else {
failure?(OAuthSwiftError.encodingError(urlString: credential.oauthToken)) //TODO specific error
}
}, failure: failure)
return self
}
@discardableResult
open func authorize(withCallbackURL urlString: String, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
guard let url = URL(string: urlString) else {
failure?(OAuthSwiftError.encodingError(urlString: urlString))
return nil
}
return authorize(withCallbackURL: url, success: success, failure: failure)
}
// 1. Request token
func postOAuthRequestToken(callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) {
var parameters = [String: Any]()
parameters["oauth_callback"] = callbackURL.absoluteString
if let handle = self.client.post(
self.requestTokenUrl, parameters: parameters,
success: { [weak self] response in
guard let this = self else { OAuthSwift.retainError(failure); return }
let parameters = response.string?.parametersFromQueryString ?? [:]
if let oauthToken = parameters["oauth_token"] {
this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret=parameters["oauth_token_secret"] {
this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
success(this.client.credential, response, parameters)
}, failure: failure
) {
self.putHandle(handle, withKey: UUID().uuidString)
}
}
// 3. Get Access token
func postOAuthAccessTokenWithRequestToken(success: @escaping TokenSuccessHandler, failure: FailureHandler?) {
var parameters = [String: Any]()
parameters["oauth_token"] = self.client.credential.oauthToken
if !self.allowMissingOAuthVerifier {
parameters["oauth_verifier"] = self.client.credential.oauthVerifier
}
if let handle = self.client.post(
self.accessTokenUrl, parameters: parameters,
success: { [weak self] response in
guard let this = self else { OAuthSwift.retainError(failure); return }
let parameters = response.string?.parametersFromQueryString ?? [:]
if let oauthToken = parameters["oauth_token"] {
this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret = parameters["oauth_token_secret"] {
this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
success(this.client.credential, response, parameters)
}, failure: failure
) {
self.putHandle(handle, withKey: UUID().uuidString)
}
}
}
|
mit
|
06d938a16989074abd6179dcf0e69fb0
| 43.60452 | 168 | 0.621153 | 5.809419 | false | false | false | false |
MaxHasADHD/TraktKit
|
Common/Models/Movies/TraktMovie.swift
|
1
|
2661
|
//
// TraktMovie.swift
// TraktKit
//
// Created by Maximilian Litteral on 4/13/16.
// Copyright © 2016 Maximilian Litteral. All rights reserved.
//
import Foundation
public struct TraktMovie: Codable, Hashable {
// Extended: Min
public let title: String
public let year: Int?
public let ids: ID
// Extended: Full
public let tagline: String?
public let overview: String?
public let released: Date?
public let runtime: Int?
public let trailer: URL?
public let homepage: URL?
public let rating: Double?
public let votes: Int?
public let updatedAt: Date?
public let language: String?
public let availableTranslations: [String]?
public let genres: [String]?
public let certification: String?
enum CodingKeys: String, CodingKey {
case title
case year
case ids
case tagline
case overview
case released
case runtime
case trailer
case homepage
case rating
case votes
case updatedAt = "updated_at"
case language
case availableTranslations = "available_translations"
case genres
case certification
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: CodingKeys.title)
year = try container.decodeIfPresent(Int.self, forKey: CodingKeys.year)
ids = try container.decode(ID.self, forKey: CodingKeys.ids)
tagline = try container.decodeIfPresent(String.self, forKey: CodingKeys.tagline)
overview = try container.decodeIfPresent(String.self, forKey: CodingKeys.overview)
released = try container.decodeIfPresent(Date.self, forKey: CodingKeys.released)
runtime = try container.decodeIfPresent(Int.self, forKey: CodingKeys.runtime)
certification = try container.decodeIfPresent(String.self, forKey: .certification)
trailer = try? container.decode(URL.self, forKey: .trailer)
homepage = try? container.decode(URL.self, forKey: .homepage)
rating = try container.decodeIfPresent(Double.self, forKey: .rating)
votes = try container.decodeIfPresent(Int.self, forKey: .votes)
updatedAt = try container.decodeIfPresent(Date.self, forKey: .updatedAt)
language = try container.decodeIfPresent(String.self, forKey: .language)
availableTranslations = try container.decodeIfPresent([String].self, forKey: .availableTranslations)
genres = try container.decodeIfPresent([String].self, forKey: .genres)
}
}
|
mit
|
34ba829ee490ee3175fcb6a86cef5904
| 35.944444 | 108 | 0.678947 | 4.699647 | false | false | false | false |
luispadron/GradePoint
|
GradePoint/Controllers/Onboarding/OnboardPageViewController.swift
|
1
|
4702
|
//
// OnboardViewController.swift
// GradePoint
//
// Created by Luis Padron on 2/19/17.
// Copyright © 2017 Luis Padron. All rights reserved.
//
import UIKit
class OnboardPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
/// The controllers for the onboarding
private(set) lazy var onboardControllers: [UIViewController] = {
return
[self.newOnboardController(with: "Onboard1"),
self.newOnboardController(with: "Onboard2"),
self.newOnboardController(with: "Onboard3"),
self.newOnboardController(with: "Onboard4")]
}()
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let firstVC = onboardControllers.first {
self.setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
self.view.backgroundColor = firstVC.view.backgroundColor?.lighter(by: 20)
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ApplicationTheme.shared.statusBarStyle
}
private var backgroundColor: UIColor? {
didSet {
self.oldColor = oldValue
self.view.backgroundColor = self.backgroundColor
}
}
private var oldColor: UIColor?
// MARK: PageViewController DataSource
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = onboardControllers.firstIndex(of: viewController) else { return nil }
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0, onboardControllers.count > previousIndex else { return nil }
return onboardControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = onboardControllers.firstIndex(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
guard onboardControllers.count != nextIndex, onboardControllers.count > nextIndex else { return nil }
// Special case if were trying to move to the next controller and were in oboarding 3, then we need to make sure values are filled
if let vc = viewController as? Onboard3ViewController, !vc.isReadyToTransition { return nil }
return onboardControllers[nextIndex]
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return onboardControllers.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstVC = onboardControllers.first, let firstIndex = onboardControllers.firstIndex(of: firstVC) else {
return 0
}
return firstIndex
}
// MARK: PageViewController Delegate
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
guard let toVC = pendingViewControllers.first else { return }
// Set self as controller
if let vc = toVC as? Onboard3ViewController {
vc.pageController = self
}
// Set the background color for this pageviewcontroller, which in turn sets the page controls color
UIView.animate(withDuration: 0.2) {
self.backgroundColor = toVC.view.backgroundColor?.lighter(by: 10)
}
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if finished && !completed {
// Return to old color since user didnt go through with transition
UIView.animate(withDuration: 0.15, animations: {
self.backgroundColor = self.oldColor
})
}
}
func pageViewControllerSupportedInterfaceOrientations(_ pageViewController: UIPageViewController) -> UIInterfaceOrientationMask {
return .portrait
}
// MARK: Helper methods
private func newOnboardController(with id: String) -> UIViewController {
return UIStoryboard(name: "Onboarding", bundle: nil).instantiateViewController(withIdentifier: id)
}
}
|
apache-2.0
|
aa1943273937f119cc57d97c8710cb19
| 37.219512 | 190 | 0.674325 | 5.746944 | false | false | false | false |
prcela/NKNetworkKit
|
Pod/Classes/NKFileDownloadInfo.swift
|
1
|
3542
|
//
// NKFileDownloadInfo.swift
// NetworkKit
//
// Created by Kresimir Prcela on 15/07/15.
// Copyright (c) 2015 prcela. All rights reserved.
//
// Global constants for notifications
public let NKNotificationDownloadTaskDidFinish = "NKNotificationDownloadTaskDidFinish"
public let NKNotificationDownloadTaskDidResumeData = "NKNotificationDownloadTaskDidResumeData"
// MARK: - File download info
public class NKFileDownloadInfo: NSObject {
public var url: NSURL
public var task: NSURLSessionDownloadTask!
public var resumeData: NSData?
public var downloadFilePath: String
public var downloadRatio:Float = 0
public init(url:NSURL, downloadFilePath: String)
{
self.url = url
self.downloadFilePath = downloadFilePath
super.init()
}
}
// MARK: - Session delegate
extension NKFileDownloadInfo: NSURLSessionDownloadDelegate
{
// didFinishDownloadingToURL
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
{
NSLog("Did finish download to url: %@", location)
let fm = NSFileManager.defaultManager()
setValue(1, forKey: "downloadRatio")
let folder = downloadFilePath.stringByDeletingLastPathComponent
var error:NSErrorPointer = nil
if !fm.fileExistsAtPath(folder)
{
fm.createDirectoryAtPath(folder, withIntermediateDirectories: true, attributes: nil, error: error)
}
if fm.fileExistsAtPath(downloadFilePath)
{
fm.removeItemAtPath(downloadFilePath, error:error)
}
fm.moveItemAtURL(location, toURL:NSURL(fileURLWithPath:downloadFilePath)!, error:error)
if (error != nil)
{
NSLog("%@", error.memory!.description);
}
else
{
NSLog("File successfully moved to \(downloadFilePath)")
}
dispatch_async(dispatch_get_main_queue()) {
if let idx = find(NKProcessorInfo.shared.downloads,self) {
NKProcessorInfo.shared.downloads.removeAtIndex(idx)
}
NSNotificationCenter.defaultCenter().postNotificationName(NKNotificationDownloadTaskDidFinish,
object:self)
}
}
// didWriteData
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
{
setValue(Float(Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)), forKey: "downloadRatio")
}
// didResumeAtOffset
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)
{
NSLog("Did resume at offset %lld", fileOffset)
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(NKNotificationDownloadTaskDidResumeData,
object:downloadTask.taskIdentifier)
}
}
// didCompleteWithError
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil
{
NSLog("Did complete with error: \(error!.description)")
if let resumeData = error!.userInfo?[NSURLSessionDownloadTaskResumeData] as? NSData
{
self.resumeData = resumeData
}
}
}
}
|
mit
|
09a18f619264577182cf41d46f6f8c42
| 35.525773 | 183 | 0.677019 | 5.366667 | false | false | false | false |
nathanntg/syllable-detector
|
Common/StreamReader.swift
|
2
|
3205
|
//
// StreamReader.swift
// SyllableDetector
//
// From Stack Overflow answer:
// http://stackoverflow.com/questions/24581517/read-a-file-url-line-by-line-in-swift
import Foundation
class StreamReader {
let encoding : String.Encoding
let chunkSize : Int
var fileHandle : FileHandle!
let buffer : NSMutableData!
let delimData : Data!
var atEof : Bool = false
init?(path: String, delimiter: String = "\n", encoding: String.Encoding = .utf8, chunkSize : Int = 4096) {
self.chunkSize = chunkSize
self.encoding = encoding
if let fileHandle = FileHandle(forReadingAtPath: path),
let delimData = delimiter.data(using: encoding),
let buffer = NSMutableData(capacity: chunkSize)
{
self.fileHandle = fileHandle
self.delimData = delimData
self.buffer = buffer
} else {
self.fileHandle = nil
self.delimData = nil
self.buffer = nil
return nil
}
}
deinit {
self.close()
}
/// Return next line, or nil on EOF.
func nextLine() -> String? {
precondition(fileHandle != nil, "Attempt to read from closed file")
if atEof {
return nil
}
// Read data chunks from file until a line delimiter is found:
var range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length))
while range.location == NSNotFound {
let tmpData = fileHandle.readData(ofLength: chunkSize)
if tmpData.count == 0 {
// EOF or read error.
atEof = true
if buffer.length > 0 {
// Buffer contains last line in file (not terminated by delimiter).
let line = NSString(data: buffer as Data, encoding: encoding.rawValue)
buffer.length = 0
return line as String?
}
// No more lines.
return nil
}
buffer.append(tmpData)
range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length))
}
// Convert complete line (excluding the delimiter) to a string:
let line = NSString(data: buffer.subdata(with: NSMakeRange(0, range.location)),
encoding: encoding.rawValue)
// Remove line (and the delimiter) from the buffer:
buffer.replaceBytes(in: NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0)
return line as String?
}
/// Start reading from the beginning of file.
func rewind() -> Void {
fileHandle.seek(toFileOffset: 0)
buffer.length = 0
atEof = false
}
/// Close the underlying file. No reading must be done after calling this method.
func close() -> Void {
fileHandle?.closeFile()
fileHandle = nil
}
}
extension StreamReader : Sequence {
func makeIterator() -> AnyIterator<String> {
return AnyIterator {
return self.nextLine()
}
}
}
|
mit
|
c0445d4df4fc336e66d30043a4c4401a
| 31.05 | 110 | 0.560686 | 4.769345 | false | false | false | false |
mentrena/SyncKit
|
SyncKit/Classes/QSSynchronizer/BackupDetection.swift
|
1
|
2154
|
//
// QSBackupDetection.swift
// Pods
//
// Created by Manuel Entrena on 04/04/2019.
//
import Foundation
class BackupDetection: NSObject {
@objc enum DetectionResult: Int {
case firstRun
case restoredFromBackup
case regularLaunch
}
fileprivate static let backupDetectionStoreKey = "QSBackupDetectionStoreKey"
fileprivate static var applicationDocumentsDirectory: String {
#if os(iOS) || os(watchOS)
return NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
#else
let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
return urls.last?.appendingPathComponent("com.mentrena.QSCloudKitSynchronizer").path ?? ""
#endif
}
fileprivate static let fileName = "backupDetection"
fileprivate static var backupDetectionFilePath: String {
return NSString.path(withComponents: [applicationDocumentsDirectory, fileName])
}
@objc
static func runBackupDetection(completion: (DetectionResult, Error?) -> ()) {
let result: DetectionResult
if FileManager.default.fileExists(atPath: backupDetectionFilePath) {
result = .regularLaunch
} else if UserDefaults.standard.bool(forKey: backupDetectionStoreKey) {
result = .restoredFromBackup
} else {
result = .firstRun
}
var error: Error?
if result == .firstRun || result == .restoredFromBackup {
let content = "Backup detection file\n"
let fileContents = content.data(using: .utf8)
FileManager.default.createFile(atPath: backupDetectionFilePath, contents: fileContents, attributes: nil)
var fileURL = URL(fileURLWithPath: backupDetectionFilePath)
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
do {
try fileURL.setResourceValues(resourceValues)
} catch let err {
error = err
}
}
completion(result, error)
}
}
|
mit
|
fa18dcea02cfa41f2753212b6675f4e8
| 33.741935 | 116 | 0.647632 | 5.305419 | false | false | false | false |
davbeck/ImageIOSwift
|
Sources/ImageIOUIKit/UIImageOrientation+Helpers.swift
|
1
|
579
|
#if canImport(UIKit)
import ImageIOSwift
import UIKit
extension UIImage.Orientation {
public init(exifOrientation: Int) {
switch exifOrientation {
case 2:
self = .upMirrored
case 3:
self = .down
case 4:
self = .downMirrored
case 5:
self = .leftMirrored
case 6:
self = .right
case 7:
self = .rightMirrored
case 8:
self = .left
default: // 1
self = .up
}
}
}
extension ImageProperties {
var orientation: UIImage.Orientation {
return UIImage.Orientation(exifOrientation: exifOrientation)
}
}
#endif
|
mit
|
0fb77a30669b9c6a54e15e520c3a4b45
| 16.545455 | 63 | 0.644214 | 3.289773 | false | false | false | false |
cikelengfeng/Jude
|
Jude/Antlr4/misc/extension/ArrayExtension.swift
|
2
|
2903
|
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
import Foundation
//https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift
extension Array {
@discardableResult
mutating func concat(_ addArray: [Element]) -> [Element] {
return self + addArray
}
mutating func removeObject<T:Equatable>(_ object: T) {
var index: Int?
for (idx, objectToCompare) in self.enumerated() {
if let to = objectToCompare as? T {
if object == to {
index = idx
}
}
}
if index != nil {
self.remove(at: index!)
}
}
/// Removes the last element from self and returns it.
///
/// :returns: The removed element
mutating func pop() -> Element {
return removeLast()
}
/// Same as append.
///
/// :param: newElement Element to append
mutating func push(_ newElement: Element) {
return append(newElement)
}
func all(_ test: (Element) -> Bool) -> Bool {
for item in self {
if !test(item) {
return false
}
}
return true
}
/// Checks if test returns true for all the elements in self
///
/// :param: test Function to call for each element
/// :returns: True if test returns true for all the elements in self
func every(_ test: (Element) -> Bool) -> Bool {
for item in self {
if !test(item) {
return false
}
}
return true
}
/// Checks if test returns true for any element of self.
///
/// :param: test Function to call for each element
/// :returns: true if test returns true for any element of self
func any(_ test: (Element) -> Bool) -> Bool {
for item in self {
if test(item) {
return true
}
}
return false
}
/// slice array
/// :param: index slice index
/// :param: isClose is close array
/// :param: first First array
/// :param: second Second array
//func slice(startIndex startIndex:Int, endIndex:Int) -> Slice<Element> {
func slice(startIndex: Int, endIndex: Int) -> ArraySlice<Element> {
return self[startIndex ... endIndex]
}
// func slice(index:Int,isClose:Bool = false) ->(first:Slice<Element> ,second:Slice<Element>){
func slice(_ index: Int, isClose: Bool = false) -> (first:ArraySlice<Element>, second:ArraySlice<Element>) {
var first = self[0 ... index]
var second = self[index ..< count]
if isClose {
first = second + first
second = []
}
return (first, second)
}
}
|
mit
|
a258820dad0291e3d8ee13acf4a279ce
| 24.243478 | 112 | 0.549776 | 4.405159 | false | true | false | false |
KrishMunot/swift
|
test/SILGen/generic_casts.swift
|
6
|
9334
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | FileCheck %s
protocol ClassBound : class {}
protocol NotClassBound {}
class C : ClassBound, NotClassBound {}
struct S : NotClassBound {}
struct Unloadable : NotClassBound { var x : NotClassBound }
// CHECK-LABEL: sil hidden @_TF13generic_casts36opaque_archetype_to_opaque_archetype{{.*}}
func opaque_archetype_to_opaque_archetype
<T:NotClassBound, U>(_ t:T) -> U {
return t as! U
// CHECK: bb0([[RET:%.*]] : $*U, {{%.*}}: $*T):
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to U in [[RET]] : $*U
}
// CHECK-LABEL: sil hidden @_TF13generic_casts36opaque_archetype_is_opaque_archetype{{.*}}
func opaque_archetype_is_opaque_archetype
<T:NotClassBound, U>(_ t:T, u:U.Type) -> Bool {
return t is U
// CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : $*T to U in [[DEST:%.*]] : $*U, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[Y:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: destroy_addr [[DEST]]
// CHECK: br [[CONT:bb[0-9]+]]([[Y]] : $Builtin.Int1)
// CHECK: [[NO]]:
// CHECK: [[N:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: br [[CONT]]([[N]] : $Builtin.Int1)
// CHECK: [[CONT]]([[I1:%.*]] : $Builtin.Int1):
// -- apply the _getBool library fn
// CHECK-NEXT: function_ref Swift._getBool
// CHECK-NEXT: [[GETBOOL:%.*]] = function_ref @_TFs8_getBoolFBi1_Sb :
// CHECK-NEXT: [[RES:%.*]] = apply [[GETBOOL]]([[I1]])
// -- we don't consume the checked value
// CHECK: return [[RES]] : $Bool
}
// CHECK-LABEL: sil hidden @_TF13generic_casts35opaque_archetype_to_class_archetype{{.*}}
func opaque_archetype_to_class_archetype
<T:NotClassBound, U:ClassBound> (_ t:T) -> U {
return t as! U
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U
// CHECK: [[DOWNCAST:%.*]] = load [[DOWNCAST_ADDR]] : $*U
// CHECK: return [[DOWNCAST]] : $U
}
// CHECK-LABEL: sil hidden @_TF13generic_casts35opaque_archetype_is_class_archetype{{.*}}
func opaque_archetype_is_class_archetype
<T:NotClassBound, U:ClassBound> (_ t:T, u:U.Type) -> Bool {
return t is U
// CHECK: copy_addr {{.*}} : $*T
// CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to U
}
// CHECK-LABEL: sil hidden @_TF13generic_casts34class_archetype_to_class_archetype{{.*}}
func class_archetype_to_class_archetype
<T:ClassBound, U:ClassBound>(_ t:T) -> U {
return t as! U
// CHECK: unconditional_checked_cast_addr {{.*}} T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U
// CHECK: [[DOWNCAST:%.*]] = load [[DOWNCAST_ADDR]]
// CHECK: return [[DOWNCAST]] : $U
}
// CHECK-LABEL: sil hidden @_TF13generic_casts34class_archetype_is_class_archetype{{.*}}
func class_archetype_is_class_archetype
<T:ClassBound, U:ClassBound>(_ t:T, u:U.Type) -> Bool {
return t is U
// CHECK: checked_cast_addr_br {{.*}} T in {{%.*}} : $*T to U in {{%.*}} : $*U
}
// CHECK-LABEL: sil hidden @_TF13generic_casts38opaque_archetype_to_addr_only_concrete{{.*}}
func opaque_archetype_to_addr_only_concrete
<T:NotClassBound> (_ t:T) -> Unloadable {
return t as! Unloadable
// CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*T):
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to Unloadable in [[RET]] : $*Unloadable
}
// CHECK-LABEL: sil hidden @_TF13generic_casts38opaque_archetype_is_addr_only_concrete{{.*}}
func opaque_archetype_is_addr_only_concrete
<T:NotClassBound> (_ t:T) -> Bool {
return t is Unloadable
// CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to Unloadable in
}
// CHECK-LABEL: sil hidden @_TF13generic_casts37opaque_archetype_to_loadable_concrete{{.*}}
func opaque_archetype_to_loadable_concrete
<T:NotClassBound>(_ t:T) -> S {
return t as! S
// CHECK: unconditional_checked_cast_addr take_always T in {{%.*}} : $*T to S in [[DOWNCAST_ADDR:%.*]] : $*S
// CHECK: [[DOWNCAST:%.*]] = load [[DOWNCAST_ADDR]] : $*S
// CHECK: return [[DOWNCAST]] : $S
}
// CHECK-LABEL: sil hidden @_TF13generic_casts37opaque_archetype_is_loadable_concrete{{.*}}
func opaque_archetype_is_loadable_concrete
<T:NotClassBound>(_ t:T) -> Bool {
return t is S
// CHECK: checked_cast_addr_br take_always T in {{%.*}} : $*T to S in
}
// CHECK-LABEL: sil hidden @_TF13generic_casts24class_archetype_to_class{{.*}}
func class_archetype_to_class
<T:ClassBound>(_ t:T) -> C {
return t as! C
// CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to $C
// CHECK: return [[DOWNCAST]] : $C
}
// CHECK-LABEL: sil hidden @_TF13generic_casts24class_archetype_is_class{{.*}}
func class_archetype_is_class
<T:ClassBound>(_ t:T) -> Bool {
return t is C
// CHECK: checked_cast_br {{%.*}} to $C
}
// CHECK-LABEL: sil hidden @_TF13generic_casts38opaque_existential_to_opaque_archetype{{.*}}
func opaque_existential_to_opaque_archetype
<T:NotClassBound>(_ p:NotClassBound) -> T {
return p as! T
// CHECK: bb0([[RET:%.*]] : $*T, [[ARG:%.*]] : $*NotClassBound):
// CHECK: [[TEMP:%.*]] = alloc_stack $NotClassBound
// CHECK-NEXT: copy_addr [[ARG]] to [initialization] [[TEMP]]
// CHECK-NEXT: unconditional_checked_cast_addr take_always NotClassBound in [[TEMP]] : $*NotClassBound to T in [[RET]] : $*T
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: destroy_addr [[ARG]]
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]]
}
// CHECK-LABEL: sil hidden @_TF13generic_casts38opaque_existential_is_opaque_archetype{{.*}}
func opaque_existential_is_opaque_archetype
<T:NotClassBound>(_ p:NotClassBound, _: T) -> Bool {
return p is T
// CHECK: checked_cast_addr_br take_always NotClassBound in [[CONTAINER:%.*]] : {{.*}} to T in
}
// CHECK-LABEL: sil hidden @_TF13generic_casts37opaque_existential_to_class_archetype{{.*}}
func opaque_existential_to_class_archetype
<T:ClassBound>(_ p:NotClassBound) -> T {
return p as! T
// CHECK: unconditional_checked_cast_addr take_always NotClassBound in {{%.*}} : $*NotClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T
// CHECK: [[DOWNCAST:%.*]] = load [[DOWNCAST_ADDR]] : $*T
// CHECK: return [[DOWNCAST]] : $T
}
// CHECK-LABEL: sil hidden @_TF13generic_casts37opaque_existential_is_class_archetype{{.*}}
func opaque_existential_is_class_archetype
<T:ClassBound>(_ p:NotClassBound, _: T) -> Bool {
return p is T
// CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to T in
}
// CHECK-LABEL: sil hidden @_TF13generic_casts36class_existential_to_class_archetype{{.*}}
func class_existential_to_class_archetype
<T:ClassBound>(_ p:ClassBound) -> T {
return p as! T
// CHECK: unconditional_checked_cast_addr {{.*}} ClassBound in {{%.*}} : $*ClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T
// CHECK: [[DOWNCAST:%.*]] = load [[DOWNCAST_ADDR]]
// CHECK: return [[DOWNCAST]] : $T
}
// CHECK-LABEL: sil hidden @_TF13generic_casts36class_existential_is_class_archetype{{.*}}
func class_existential_is_class_archetype
<T:ClassBound>(_ p:ClassBound, _: T) -> Bool {
return p is T
// CHECK: checked_cast_addr_br {{.*}} ClassBound in {{%.*}} : $*ClassBound to T in {{%.*}} : $*T
}
// CHECK-LABEL: sil hidden @_TF13generic_casts40opaque_existential_to_addr_only_concrete{{.*}}
func opaque_existential_to_addr_only_concrete(_ p: NotClassBound) -> Unloadable {
return p as! Unloadable
// CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*NotClassBound):
// CHECK: unconditional_checked_cast_addr take_always NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in [[RET]] : $*Unloadable
}
// CHECK-LABEL: sil hidden @_TF13generic_casts40opaque_existential_is_addr_only_concrete{{.*}}
func opaque_existential_is_addr_only_concrete(_ p: NotClassBound) -> Bool {
return p is Unloadable
// CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in
}
// CHECK-LABEL: sil hidden @_TF13generic_casts39opaque_existential_to_loadable_concrete{{.*}}
func opaque_existential_to_loadable_concrete(_ p: NotClassBound) -> S {
return p as! S
// CHECK: unconditional_checked_cast_addr take_always NotClassBound in {{%.*}} : $*NotClassBound to S in [[DOWNCAST_ADDR:%.*]] : $*S
// CHECK: [[DOWNCAST:%.*]] = load [[DOWNCAST_ADDR]] : $*S
// CHECK: return [[DOWNCAST]] : $S
}
// CHECK-LABEL: sil hidden @_TF13generic_casts39opaque_existential_is_loadable_concrete{{.*}}
func opaque_existential_is_loadable_concrete(_ p: NotClassBound) -> Bool {
return p is S
// CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to S in
}
// CHECK-LABEL: sil hidden @_TF13generic_casts26class_existential_to_class{{.*}}
func class_existential_to_class(_ p: ClassBound) -> C {
return p as! C
// CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to $C
// CHECK: return [[DOWNCAST]] : $C
}
// CHECK-LABEL: sil hidden @_TF13generic_casts26class_existential_is_class{{.*}}
func class_existential_is_class(_ p: ClassBound) -> Bool {
return p is C
// CHECK: checked_cast_br {{%.*}} to $C
}
// CHECK-LABEL: sil hidden @_TF13generic_casts27optional_anyobject_to_classFGSqPs9AnyObject__GSqCS_1C_
// CHECK: checked_cast_br {{%.*}} : $AnyObject to $C
func optional_anyobject_to_class(_ p: AnyObject?) -> C? {
return p as? C
}
|
apache-2.0
|
edf7e2325a5a6165cd9b0d67d067b6a1
| 42.413953 | 140 | 0.645811 | 3.390483 | false | false | false | false |
lenglengiOS/BuDeJie
|
百思不得姐/Pods/Charts/Charts/Classes/Data/PieChartData.swift
|
119
|
1821
|
//
// PieData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class PieChartData: ChartData
{
public override init()
{
super.init()
}
public override init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
var dataSet: PieChartDataSet?
{
get
{
return dataSets.count > 0 ? dataSets[0] as? PieChartDataSet : nil
}
set
{
if (newValue != nil)
{
dataSets = [newValue!]
}
else
{
dataSets = []
}
}
}
public override func getDataSetByIndex(index: Int) -> ChartDataSet?
{
if (index != 0)
{
return nil
}
return super.getDataSetByIndex(index)
}
public override func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet?
{
if (dataSets.count == 0 || dataSets[0].label == nil)
{
return nil
}
if (ignorecase)
{
if (label.caseInsensitiveCompare(dataSets[0].label!) == NSComparisonResult.OrderedSame)
{
return dataSets[0]
}
}
else
{
if (label == dataSets[0].label)
{
return dataSets[0]
}
}
return nil
}
}
|
apache-2.0
|
2d4bc6546ec005ca7ab375b5f6e19e25
| 20.678571 | 99 | 0.501922 | 4.610127 | false | false | false | false |
fnazarios/weather-app
|
WeatherTests/Models/WeatherSpec.swift
|
1
|
1608
|
import Quick
import Nimble
import RxSwift
import Argo
@testable import Weather
class WeatherSpec: QuickSpec {
lazy var disposeBag = DisposeBag()
override func spec() {
fdescribe("Weather") {
fcontext("parse weather") {
var weather: Weather?
let jsonText = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03d\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":286.391,\"pressure\":1013.81,\"humidity\":80,\"temp_min\":286.391,\"temp_max\":286.391,\"sea_level\":1023.71,\"grnd_level\":1013.81},\"wind\":{\"speed\":9.42,\"deg\":227.501},\"clouds\":{\"all\":48},\"dt\":1447852426,\"sys\":{\"message\":0.0027,\"country\":\"GB\",\"sunrise\":1447831434,\"sunset\":1447862820},\"id\":2643743,\"name\":\"London\",\"cod\":200}"
.dataUsingEncoding(NSUTF8StringEncoding)!
let json = try? NSJSONSerialization.JSONObjectWithData(jsonText, options: .AllowFragments)
if let j = json {
weather = decode(j)
}
fit("weather should not be nil") {
expect(weather).toNot(beNil())
}
fit("weather name should be eq \"London\"") {
expect(weather?.name).to(equal("London"))
}
fit("temp should be eq 286.391") {
expect(weather?.degress).to(equal(286.391))
}
}
}
}
}
|
apache-2.0
|
4cbac073c43013787466b0cc5e95e955
| 44.942857 | 577 | 0.501244 | 4.555241 | false | false | false | false |
GMSLabs/Hyber-SDK-iOS
|
Hyber/Classes/Helpers/Network/Networking.swift
|
1
|
6754
|
//
// Networking.swift
// Hyber-SDK-IOS
//
// Created by Taras on 11/8/16.
//
//
import Alamofire
import CoreData
import Realm
import RealmSwift
import SwiftyJSON
import RxSwift
class Networking: NSObject {
let disposeBag = DisposeBag()
class func registerRequest(parameters: [String: Any]?, headers: [String: String]) -> Observable<Any> {
return request(.post, kRegUrl, parameters: parameters, encoding: JSONEncoding.prettyPrinted, headers: headers)
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.instance)
.flatMap { response -> Observable<Any> in
return response.validate(statusCode: 200..<300)
.validate(contentType: ["application/json", "text/json"])
.rx.json()
}
.map {
json in
let validJson = JSON(json)
DataRealm.saveProfile(json: validJson)
HyberLogger.info(validJson)
return validJson
}
}
class func updateDeviceRequest(parameters: [String: Any]?, headers: [String: String]) -> Observable<Any> {
return request(.post, kUpdateUrl, parameters: parameters, encoding: JSONEncoding.prettyPrinted, headers: headers)
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.instance)
.flatMap { response -> Observable<Any> in
return response.validate(statusCode: 200..<300)
.validate(contentType: ["application/json", "text/json"])
.rx.json()
}
.map { json in
let data = json
let validJson = JSON(data)
DataRealm.updateDevice(json: validJson)
HyberLogger.info(validJson)
return validJson
}
}
class func getMessagesRequest(parameters: [String: Any]?, headers: [String: String]) -> Observable<Any> {
return request(.get, kGetMsgHistory, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.asyncInstance)
.flatMap { response -> Observable<Any> in
return response.validate(statusCode: 200..<300)
.validate(contentType: ["application/json", "text/json"])
.rx.json()
}
.map { json in
let data = json
let validJson = JSON(data)
DataRealm.saveMessages(json: validJson)
HyberLogger.debug(validJson)
return validJson
}
}
class func sentDeliveredStatus(parameters: [String: Any]? = nil, headers: [String: String]) -> Observable<Any> {
return request(.post, kSendMsgDr, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.instance)
.flatMap { response -> Observable<Any> in
return response.validate(statusCode: 200..<500)
.rx.json()
}
.map { _ in
HyberLogger.debug(HTTPURLResponse())
}
}
class func sentBiderectionalMessage(parameters: [String: Any]? = nil, headers: [String: String]) -> Observable<Any> {
return request(.post, kSendMsgCallback, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.instance)
.flatMap { response -> Observable<Any> in
return response.validate(statusCode: 200..<500)
.rx.json()
}
.map { _ in
HyberLogger.debug(HTTPURLResponse())
}
}
//MARK: -New features
class func deleteDevice(parameters: [String: Any]?, headers: [String: String]) -> Observable<Any> {
return request(.post, kDeleteDevice, parameters: parameters, encoding: JSONEncoding.prettyPrinted, headers: headers)
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.instance)
.flatMap { response -> Observable<Any> in
return response.validate(statusCode: 200..<300)
.validate(contentType: ["application/json", "text/json"])
.rx.json()
}
.map { json in
let data = json
let validJson = JSON(data)
HyberLogger.info(validJson)
return validJson
}
}
class func getDeviceInfoRequest(parameters: [String: Any]?, headers: [String: String]) -> Observable<Any> {
return request(.get, kGetDeviceInfo, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.instance)
.flatMap { response -> Observable<Any> in
return response.validate(statusCode: 200..<500)
.validate(contentType: ["application/json", "text/json", "text/plain"])
.rx.json()
}
.map { json in
let data = json
let validJson = JSON(data)
DataRealm.saveDeiveList(json:validJson)
HyberLogger.debug(validJson)
return validJson
}
}
//MARK: - Method with Handler
class func getMessagesArea(parameters: [String: Any]?, headers: [String: String], completionHandler: @escaping (AnyObject?, Error?) -> ()) {
Alamofire.request(kGetMsgHistory, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers) .responseJSON { response in
switch response.result {
case .success(let value):
completionHandler(value as AnyObject?, nil)
case .failure(let error):
completionHandler(nil, error)
HyberLogger.error(error)
}
}
}
class func getDeviceArea(parameters: [String: Any]?, headers: [String: String], completionHandler: @escaping (AnyObject?, Error?) -> ()) {
Alamofire.request(kGetDeviceInfo, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers) .responseJSON { response in
switch response.result {
case .success(let value):
completionHandler(value as AnyObject?, nil)
case .failure(let error):
completionHandler(nil, error)
HyberLogger.error(error)
}
}
}
}
|
apache-2.0
|
778943cb8294893baf3818d24ae26f6e
| 38.267442 | 156 | 0.583062 | 4.955246 | false | false | false | false |
AlexLittlejohn/OMDBMovies
|
OMDBMovies/Views/MovieGridCell.swift
|
1
|
3877
|
//
// MovieGridCell.swift
// OMDBMovies
//
// Created by Alex Littlejohn on 2016/04/04.
// Copyright © 2016 Alex Littlejohn. All rights reserved.
//
import UIKit
class MovieGridCell: UICollectionViewCell {
let imageView = UIImageView()
let titleLabel = UILabel()
let gradientView = UIView()
let spinner = UIActivityIndicatorView()
static var reuseIdentifier: String {
return String(MovieGridCell.self)
}
// I avoid using nibs/storyboards when working on projects with multiple contributors
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
addSubview(imageView)
addSubview(gradientView)
addSubview(titleLabel)
addSubview(spinner)
imageView.image = UIImage(named: "Placeholder")
imageView.contentMode = .ScaleAspectFill
titleLabel.textColor = Colors.List.Title
titleLabel.font = Typography.List.Title
titleLabel.numberOfLines = 0
gradientView.backgroundColor = Colors.List.GradientEnd
spinner.activityIndicatorViewStyle = .Gray
spinner.hidesWhenStopped = true
clipsToBounds = true
opaque = true
layer.drawsAsynchronously = true
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = UIImage(named: "Placeholder")
titleLabel.text = ""
gradientView.alpha = 0
spinner.stopAnimating()
}
// The layout performance needs to be good as it will be in a scrollview, hence no autolayout
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
let padding = Metrics.List.CellPadding
let constrainedTextWidth = frame.width - (padding.left + padding.right)
let constrainedTextSize = CGSize(width: constrainedTextWidth, height: CGFloat.max)
let titleSize = titleLabel.sizeThatFits(constrainedTextSize)
let titleX = padding.left
let titleY = frame.height - (titleSize.height + padding.bottom)
titleLabel.frame = CGRect(x: titleX, y: titleY, width: titleSize.width, height: titleSize.height)
let gradientX: CGFloat = 0
let gradientY = titleY - padding.top
let gradientWidth = frame.width
let gradientHeight = frame.height - gradientY
gradientView.frame = CGRect(x: gradientX, y: gradientY, width: gradientWidth, height: gradientHeight)
gradientView.layer.mask = gradientMask()
let spinnerCenter = CGPoint(x: bounds.midX, y: bounds.midY * 1.5)
spinner.center = spinnerCenter
}
func gradientMask() -> CAGradientLayer {
let gradient = CAGradientLayer()
gradient.frame = gradientView.bounds
gradient.colors = [Colors.List.GradientStart.CGColor, Colors.List.GradientEnd.CGColor]
gradient.locations = [0.0, 1]
return gradient
}
}
extension MovieGridCell {
func configureWithItem(item: MovieResult) {
titleLabel.text = item.title
gradientView.alpha = 1
spinner.stopAnimating()
setNeedsLayout()
layoutIfNeeded()
}
static func sizeWithItem(item: MovieResult, constrainedSize: CGSize) -> CGSize {
// a little dirty but for the purposes of this test im leaving it in
let width = (constrainedSize.width - (Metrics.List.Columns + 1))/Metrics.List.Columns
let height = width * 1.5
return CGSize(width: width, height: height)
}
}
|
mit
|
99ac5fb0bf416793740c4ee64a91f069
| 31.041322 | 109 | 0.633127 | 4.969231 | false | false | false | false |
xwu/swift
|
benchmark/single-source/WordCount.swift
|
3
|
9240
|
//===--- WordCount.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
//
// Mini benchmark counting words in a longer string.
// Measures performance of
// - Iterating over the Characters in a String
// - Extracting short substrings as Strings
// - Set<Character> lookup performance
// - Set<String> init from sequence of short Strings, with duplicates
// - Uniquing initializer for Dictionary with short string keys
//
public let benchmarks = [
BenchmarkInfo(
name: "WordSplitASCII",
runFunction: run_WordSplitASCII,
tags: [.validation, .api, .String, .algorithm, .unstable],
setUpFunction: { buildWorkload() },
legacyFactor: 10
),
BenchmarkInfo(
name: "WordSplitUTF16",
runFunction: run_WordSplitUTF16,
tags: [.validation, .api, .String, .algorithm, .unstable],
setUpFunction: { buildWorkload() },
legacyFactor: 10
),
BenchmarkInfo(
name: "WordCountUniqueASCII",
runFunction: run_WordCountUniqueASCII,
tags: [.validation, .api, .String, .Dictionary, .algorithm],
setUpFunction: { buildWorkload() },
legacyFactor: 10
),
BenchmarkInfo(
name: "WordCountUniqueUTF16",
runFunction: run_WordCountUniqueUTF16,
tags: [.validation, .api, .String, .Dictionary, .algorithm],
setUpFunction: { buildWorkload() },
legacyFactor: 10
),
BenchmarkInfo(
name: "WordCountHistogramASCII",
runFunction: run_WordCountHistogramASCII,
tags: [.validation, .api, .String, .Dictionary, .algorithm],
setUpFunction: { buildWorkload() },
legacyFactor: 100
),
BenchmarkInfo(
name: "WordCountHistogramUTF16",
runFunction: run_WordCountHistogramUTF16,
tags: [.validation, .api, .String, .Dictionary, .algorithm],
setUpFunction: { buildWorkload() },
legacyFactor: 100
),
]
let asciiText = """
**Welcome to Swift!**
Swift is a high-performance system programming language. It has a clean and
modern syntax, offers seamless access to existing C and Objective-C code and
frameworks, and is memory safe by default.
Although inspired by Objective-C and many other languages, Swift is not itself a
C-derived language. As a complete and independent language, Swift packages core
features like flow control, data structures, and functions, with high-level
constructs like objects, protocols, closures, and generics. Swift embraces
modules, eliminating the need for headers and the code duplication they entail.
To learn more about the programming language, visit swift.org.
## Contributing to Swift
Contributions to Swift are welcomed and encouraged! Please see the
Contributing to Swift guide.
To be a truly great community, Swift.org needs to welcome developers from all
walks of life, with different backgrounds, and with a wide range of
experience. A diverse and friendly community will have more great ideas, more
unique perspectives, and produce more great code. We will work diligently to
make the Swift community welcoming to everyone.
To give clarity of what is expected of our members, Swift has adopted the code
of conduct defined by the Contributor Covenant. This document is used across
many open source communities, and we think it articulates our values well. For
more, see the Code of Conduct.
## Getting Started
These instructions give the most direct path to a working Swift development
environment. To build from source you will need 2 GB of disk space for the
source code and over 20 GB of disk space for the build artifacts. A clean build
can take multiple hours, but incremental builds will finish much faster.
"""
let utf16Text = """
✨🌟 Welcome tö Swift! ⭐️✨
Swift is a high-performance system programming language. It has a clean and
modern syntax, offers seamless access tö existing C and Objective-C code and
frameworks, and is memory safe by default.
Although inspired by Objective-C and many othér languages, Swift is not itself a
C-derived language. As a complete and independent language, Swift packages core
features li\u{30A}ke flow control, data structures, and functions, with
high-level constructs li\u{30A}ke objects, protöcols, closures, and
generics. Swift embraces modules, eliminating thé need for headers and thé code
duplication théy entail.
Tö learn more about thé programming language, visit swift.org.
☞ Contributing tö Swift
Contributions tö Swift are welcomed and encouraged! Please see thé
Contributing tö Swift guide.
Tö be a truly great community, Swift.org needs tö welcome developers from all
walks of life, with different backgrounds, and with a wide range of
experience. A diverse and friendly community will have more great ideas, more
unique perspectives, and produce more great code. We will work diligently tö
make thé Swift community welcoming tö everyone.
Tö give clarity of what is expected of our members, Swift has adopted thé code
of conduct defined by thé Contributör Covenant. This document is used across
many open source communities, and we think it articulates our values well. For
more, see thé Code of Conduct.
☞ Getting Started
Thése instructions give thé most direct path tö a working Swift development
environment. Tö build from source you will need 2 GB of disk space for thé
source code and over 20 GB of disk space for thé build artifacts. A clean build
can take multiple hours, but incremental builds will finish much faster.
"""
@inline(never)
func buildWorkload() {
blackHole(someAlphanumerics)
blackHole(asciiWords)
blackHole(utf16Words)
}
// A partial set of Unicode alphanumeric characters. (ASCII letters with at most
// one diacritic (of a limited selection), plus ASCII digits.)
let someAlphanumerics: Set<Character> = {
let baseAlphabet = Set(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".unicodeScalars)
let someCombiningDiacriticalMarks: Set<Unicode.Scalar> =
Set((0x300..<0x310).map { Unicode.Scalar($0)! })
var alphanumerics: Set<Character> = []
for base in baseAlphabet {
alphanumerics.insert(Character(base))
for mark in someCombiningDiacriticalMarks {
var v = String.UnicodeScalarView()
v.append(base)
v.append(mark)
alphanumerics.insert(Character(String(v)))
}
}
alphanumerics.formUnion("0123456789")
return alphanumerics
}()
extension Character {
var isAlphanumeric: Bool {
return someAlphanumerics.contains(self)
}
}
struct Words: IteratorProtocol, Sequence {
public typealias Iterator = Words
let text: String
var nextIndex: String.Index
init(_ text: String) {
self.text = text
self.nextIndex = text.startIndex
}
mutating func next() -> String? {
while nextIndex != text.endIndex && !text[nextIndex].isAlphanumeric {
text.formIndex(after: &nextIndex)
}
let start = nextIndex
while nextIndex != text.endIndex && text[nextIndex].isAlphanumeric {
text.formIndex(after: &nextIndex)
}
guard start < nextIndex else { return nil }
return String(text[start..<nextIndex])
}
}
@inline(never)
public func run_WordSplitASCII(_ n: Int) {
for _ in 1...n {
let words = Array(Words(identity(asciiText)))
check(words.count == 280)
blackHole(words)
}
}
@inline(never)
public func run_WordSplitUTF16(_ n: Int) {
for _ in 1...n {
let words = Array(Words(identity(utf16Text)))
check(words.count == 280)
blackHole(words)
}
}
let asciiWords = Array(Words(asciiText))
let utf16Words = Array(Words(utf16Text))
@inline(never)
public func run_WordCountUniqueASCII(_ n: Int) {
for _ in 1...10*n {
let words = Set(identity(asciiWords))
check(words.count == 168)
blackHole(words)
}
}
@inline(never)
public func run_WordCountUniqueUTF16(_ n: Int) {
for _ in 1...10*n {
let words = Set(identity(utf16Words))
check(words.count == 168)
blackHole(words)
}
}
/// Returns an array of all words in the supplied string, along with their
/// number of occurances. The array is sorted by decreasing frequency.
/// (Words are case-sensitive and only support a limited subset of Unicode.)
@inline(never)
func histogram<S: Sequence>(for words: S) -> [(String, Int)]
where S.Element == String {
let histogram = Dictionary<String, Int>(
words.lazy.map { ($0, 1) },
uniquingKeysWith: +)
return histogram.sorted { (-$0.1, $0.0) < (-$1.1, $1.0) }
}
@inline(never)
public func run_WordCountHistogramASCII(_ n: Int) {
for _ in 1...n {
let words = histogram(for: identity(asciiWords))
check(words.count == 168)
check(words[0] == ("and", 15))
blackHole(words)
}
}
@inline(never)
public func run_WordCountHistogramUTF16(_ n: Int) {
for _ in 1...n {
let words = histogram(for: identity(utf16Words))
check(words.count == 168)
check(words[0] == ("and", 15))
blackHole(words)
}
}
|
apache-2.0
|
e0d7b7d29b98208652b5b135fa7bc190
| 32.198556 | 80 | 0.718573 | 3.963793 | false | false | false | false |
joerocca/GitHawk
|
Local Pods/SlackTextViewController/Examples/Messenger-Swift/MessageViewController.swift
|
1
|
27127
|
//
// MessageViewController.swift
// Messenger
//
// Created by Ignacio Romero Zurbuchen on 10/16/14.
// Copyright (c) 2014 Slack Technologies, Inc. All rights reserved.
//
let DEBUG_CUSTOM_TYPING_INDICATOR = false
class MessageViewController: SLKTextViewController {
var messages = [Message]()
var users: Array = ["Allen", "Anna", "Alicia", "Arnold", "Armando", "Antonio", "Brad", "Catalaya", "Christoph", "Emerson", "Eric", "Everyone", "Steve"]
var channels: Array = ["General", "Random", "iOS", "Bugs", "Sports", "Android", "UI", "SSB"]
var emojis: Array = ["-1", "m", "man", "machine", "block-a", "block-b", "bowtie", "boar", "boat", "book", "bookmark", "neckbeard", "metal", "fu", "feelsgood"]
var commands: Array = ["msg", "call", "text", "skype", "kick", "invite"]
var searchResult: [String]?
var pipWindow: UIWindow?
var editingMessage = Message()
override var tableView: UITableView {
get {
return super.tableView!
}
}
// MARK: - Initialisation
override class func tableViewStyle(for decoder: NSCoder) -> UITableViewStyle {
return .plain
}
func commonInit() {
NotificationCenter.default.addObserver(self.tableView, selector: #selector(UITableView.reloadData), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(MessageViewController.textInputbarDidMove(_:)), name: NSNotification.Name.SLKTextInputbarDidMove, object: nil)
}
override func viewDidLoad() {
// Register a SLKTextView subclass, if you need any special appearance and/or behavior customisation.
self.registerClass(forTextView: MessageTextView.classForCoder())
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
// Register a UIView subclass, conforming to SLKTypingIndicatorProtocol, to use a custom typing indicator view.
self.registerClass(forTypingIndicatorView: TypingIndicatorView.classForCoder())
}
super.viewDidLoad()
self.commonInit()
// Example's configuration
self.configureDataSource()
self.configureActionItems()
// SLKTVC's configuration
self.bounces = true
self.shakeToClearEnabled = true
self.isKeyboardPanningEnabled = true
self.shouldScrollToBottomAfterKeyboardShows = false
self.isInverted = true
self.leftButton.setImage(UIImage(named: "icn_upload"), for: UIControlState())
self.leftButton.tintColor = UIColor.gray
self.rightButton.setTitle(NSLocalizedString("Send", comment: ""), for: UIControlState())
self.textInputbar.autoHideRightButton = true
self.textInputbar.maxCharCount = 256
self.textInputbar.counterStyle = .split
self.textInputbar.counterPosition = .top
self.textInputbar.editorTitle.textColor = UIColor.darkGray
self.textInputbar.editorLeftButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
self.textInputbar.editorRightButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
if DEBUG_CUSTOM_TYPING_INDICATOR == false {
self.typingIndicatorView!.canResignByTouch = true
}
self.tableView.separatorStyle = .none
self.tableView.register(MessageTableViewCell.classForCoder(), forCellReuseIdentifier: MessengerCellIdentifier)
self.autoCompletionView.register(MessageTableViewCell.classForCoder(), forCellReuseIdentifier: AutoCompletionCellIdentifier)
self.registerPrefixes(forAutoCompletion: ["@", "#", ":", "+:", "/"])
self.textView.placeholder = "Message";
self.textView.registerMarkdownFormattingSymbol("*", withTitle: "Bold")
self.textView.registerMarkdownFormattingSymbol("_", withTitle: "Italics")
self.textView.registerMarkdownFormattingSymbol("~", withTitle: "Strike")
self.textView.registerMarkdownFormattingSymbol("`", withTitle: "Code")
self.textView.registerMarkdownFormattingSymbol("```", withTitle: "Preformatted")
self.textView.registerMarkdownFormattingSymbol(">", withTitle: "Quote")
}
// MARK: - Lifeterm
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension MessageViewController {
// MARK: - Example's Configuration
func configureDataSource() {
var array = [Message]()
for _ in 0..<100 {
let words = Int((arc4random() % 40)+1)
let message = Message()
message.username = LoremIpsum.name()
message.text = LoremIpsum.words(withNumber: words)
array.append(message)
}
let reversed = array.reversed()
self.messages.append(contentsOf: reversed)
}
func configureActionItems() {
let arrowItem = UIBarButtonItem(image: UIImage(named: "icn_arrow_down"), style: .plain, target: self, action: #selector(MessageViewController.hideOrShowTextInputbar(_:)))
let editItem = UIBarButtonItem(image: UIImage(named: "icn_editing"), style: .plain, target: self, action: #selector(MessageViewController.editRandomMessage(_:)))
let typeItem = UIBarButtonItem(image: UIImage(named: "icn_typing"), style: .plain, target: self, action: #selector(MessageViewController.simulateUserTyping(_:)))
let appendItem = UIBarButtonItem(image: UIImage(named: "icn_append"), style: .plain, target: self, action: #selector(MessageViewController.fillWithText(_:)))
let pipItem = UIBarButtonItem(image: UIImage(named: "icn_pic"), style: .plain, target: self, action: #selector(MessageViewController.togglePIPWindow(_:)))
self.navigationItem.rightBarButtonItems = [arrowItem, pipItem, editItem, appendItem, typeItem]
}
// MARK: - Action Methods
func hideOrShowTextInputbar(_ sender: AnyObject) {
guard let buttonItem = sender as? UIBarButtonItem else {
return
}
let hide = !self.isTextInputbarHidden
let image = hide ? UIImage(named: "icn_arrow_up") : UIImage(named: "icn_arrow_down")
self.setTextInputbarHidden(hide, animated: true)
buttonItem.image = image
}
func fillWithText(_ sender: AnyObject) {
if self.textView.text.characters.count == 0 {
var sentences = Int(arc4random() % 4)
if sentences <= 1 {
sentences = 1
}
self.textView.text = LoremIpsum.sentences(withNumber: sentences)
}
else {
self.textView.slk_insertText(atCaretRange: " " + LoremIpsum.word())
}
}
func simulateUserTyping(_ sender: AnyObject) {
if !self.canShowTypingIndicator() {
return
}
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
guard let view = self.typingIndicatorProxyView as? TypingIndicatorView else {
return
}
let scale = UIScreen.main.scale
let imgSize = CGSize(width: kTypingIndicatorViewAvatarHeight*scale, height: kTypingIndicatorViewAvatarHeight*scale)
// This will cause the typing indicator to show after a delay ¯\_(ツ)_/¯
LoremIpsum.asyncPlaceholderImage(with: imgSize, completion: { (image) -> Void in
guard let cgImage = image?.cgImage else {
return
}
let thumbnail = UIImage(cgImage: cgImage, scale: scale, orientation: .up)
view.presentIndicator(withName: LoremIpsum.name(), image: thumbnail)
})
}
else {
self.typingIndicatorView!.insertUsername(LoremIpsum.name())
}
}
func didLongPressCell(_ gesture: UIGestureRecognizer) {
guard let view = gesture.view else {
return
}
if gesture.state != .began {
return
}
if #available(iOS 8, *) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.modalPresentationStyle = .popover
alertController.popoverPresentationController?.sourceView = view.superview
alertController.popoverPresentationController?.sourceRect = view.frame
alertController.addAction(UIAlertAction(title: "Edit Message", style: .default, handler: { [unowned self] (action) -> Void in
self.editCellMessage(gesture)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.navigationController?.present(alertController, animated: true, completion: nil)
}
else {
self.editCellMessage(gesture)
}
}
func editCellMessage(_ gesture: UIGestureRecognizer) {
guard let cell = gesture.view as? MessageTableViewCell else {
return
}
self.editingMessage = self.messages[cell.indexPath.row]
self.editText(self.editingMessage.text)
self.tableView.scrollToRow(at: cell.indexPath, at: .bottom, animated: true)
}
func editRandomMessage(_ sender: AnyObject) {
var sentences = Int(arc4random() % 10)
if sentences <= 1 {
sentences = 1
}
self.editText(LoremIpsum.sentences(withNumber: sentences))
}
func editLastMessage(_ sender: AnyObject?) {
if self.textView.text.characters.count > 0 {
return
}
let lastSectionIndex = self.tableView.numberOfSections-1
let lastRowIndex = self.tableView.numberOfRows(inSection: lastSectionIndex)-1
let lastMessage = self.messages[lastRowIndex]
self.editText(lastMessage.text)
self.tableView.scrollToRow(at: IndexPath(row: lastRowIndex, section: lastSectionIndex), at: .bottom, animated: true)
}
func togglePIPWindow(_ sender: AnyObject) {
if self.pipWindow == nil {
self.showPIPWindow(sender)
}
else {
self.hidePIPWindow(sender)
}
}
func showPIPWindow(_ sender: AnyObject) {
var frame = CGRect(x: self.view.frame.width - 60.0, y: 0.0, width: 50.0, height: 50.0)
frame.origin.y = self.textInputbar.frame.minY - 60.0
self.pipWindow = UIWindow(frame: frame)
self.pipWindow?.backgroundColor = UIColor.black
self.pipWindow?.layer.cornerRadius = 10
self.pipWindow?.layer.masksToBounds = true
self.pipWindow?.isHidden = false
self.pipWindow?.alpha = 0.0
UIApplication.shared.keyWindow?.addSubview(self.pipWindow!)
UIView.animate(withDuration: 0.25, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 1.0
})
}
func hidePIPWindow(_ sender: AnyObject) {
UIView.animate(withDuration: 0.3, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 0.0
}, completion: { [unowned self] (finished) -> Void in
self.pipWindow?.isHidden = true
self.pipWindow = nil
})
}
func textInputbarDidMove(_ note: Notification) {
guard let pipWindow = self.pipWindow else {
return
}
guard let userInfo = (note as NSNotification).userInfo else {
return
}
guard let value = userInfo["origin"] as? NSValue else {
return
}
var frame = pipWindow.frame
frame.origin.y = value.cgPointValue.y - 60.0
pipWindow.frame = frame
}
}
extension MessageViewController {
// MARK: - Overriden Methods
override func ignoreTextInputbarAdjustment() -> Bool {
return super.ignoreTextInputbarAdjustment()
}
override func forceTextInputbarAdjustment(for responder: UIResponder!) -> Bool {
if #available(iOS 8.0, *) {
guard let _ = responder as? UIAlertController else {
// On iOS 9, returning YES helps keeping the input view visible when the keyboard if presented from another app when using multi-tasking on iPad.
return UIDevice.current.userInterfaceIdiom == .pad
}
return true
}
else {
return UIDevice.current.userInterfaceIdiom == .pad
}
}
// Notifies the view controller that the keyboard changed status.
override func didChangeKeyboardStatus(_ status: SLKKeyboardStatus) {
switch status {
case .willShow:
print("Will Show")
case .didShow:
print("Did Show")
case .willHide:
print("Will Hide")
case .didHide:
print("Did Hide")
}
}
// Notifies the view controller that the text will update.
override func textWillUpdate() {
super.textWillUpdate()
}
// Notifies the view controller that the text did update.
override func textDidUpdate(_ animated: Bool) {
super.textDidUpdate(animated)
}
// Notifies the view controller when the left button's action has been triggered, manually.
override func didPressLeftButton(_ sender: Any!) {
super.didPressLeftButton(sender)
self.dismissKeyboard(true)
self.performSegue(withIdentifier: "Push", sender: nil)
}
// Notifies the view controller when the right button's action has been triggered, manually or by using the keyboard return key.
override func didPressRightButton(_ sender: Any!) {
// This little trick validates any pending auto-correction or auto-spelling just after hitting the 'Send' button
self.textView.refreshFirstResponder()
let message = Message()
message.username = LoremIpsum.name()
message.text = self.textView.text
let indexPath = IndexPath(row: 0, section: 0)
let rowAnimation: UITableViewRowAnimation = self.isInverted ? .bottom : .top
let scrollPosition: UITableViewScrollPosition = self.isInverted ? .bottom : .top
self.tableView.beginUpdates()
self.messages.insert(message, at: 0)
self.tableView.insertRows(at: [indexPath], with: rowAnimation)
self.tableView.endUpdates()
self.tableView.scrollToRow(at: indexPath, at: scrollPosition, animated: true)
// Fixes the cell from blinking (because of the transform, when using translucent cells)
// See https://github.com/slackhq/SlackTextViewController/issues/94#issuecomment-69929927
self.tableView.reloadRows(at: [indexPath], with: .automatic)
super.didPressRightButton(sender)
}
override func didPressArrowKey(_ keyCommand: UIKeyCommand?) {
guard let keyCommand = keyCommand else { return }
if keyCommand.input == UIKeyInputUpArrow && self.textView.text.characters.count == 0 {
self.editLastMessage(nil)
}
else {
super.didPressArrowKey(keyCommand)
}
}
override func keyForTextCaching() -> String? {
return Bundle.main.bundleIdentifier
}
// Notifies the view controller when the user has pasted a media (image, video, etc) inside of the text view.
override func didPasteMediaContent(_ userInfo: [AnyHashable: Any]) {
super.didPasteMediaContent(userInfo)
let mediaType = (userInfo[SLKTextViewPastedItemMediaType] as? NSNumber)?.intValue
let contentType = userInfo[SLKTextViewPastedItemContentType]
let data = userInfo[SLKTextViewPastedItemData]
print("didPasteMediaContent : \(contentType) (type = \(mediaType) | data : \(data))")
}
// Notifies the view controller when a user did shake the device to undo the typed text
override func willRequestUndo() {
super.willRequestUndo()
}
// Notifies the view controller when tapped on the right "Accept" button for commiting the edited text
override func didCommitTextEditing(_ sender: Any) {
self.editingMessage.text = self.textView.text
self.tableView.reloadData()
super.didCommitTextEditing(sender)
}
// Notifies the view controller when tapped on the left "Cancel" button
override func didCancelTextEditing(_ sender: Any) {
super.didCancelTextEditing(sender)
}
override func canPressRightButton() -> Bool {
return super.canPressRightButton()
}
override func canShowTypingIndicator() -> Bool {
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
return true
}
else {
return super.canShowTypingIndicator()
}
}
override func shouldProcessText(forAutoCompletion text: String) -> Bool {
return true
}
override func didChangeAutoCompletionPrefix(_ prefix: String, andWord word: String) {
var array:Array<String> = []
let wordPredicate = NSPredicate(format: "self BEGINSWITH[c] %@", word);
self.searchResult = nil
if prefix == "@" {
if word.characters.count > 0 {
array = self.users.filter { wordPredicate.evaluate(with: $0) };
}
else {
array = self.users
}
}
else if prefix == "#" {
if word.characters.count > 0 {
array = self.channels.filter { wordPredicate.evaluate(with: $0) };
}
else {
array = self.channels
}
}
else if (prefix == ":" || prefix == "+:") && word.characters.count > 0 {
array = self.emojis.filter { wordPredicate.evaluate(with: $0) };
}
else if prefix == "/" && self.foundPrefixRange.location == 0 {
if word.characters.count > 0 {
array = self.commands.filter { wordPredicate.evaluate(with: $0) };
}
else {
array = self.commands
}
}
var show = false
if array.count > 0 {
let sortedArray = array.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
self.searchResult = sortedArray
show = sortedArray.count > 0
}
self.showAutoCompletionView(show)
}
override func heightForAutoCompletionView() -> CGFloat {
guard let searchResult = self.searchResult else {
return 0
}
let cellHeight = self.autoCompletionView.delegate?.tableView!(self.autoCompletionView, heightForRowAt: IndexPath(row: 0, section: 0))
guard let height = cellHeight else {
return 0
}
return height * CGFloat(searchResult.count)
}
}
extension MessageViewController {
// MARK: - UITableViewDataSource Methods
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return self.messages.count
}
else {
if let searchResult = self.searchResult {
return searchResult.count
}
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableView {
return self.messageCellForRowAtIndexPath(indexPath)
}
else {
return self.autoCompletionCellForRowAtIndexPath(indexPath)
}
}
func messageCellForRowAtIndexPath(_ indexPath: IndexPath) -> MessageTableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: MessengerCellIdentifier) as! MessageTableViewCell
if cell.gestureRecognizers?.count == nil {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(MessageViewController.didLongPressCell(_:)))
cell.addGestureRecognizer(longPress)
}
let message = self.messages[(indexPath as NSIndexPath).row]
cell.titleLabel.text = message.username
cell.bodyLabel.text = message.text
cell.indexPath = indexPath
cell.usedForMessage = true
// Cells must inherit the table view's transform
// This is very important, since the main table view may be inverted
cell.transform = self.tableView.transform
return cell
}
func autoCompletionCellForRowAtIndexPath(_ indexPath: IndexPath) -> MessageTableViewCell {
let cell = self.autoCompletionView.dequeueReusableCell(withIdentifier: AutoCompletionCellIdentifier) as! MessageTableViewCell
cell.indexPath = indexPath
cell.selectionStyle = .default
guard let searchResult = self.searchResult else {
return cell
}
guard let prefix = self.foundPrefix else {
return cell
}
var text = searchResult[(indexPath as NSIndexPath).row]
if prefix == "#" {
text = "# " + text
}
else if prefix == ":" || prefix == "+:" {
text = ":\(text):"
}
cell.titleLabel.text = text
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == self.tableView {
let message = self.messages[(indexPath as NSIndexPath).row]
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .left
let pointSize = MessageTableViewCell.defaultFontSize()
let attributes = [
NSFontAttributeName : UIFont.systemFont(ofSize: pointSize),
NSParagraphStyleAttributeName : paragraphStyle
]
var width = tableView.frame.width-kMessageTableViewCellAvatarHeight
width -= 25.0
let titleBounds = (message.username as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let bodyBounds = (message.text as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
if message.text.characters.count == 0 {
return 0
}
var height = titleBounds.height
height += bodyBounds.height
height += 40
if height < kMessageTableViewCellMinimumHeight {
height = kMessageTableViewCellMinimumHeight
}
return height
}
else {
return kMessageTableViewCellMinimumHeight
}
}
// MARK: - UITableViewDelegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == self.autoCompletionView {
guard let searchResult = self.searchResult else {
return
}
var item = searchResult[(indexPath as NSIndexPath).row]
if self.foundPrefix == "@" && self.foundPrefixRange.location == 0 {
item += ":"
}
else if self.foundPrefix == ":" || self.foundPrefix == "+:" {
item += ":"
}
item += " "
self.acceptAutoCompletion(with: item, keepPrefix: true)
}
}
}
extension MessageViewController {
// MARK: - UIScrollViewDelegate Methods
// Since SLKTextViewController uses UIScrollViewDelegate to update a few things, it is important that if you override this method, to call super.
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
}
}
extension MessageViewController {
// MARK: - UITextViewDelegate Methods
override func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return true
}
override func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
// Since SLKTextViewController uses UIScrollViewDelegate to update a few things, it is important that if you override this method, to call super.
return true
}
override func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return super.textView(textView, shouldChangeTextIn: range, replacementText: text)
}
override func textView(_ textView: SLKTextView, shouldOfferFormattingForSymbol symbol: String) -> Bool {
if symbol == ">" {
let selection = textView.selectedRange
// The Quote formatting only applies new paragraphs
if selection.location == 0 && selection.length > 0 {
return true
}
// or older paragraphs too
let prevString = (textView.text as NSString).substring(with: NSMakeRange(selection.location-1, 1))
if CharacterSet.newlines.contains(UnicodeScalar((prevString as NSString).character(at: 0))!) {
return true
}
return false
}
return super.textView(textView, shouldOfferFormattingForSymbol: symbol)
}
override func textView(_ textView: SLKTextView, shouldInsertSuffixForFormattingWithSymbol symbol: String, prefixRange: NSRange) -> Bool {
if symbol == ">" {
return false
}
return super.textView(textView, shouldInsertSuffixForFormattingWithSymbol: symbol, prefixRange: prefixRange)
}
}
|
mit
|
930b7edcdceee64d506de70ee6aaa662
| 35.01992 | 214 | 0.603215 | 5.197969 | false | false | false | false |
zats/Injector
|
Scripts/generator.swift
|
1
|
4294
|
#!/usr/bin/env xcrun swift
// Generates a Swift file with implementation of injection for a ridicolously high number of arguments
import Foundation
let generics = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
let padding = " "
extension Array {
subscript(safe index: Int) -> Element? {
return indices ~= index ? self[index] : .None
}
}
func genericTypeForPosition(x: Int) -> String {
let max = generics.count
switch x {
case _ where x < max: return generics[x % max]
default: return generics[x / max - 1] + generics[x % max]
}
}
func commaConcat(xs: [String]) -> String {
return xs.joinWithSeparator(", ")
}
func curryDefinitionGenerator(arguments arguments: Int) -> String {
let genericParameters = (0..<arguments).map(genericTypeForPosition) // ["A", "B", "C"]
let genericTypeDefinition = "<\(commaConcat(genericParameters))>" // "<A, B, C>"
let inputParameters = Array(genericParameters[0..<arguments - 1]) // ["A", "B"]
let lowerFunctionArguments = inputParameters.map { "`\($0.lowercaseString)`" } // ["`a`", "`b`"]
let returnType = genericParameters.last! // "C"
let functionArguments = "(\(commaConcat(inputParameters)))" // "(A, B)"
let innerFunctionArguments = commaConcat(lowerFunctionArguments) // "`a`, `b`"
let guards = zip(inputParameters, lowerFunctionArguments).map{ A, a in // guard let a: A = get() else { throw InjectorError.TypeNotFound(A) }
return "guard let \(a): \(A) = get() else { throw InjectorError.TypeNotFound(\(A)) }"
}
let functionDefinition = "function(\(innerFunctionArguments))" // return function(`a`, `b`)
let joinedGuards = guards.joinWithSeparator("\n\(padding)")
let implementation = "\(joinedGuards)\n\(padding)return \(functionDefinition)" // guard let b: B = get() else { throw InjectorError.TypeNotFound(B) } return f(a, b)
let documentation = [
"/**",
" Injects specified method using arguments that has been registered with the `injector` instance.",
" If an argument has not been registered, function is going to throw.",
" */"
]
let curry = [
"public func inject\(genericTypeDefinition)(function: \(functionArguments) -> \(returnType)) throws -> \(returnType) {",
"\(padding)\(implementation)",
"}"
]
return documentation.joinWithSeparator("\n") + "\n" + curry.joinWithSeparator("\n")
}
func errorDefinition() -> String {
let components = [
"/**",
" Error being thrown during injection if an instance has not been registered with injector.",
" */",
"public enum InjectorError: ErrorType {",
"\(padding)/**",
"\(padding) Error being thrown during injection if an instance has not been registered with injector.",
"\(padding) Contains first type that has not been registered with injector.",
"\(padding) */",
"\(padding)case TypeNotFound(Any.Type)",
"}"
]
return components.joinWithSeparator("\n")
}
func wrapInExtension(generated: String) -> String {
let paddedGenerated = generated.componentsSeparatedByString("\n").joinWithSeparator("\n\(padding)")
let extesnionComponents = [
"extension Injector {",
"\(padding)\(paddedGenerated)",
"}"
]
return extesnionComponents.joinWithSeparator("\n")
}
print("Generating 💬")
let input = Process.arguments[safe: 1] ?? "20"
let limit = Int(input)!
let start = 2
let curries = (start..<limit).map { curryDefinitionGenerator(arguments: $0) }
let joinedCurries = curries.joinWithSeparator("\n\n") + "\n"
let output = errorDefinition() + "\n\n" + wrapInExtension(joinedCurries)
let outputPath = "Sources/Injecting.swift"
let currentPath = NSURL(fileURLWithPath: NSFileManager.defaultManager().currentDirectoryPath)
let currySwiftPath = currentPath.URLByAppendingPathComponent(outputPath)
do {
try output.writeToURL(currySwiftPath, atomically: true, encoding: NSUTF8StringEncoding)
} catch let e as NSError {
print("An error occurred while saving the generated functions. Error: \(e)")
}
print("Done, curry functions files written at \(outputPath) 👍")
|
mit
|
04ed170bc6c0f580b4bde72d838ca1a3
| 37.63964 | 169 | 0.64389 | 4.049103 | false | false | false | false |
languageininteraction/VowelSpaceTravel
|
mobile/Vowel Space Travel iOS/Vowel Space Travel iOS/DownloadBarView.swift
|
1
|
1498
|
//
// DownloadBarView.swift
// Vowel Space Travel iOS
//
// Created by Wessel Stoop on 21/08/15.
// Copyright (c) 2015 Radboud University. All rights reserved.
//
import Foundation
import UIKit
class DownloadBarView : UIView
{
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override init(frame : CGRect)
{
super.init(frame : frame)
self.updatePercentage(0)
}
func drawFilledInPath(path : UIBezierPath, color : UIColor)
{
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.CGPath
shapeLayer.fillColor = color.CGColor
self.layer.addSublayer(shapeLayer)
}
func updatePercentage(percentage : CGFloat)
{
let topLeft : CGPoint = CGPoint(x: self.frame.minX, y: self.frame.maxY-percentage*self.frame.height)
let topRight : CGPoint = CGPoint(x: self.frame.maxX, y: self.frame.maxY-percentage*self.frame.height)
let bottomLeft : CGPoint = CGPoint(x: self.frame.minX, y:self.frame.maxY)
let bottomRight : CGPoint = CGPoint(x: self.frame.maxX, y: self.frame.maxY)
let myBezier = UIBezierPath()
myBezier.moveToPoint(topLeft)
myBezier.addLineToPoint(topRight)
myBezier.addLineToPoint(bottomRight)
myBezier.addLineToPoint(bottomLeft)
self.drawFilledInPath(myBezier, color: UIColor(hue: 0.83, saturation: 0.3, brightness: 0.55, alpha: 1))
}
}
|
gpl-2.0
|
9088b03d3f1e2f7d49515cf5fd1fa85a
| 28.98 | 111 | 0.645527 | 4.081744 | false | false | false | false |
svdo/swift-SecurityExtensions
|
SecurityExtensionsTests/SecCertificateTests.swift
|
1
|
1056
|
import Quick
import Nimble
import SecurityExtensions
class SecCertificateTests: QuickSpec {
override func spec() {
let bundle = Bundle(for: type(of: self))
let filePath = bundle.path(forResource: "Staat der Nederlanden EV Root CA", ofType: "der")!
it("can load from file") {
let cert = SecCertificate.create(derEncodedFile: filePath)
expect(cert).toNot(beNil())
}
it("cannot load from nonexisting file") {
let cert = SecCertificate.create(derEncodedFile: "non-existing")
expect(cert).to(beNil())
}
it("can return the cert data") {
let cert = SecCertificate.create(derEncodedFile: filePath)!
let certData = cert.data
let fileData = NSData(contentsOfFile: filePath)!
expect(certData) == fileData as Data
}
it("can return the public key") {
let cert = SecCertificate.create(derEncodedFile: filePath)!
expect(cert.publicKey).toNot(beNil())
}
}
}
|
mit
|
00aba0f8c25fd80c5b9e381c37bf5fd4
| 31 | 99 | 0.602273 | 4.551724 | false | false | false | false |
MarceloOscarJose/DynamicTextField
|
DynamicTextField/DynamicFieldDelegate.swift
|
1
|
4409
|
//
// DynamicTextFieldDelegate.swift
// TrastornoBipolar
//
// Created by Marcelo Oscar José on 10/26/16.
// Copyright © 2016 Marcelo Oscar José. All rights reserved.
//
import UIKit
open class DynamicFieldDelegate: UITextField, UITextFieldDelegate {
// MARK - Properties
private var maxLength: Int = Int.max
private var maskText : String?
private var validationRules: [DynamicFieldRule] = []
private var entryType: String = DynamicFieldEntry.Default
private var fieldError: String = ""
// MARK - Properties Setters
func setMaxLength(max: Int) {
self.maxLength = max
}
func setMask(mask: String) {
self.maskText = mask
}
func setEntryType(entry: String) {
self.entryType = entry
}
func setValidationRules(rules: [DynamicFieldRule]) {
self.validationRules = rules
}
func getFieldError() -> String {
return self.fieldError
}
// MARK - Lifecycle
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.delegate = self
}
// MARK - Delegate
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard string.characters.count > 0 else {
return true
}
let currentText = textField.text ?? ""
let futureText = (currentText as NSString).replacingCharacters(in: range, with: string)
let mask = maskText ?? ""
if futureText.characters.count <= self.maxLength {
if string.range(of: self.entryType, options: .regularExpression) == nil {
return false
}
if mask.characters.count == 0 {
return true
}
if futureText.characters.count > mask.characters.count {
return false
} else {
let maskValue = mask[mask.index(mask.startIndex, offsetBy: (futureText.characters.count-1))]
switch maskValue {
case "d": return string.range(of: DynamicFieldEntry.Numeric, options: .regularExpression) != nil
case "s": return string.range(of: DynamicFieldEntry.Alpha, options: .regularExpression) != nil
case "*": return true
default:
textField.text = textField.text! + String(maskValue)
return self.textField(textField, shouldChangeCharactersIn: range, replacementString: string)
}
}
}
return false
}
// MARK - Private
func isValid() -> Bool {
let text = self.text ?? ""
var result = false
for rule in self.validationRules {
let regex = try? NSRegularExpression(pattern: rule.regex, options: .caseInsensitive)
result = regex?.firstMatch(in: self.text!, options: [], range: NSMakeRange(0, text.characters.count)) != nil
if result == false {
self.toggleError(error: rule.error, show: true)
break
}
}
if result {
self.toggleError(error: "", show: false)
}
return result
}
func toggleError(error: String, show: Bool) {
self.fieldError = error
if show {
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.red.cgColor
} else {
self.layer.borderWidth = 0
self.layer.borderColor = UIColor.clear.cgColor
}
}
}
/*
class CurrencyFormatter : NumberFormatter, FormatterProtocol {
override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, range rangep: UnsafeMutablePointer<NSRange>?) throws {
guard obj != nil else { return }
let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
obj?.pointee = NSNumber(value: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits))))
}
func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition {
return textInput.position(from: position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position
}
}*/
|
gpl-3.0
|
ef609c863bf76828d45a7bc3ab86ebfc
| 33.155039 | 159 | 0.606219 | 4.758099 | false | false | false | false |
aabrahamyan/similar_titles
|
SimilarTitles/SimilarTitles/Location/STLocationManager.swift
|
1
|
2261
|
//
// STLocationManager.swift
// SimilarTitles
//
// Created by Armen Abrahamyan on 1/29/16.
// Copyright © 2016 Armen Abrahamyan. All rights reserved.
//
import Foundation
import CoreLocation
/**
* Provides methods to get user's current location over 'STLocationManager' wrapper
*/
protocol STLocationManagerDelegate {
func succeedUserLocation(location: CLLocationCoordinate2D?)
func failedUserLocation(error: NSError?)
}
/**
* Wrapper over CLLocationManager, handles basic location requests and handling of delegates
*/
class STLocationManager: NSObject, CLLocationManagerDelegate {
// MARK: Members and lazy member
lazy var locationManager = CLLocationManager()
var currentUserLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
// Delegate one
var delegate: STLocationManagerDelegate?
//MARK: Constructor
init(accuracy: CLLocationAccuracy) {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = accuracy
// Request location
requestStLocation()
}
//MARK: Hit first time location
private func requestStLocation() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
locationManager.requestLocation();
} else {
locationManager.requestWhenInUseAuthorization()
}
}
// MARK: CLLocationManagerDelegate part
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if currentUserLocation.latitude == 0 && currentUserLocation.longitude == 0 {
currentUserLocation = (locations.last?.coordinate)!
delegate?.succeedUserLocation(currentUserLocation)
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error getting location: \(error.localizedDescription)")
delegate?.failedUserLocation(error)
}
}
|
apache-2.0
|
a5b35a3f2d08cd503f4a0e05f6f8b4b0
| 30.830986 | 114 | 0.702655 | 5.678392 | false | false | false | false |
WayneEld/Whirl
|
Indicate/LabrinthIndicator.swift
|
1
|
20255
|
//
// LabrinthIndicator.swift
// Indicate
//
// Created by Wayne Eldridge on 2017/03/24.
// Copyright © 2017 Wayne Eldridge. All rights reserved.
//
import UIKit
//TODO: Change to private. Oublic is from inicate class
//TODO: Make all funcs private
//TODO: Move current view call to call from Indicate class
class LabIndicator {
private static let lineWidth = CGFloat(1)
private static let lineColor = UIColor.black.cgColor
private static let labSize = CGFloat(30)
private static let drawDuration = CFTimeInterval(0)
private static var backDrop = UIView()
private static var circle1 = CAShapeLayer()
private static var circle2 = CAShapeLayer()
var currentView = UIApplication.shared.windows[0].rootViewController
//MARK: - Circle 3 Strcuture
private struct Circle3 {
static var circle3_1 = CAShapeLayer()
static var circle3_2 = CAShapeLayer()
static var circle3_3 = CAShapeLayer()
static var circle3_4 = CAShapeLayer()
}
//MARK: - Circle 4 Strcuture
private struct Circle4 {
static var circle4_1 = CAShapeLayer()
static var circle4_2 = CAShapeLayer()
static var circle4_3 = CAShapeLayer()
static var circle4_4 = CAShapeLayer()
static var circle4_5 = CAShapeLayer()
}
//MARK: - Show Indicator
public func showIndicator(){
//--Background View
drawBackDrop()
//--Drawn Circles
drawLab1(percentage: 0.95, size: LabIndicator.labSize, duration: 5)
drawLab2(percentage: 0.85, size: LabIndicator.labSize * 0.8, duration: 3)
drawLab3(size: LabIndicator.labSize * 0.6, duration: 3.5)
drawLab4(size: LabIndicator.labSize * 0.4, duration: 4)
}
//MARK: - Hide Indicator
public func hideIndicator(){
LabIndicator.backDrop.removeFromSuperview()
LabIndicator.circle1.removeFromSuperlayer()
LabIndicator.circle2.removeFromSuperlayer()
//-Circle 3
LabIndicator.Circle3.circle3_1.removeFromSuperlayer()
LabIndicator.Circle3.circle3_2.removeFromSuperlayer()
LabIndicator.Circle3.circle3_3.removeFromSuperlayer()
LabIndicator.Circle3.circle3_4.removeFromSuperlayer()
//--Circle 4
LabIndicator.Circle4.circle4_1.removeFromSuperlayer()
LabIndicator.Circle4.circle4_2.removeFromSuperlayer()
LabIndicator.Circle4.circle4_3.removeFromSuperlayer()
LabIndicator.Circle4.circle4_4.removeFromSuperlayer()
LabIndicator.Circle4.circle4_5.removeFromSuperlayer()
}
//MARK: - Back Drop
private func drawBackDrop(){
//--Back Drop View
let backDropView = UIView()
let backDropSize = LabIndicator.labSize * 2.4
backDropView.frame = CGRect(x: (currentView?.view.frame.size.width)!/2 - ((backDropSize)/2), y: (currentView?.view.frame.size.height)!/2 - ((backDropSize)/2), width: (backDropSize), height: (backDropSize))
backDropView.layer.borderWidth = 1
backDropView.layer.masksToBounds = false
backDropView.layer.borderColor = UIColor.clear.cgColor
backDropView.layer.cornerRadius = backDropView.frame.height/2
backDropView.clipsToBounds = true
//--Adding back drop view
currentView?.view.addSubview(backDropView)
LabIndicator.backDrop = backDropView
//--Adding blurred view to back drop
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = backDropView.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.alpha = 0.7
backDropView.addSubview(blurEffectView)
}
//MARK: - Circle 1
private func drawLab1(percentage: Double, size: CGFloat, duration: Double){
let percentCircle = percentage
let circleCenter = CGPoint(x: (currentView?.view.frame.size.width)!/2, y: (currentView?.view.frame.size.height)!/2)
let circleRadius = size
let startAngle = CGFloat(0)
let endAngle = CGFloat((.pi * 2 * percentCircle))
let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle, endAngle:endAngle, clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = LabIndicator.lineColor
shapeLayer.lineWidth = LabIndicator.lineWidth
shapeLayer.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer.bounds = shapeLayer.frame
currentView?.view.layer.addSublayer(shapeLayer)
let rotationAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = startAngle
animation.toValue = Float.pi * 2
animation.duration = duration
animation.repeatCount = Float.infinity
return animation
}()
shapeLayer.add(rotationAnimation, forKey: "rotation")
LabIndicator.circle1 = shapeLayer
shapeLayer.strokeEnd = endAngle
let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation.duration = LabIndicator.drawDuration
drawAnimation.fromValue = Int(startAngle)
drawAnimation.toValue = Int(endAngle)
drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
shapeLayer.add(drawAnimation, forKey: nil)
}
//MARK: - Circle 2
private func drawLab2(percentage: Double, size: CGFloat, duration: Double){
let percentCircle = percentage
let circleCenter = CGPoint(x: (currentView?.view.frame.size.width)!/2, y: (currentView?.view.frame.size.height)!/2)
let circleRadius = size
let startAngle = CGFloat(0)
let endAngle = CGFloat((.pi * 2 * percentCircle))
let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle, endAngle:endAngle, clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = LabIndicator.lineColor
shapeLayer.lineWidth = LabIndicator.lineWidth
shapeLayer.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer.bounds = shapeLayer.frame
currentView?.view.layer.addSublayer(shapeLayer)
let rotationAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = startAngle
animation.toValue = Float.pi * 2
animation.duration = duration
animation.repeatCount = Float.infinity
return animation
}()
shapeLayer.add(rotationAnimation, forKey: "rotation")
LabIndicator.circle2 = shapeLayer
shapeLayer.strokeEnd = endAngle
let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation.duration = LabIndicator.drawDuration
drawAnimation.fromValue = Int(startAngle)
drawAnimation.toValue = Int(endAngle)
drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
shapeLayer.add(drawAnimation, forKey: nil)
}
//MARK: - Circle 3
private func drawLab3(size: CGFloat, duration: Double){
let circleCenter = CGPoint(x: (currentView?.view.frame.size.width)!/2, y: (currentView?.view.frame.size.height)!/2)
let circleRadius = size
let startAngle = CGFloat(0)
let endAngle = CGFloat(Float.pi/2)
let startAngle2 = CGFloat((Float.pi * 2)/3)
let endAngle2 = CGFloat((Float.pi * 3)/4)
let startAngle3 = CGFloat((Float.pi * 5)/6)
let endAngle3 = CGFloat((Float.pi * 3)/2)
let startAngle4 = CGFloat((Float.pi * 5)/3)
let endAngle4 = CGFloat((Float.pi * 11)/6)
let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle, endAngle:endAngle, clockwise: true)
let circlePath2 = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle2, endAngle:endAngle2, clockwise: true)
let circlePath3 = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle3, endAngle:endAngle3, clockwise: true)
let circlePath4 = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle4, endAngle:endAngle4, clockwise: true)
//--Shape 1
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = LabIndicator.lineColor
shapeLayer.lineWidth = LabIndicator.lineWidth
shapeLayer.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer.bounds = shapeLayer.frame
currentView?.view.layer.addSublayer(shapeLayer)
//--Shape 2
let shapeLayer2 = CAShapeLayer()
shapeLayer2.path = circlePath2.cgPath
shapeLayer2.fillColor = UIColor.clear.cgColor
shapeLayer2.strokeColor = LabIndicator.lineColor
shapeLayer2.lineWidth = LabIndicator.lineWidth
shapeLayer2.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer2.bounds = shapeLayer2.frame
currentView?.view.layer.addSublayer(shapeLayer2)
//--Shape 3
let shapeLayer3 = CAShapeLayer()
shapeLayer3.path = circlePath3.cgPath
shapeLayer3.fillColor = UIColor.clear.cgColor
shapeLayer3.strokeColor = LabIndicator.lineColor
shapeLayer3.lineWidth = LabIndicator.lineWidth
shapeLayer3.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer3.bounds = shapeLayer3.frame
currentView?.view.layer.addSublayer(shapeLayer3)
//--Shape 4
let shapeLayer4 = CAShapeLayer()
shapeLayer4.path = circlePath4.cgPath
shapeLayer4.fillColor = UIColor.clear.cgColor
shapeLayer4.strokeColor = LabIndicator.lineColor
shapeLayer4.lineWidth = LabIndicator.lineWidth
shapeLayer4.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer4.bounds = shapeLayer4.frame
currentView?.view.layer.addSublayer(shapeLayer4)
let rotationAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = startAngle
animation.toValue = Float.pi * 2
animation.duration = duration
animation.repeatCount = Float.infinity
return animation
}()
shapeLayer.add(rotationAnimation, forKey: "rotation")
shapeLayer2.add(rotationAnimation, forKey: "rotation")
shapeLayer3.add(rotationAnimation, forKey: "rotation")
shapeLayer4.add(rotationAnimation, forKey: "rotation")
LabIndicator.Circle3.circle3_1 = shapeLayer
LabIndicator.Circle3.circle3_2 = shapeLayer2
LabIndicator.Circle3.circle3_3 = shapeLayer3
LabIndicator.Circle3.circle3_4 = shapeLayer4
shapeLayer.strokeEnd = endAngle
let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation.duration = LabIndicator.drawDuration
drawAnimation.fromValue = Int(startAngle)
drawAnimation.toValue = Int(endAngle)
drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
shapeLayer.add(drawAnimation, forKey: "1")
shapeLayer2.strokeEnd = endAngle2
let drawAnimation2 = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation2.duration = LabIndicator.drawDuration
drawAnimation2.fromValue = Int(startAngle2)
drawAnimation2.toValue = Int(endAngle2)
drawAnimation2.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
shapeLayer2.add(drawAnimation2, forKey: "2")
/*
shapeLayer3.strokeEnd = endAngle3
let drawAnimation3 = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation3.duration = LabIndicator.drawDuration
drawAnimation3.fromValue = Int(startAngle3)
drawAnimation3.toValue = Int(endAngle3)
drawAnimation3.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
shapeLayer3.add(drawAnimation3, forKey: nil)
*/
/*
shapeLayer4.strokeEnd = endAngle4
let drawAnimation4 = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation4.duration = LabIndicator.drawDuration
drawAnimation4.fromValue = Int(startAngle4)
drawAnimation4.toValue = Int(endAngle4)
drawAnimation4.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
shapeLayer4.add(drawAnimation4, forKey: nil)
*/
}
//MARK: - Circle 4
private func drawLab4(size: CGFloat, duration: Double){
let circleCenter = CGPoint(x: (currentView?.view.frame.size.width)!/2, y: (currentView?.view.frame.size.height)!/2)
let circleRadius = size
let startAngle = CGFloat((Float.pi * 11)/6)
let endAngle = CGFloat((Float.pi )/6)
let startAngle2 = CGFloat((Float.pi)/4)
let endAngle2 = CGFloat((Float.pi )/3)
let startAngle3 = CGFloat((Float.pi )/2)
let endAngle3 = CGFloat((Float.pi * 2)/3)
let startAngle4 = CGFloat((Float.pi * 3)/4)
let endAngle4 = CGFloat((Float.pi * 5)/4)
let startAngle5 = CGFloat((Float.pi * 4)/3)
let endAngle5 = CGFloat((Float.pi * 7)/4)
let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle, endAngle:endAngle, clockwise: true)
let circlePath2 = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle2, endAngle:endAngle2, clockwise: true)
let circlePath3 = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle3, endAngle:endAngle3, clockwise: true)
let circlePath4 = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle4, endAngle:endAngle4, clockwise: true)
let circlePath5 = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle5, endAngle:endAngle5, clockwise: true)
//--Shape 1
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = LabIndicator.lineColor
shapeLayer.lineWidth = LabIndicator.lineWidth
shapeLayer.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer.bounds = shapeLayer.frame
currentView?.view.layer.addSublayer(shapeLayer)
//--Shape 2
let shapeLayer2 = CAShapeLayer()
shapeLayer2.path = circlePath2.cgPath
shapeLayer2.fillColor = UIColor.clear.cgColor
shapeLayer2.strokeColor = LabIndicator.lineColor
shapeLayer2.lineWidth = LabIndicator.lineWidth
shapeLayer2.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer2.bounds = shapeLayer2.frame
currentView?.view.layer.addSublayer(shapeLayer2)
//--Shape 3
let shapeLayer3 = CAShapeLayer()
shapeLayer3.path = circlePath3.cgPath
shapeLayer3.fillColor = UIColor.clear.cgColor
shapeLayer3.strokeColor = LabIndicator.lineColor
shapeLayer3.lineWidth = LabIndicator.lineWidth
shapeLayer3.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer3.bounds = shapeLayer3.frame
currentView?.view.layer.addSublayer(shapeLayer3)
//--Shape 4
let shapeLayer4 = CAShapeLayer()
shapeLayer4.path = circlePath4.cgPath
shapeLayer4.fillColor = UIColor.clear.cgColor
shapeLayer4.strokeColor = LabIndicator.lineColor
shapeLayer4.lineWidth = LabIndicator.lineWidth
shapeLayer4.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer4.bounds = shapeLayer4.frame
currentView?.view.layer.addSublayer(shapeLayer4)
//--Shape 5
let shapeLayer5 = CAShapeLayer()
shapeLayer5.path = circlePath5.cgPath
shapeLayer5.fillColor = UIColor.clear.cgColor
shapeLayer5.strokeColor = LabIndicator.lineColor
shapeLayer5.lineWidth = LabIndicator.lineWidth
shapeLayer5.frame = CGRect(x: ((currentView?.view.frame.size.width)!/2) - (circleRadius/2), y: ((currentView?.view.frame.size.height)!/2) - (circleRadius/2), width: circleRadius, height: circleRadius)
shapeLayer5.bounds = shapeLayer5.frame
currentView?.view.layer.addSublayer(shapeLayer5)
let rotationAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = startAngle
animation.toValue = startAngle + CGFloat((Float.pi * 2))
animation.duration = duration
animation.repeatCount = Float.infinity
return animation
}()
shapeLayer.add(rotationAnimation, forKey: nil)
shapeLayer2.add(rotationAnimation, forKey: nil)
shapeLayer3.add(rotationAnimation, forKey: nil)
shapeLayer4.add(rotationAnimation, forKey: nil)
shapeLayer5.add(rotationAnimation, forKey: nil)
LabIndicator.Circle4.circle4_1 = shapeLayer
LabIndicator.Circle4.circle4_2 = shapeLayer2
LabIndicator.Circle4.circle4_3 = shapeLayer3
LabIndicator.Circle4.circle4_4 = shapeLayer4
LabIndicator.Circle4.circle4_5 = shapeLayer5
}
}
|
mit
|
6aa87f1463ee1708e02ea868ae690467
| 41.020747 | 213 | 0.652217 | 4.876956 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/Post/EditPostViewController.swift
|
1
|
11301
|
import UIKit
class EditPostViewController: UIViewController {
// MARK: - Editor Factory
private let editorFactory = EditorFactory()
// MARK: - Configurations
/// appear instantly, without animations
@objc var showImmediately: Bool = false
/// appear with the media picker open
@objc var openWithMediaPicker: Bool = false
/// appear with the post epilogue visible
@objc var openWithPostPost: Bool = false
/// appear with media pre-inserted into the post
var insertedMedia: [Media]? = nil
/// is editing a reblogged post
var postIsReblogged = false
/// the entry point for the editor
var entryPoint: PostEditorEntryPoint = .unknown
private let loadAutosaveRevision: Bool
@objc fileprivate(set) var post: Post?
private let prompt: BloggingPrompt?
fileprivate var hasShownEditor = false
fileprivate var editingExistingPost = false
fileprivate let blog: Blog
fileprivate lazy var postPost: PostPostViewController = {
return UIStoryboard(name: "PostPost", bundle: nil).instantiateViewController(withIdentifier: "PostPostViewController") as! PostPostViewController
}()
@objc var onClose: ((_ changesSaved: Bool) -> ())?
@objc var afterDismiss: (() -> Void)?
override var modalPresentationStyle: UIModalPresentationStyle {
didSet(newValue) {
// make sure this view is transparent with the previous VC visible
super.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
}
}
override var modalTransitionStyle: UIModalTransitionStyle {
didSet(newValue) {
super.modalTransitionStyle = .coverVertical
}
}
/// Initialize as an editor with the provided post
///
/// - Parameter post: post to edit
@objc convenience init(post: Post, loadAutosaveRevision: Bool = false) {
self.init(post: post, blog: post.blog, loadAutosaveRevision: loadAutosaveRevision)
}
/// Initialize as an editor to create a new post for the provided blog
///
/// - Parameter blog: blog to create a new post for
@objc convenience init(blog: Blog) {
self.init(post: nil, blog: blog)
}
/// Initialize as an editor to create a new post for the provided blog and prompt
///
/// - Parameter blog: blog to create a new post for
/// - Parameter prompt: blogging prompt to configure the new post for
convenience init(blog: Blog, prompt: BloggingPrompt) {
self.init(post: nil, blog: blog, prompt: prompt)
}
/// Initialize as an editor with a specified post to edit and blog to post too.
///
/// - Parameters:
/// - post: the post to edit
/// - blog: the blog to create a post for, if post is nil
/// - Note: it's preferable to use one of the convenience initializers
fileprivate init(post: Post?, blog: Blog, loadAutosaveRevision: Bool = false, prompt: BloggingPrompt? = nil) {
self.post = post
self.loadAutosaveRevision = loadAutosaveRevision
if let post = post {
if !post.originalIsDraft() {
editingExistingPost = true
}
post.fixLocalMediaURLs()
}
self.blog = blog
self.prompt = prompt
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .fullScreen
modalTransitionStyle = .coverVertical
restorationIdentifier = RestorationKey.viewController.rawValue
restorationClass = EditPostViewController.self
addChild(postPost)
view.addSubview(postPost.view)
postPost.didMove(toParent: self)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// show postpost, which will be transparent
view.isOpaque = false
view.backgroundColor = .clear
if openWithPostPost {
showPostPost()
}
}
override func viewDidAppear(_ animated: Bool) {
if !openWithPostPost && !hasShownEditor {
showEditor()
hasShownEditor = true
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if openWithPostPost {
return .darkContent
} else {
return WPStyleGuide.preferredStatusBarStyle
}
}
fileprivate func postToEdit() -> Post {
if let post = post {
return post
} else {
let newPost = blog.createDraftPost()
newPost.prepareForPrompt(prompt)
post = newPost
return newPost
}
}
// MARK: - Show editor by settings and post
fileprivate func showEditor() {
let editor = editorFactory.instantiateEditor(
for: postToEdit(),
loadAutosaveRevision: loadAutosaveRevision,
replaceEditor: { [weak self] (editor, replacement) in
self?.replaceEditor(editor: editor, replacement: replacement)
})
editor.postIsReblogged = postIsReblogged
editor.entryPoint = entryPoint
showEditor(editor)
}
private func showEditor(_ editor: EditorViewController) {
editor.isOpenedDirectlyForPhotoPost = openWithMediaPicker
// only open the media picker once.
openWithMediaPicker = false
editor.onClose = { [weak self, weak editor] changesSaved, showPostEpilogue in
guard let strongSelf = self else {
editor?.dismiss(animated: true) {}
return
}
// NOTE:
// We need to grab the latest Post Reference, since it may have changed (ie. revision / user picked a
// new blog).
if changesSaved {
strongSelf.post = editor?.post as? Post
}
strongSelf.closeEditor(changesSaved, showPostEpilogue: showPostEpilogue)
}
let navController = AztecNavigationController(rootViewController: editor)
navController.modalPresentationStyle = .fullScreen
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.prepare()
postPost.present(navController, animated: !showImmediately) {
generator.impactOccurred()
if let insertedMedia = self.insertedMedia {
editor.prepopulateMediaItems(insertedMedia)
}
}
}
func replaceEditor(editor: EditorViewController, replacement: EditorViewController) {
replacement.postIsReblogged = postIsReblogged
editor.dismiss(animated: true) { [weak self] in
self?.showEditor(replacement)
}
}
@objc func closeEditor(_ changesSaved: Bool = true, showPostEpilogue: Bool, from presentingViewController: UIViewController? = nil) {
onClose?(changesSaved)
var dismissPostPostImmediately = true
if showPostEpilogue && shouldShowPostPost(hasChanges: changesSaved) {
showPostPost()
dismissPostPostImmediately = false
}
dismiss(animated: true) {
if dismissPostPostImmediately {
self.closePostPost(animated: false)
}
}
}
private func showPostPost() {
guard let post = post else {
return
}
postPost.setup(post: post)
postPost.hideEditButton = isPresentingOverEditor()
postPost.onClose = {
self.closePostPost(animated: true)
}
postPost.reshowEditor = {
self.showEditor()
}
postPost.preview = {
self.previewPost()
}
}
/// - Returns: `true` if `self` was presented over an existing `EditPostViewController`, otherwise `false`.
private func isPresentingOverEditor() -> Bool {
guard
let aztecNavigationController = presentingViewController as? AztecNavigationController,
aztecNavigationController.presentingViewController is EditPostViewController
else {
return false
}
return true
}
@objc func shouldShowPostPost(hasChanges: Bool) -> Bool {
guard let post = post else {
return false
}
if openWithPostPost {
return true
}
if editingExistingPost {
return false
}
if postPost.revealPost {
return true
}
if post.originalIsDraft() {
return false
}
return hasChanges
}
@objc func previewPost() {
guard let post = post else {
return
}
let controller = PreviewWebKitViewController(post: post, source: "edit_post_preview")
controller.trackOpenEvent()
let navWrapper = LightNavigationController(rootViewController: controller)
if postPost.traitCollection.userInterfaceIdiom == .pad {
navWrapper.modalPresentationStyle = .fullScreen
}
postPost.present(navWrapper, animated: true) {}
}
@objc func closePostPost(animated: Bool) {
// this reference is needed in the completion
let presentingController = self.presentingViewController
// will dismiss self
dismiss(animated: animated) { [weak self] in
guard let self = self else {
return
}
self.afterDismiss?()
guard let post = self.post,
post.isPublished(),
!self.editingExistingPost,
let controller = presentingController else {
return
}
BloggingRemindersFlow.present(from: controller,
for: self.blog,
source: .publishFlow,
alwaysShow: false)
}
}
}
// MARK: - State Restoration
//
extension EditPostViewController: UIViewControllerRestoration {
enum RestorationKey: String {
case viewController = "EditPostViewControllerRestorationID"
case post = "EditPostViewControllerPostRestorationID"
}
class func viewController(withRestorationIdentifierPath identifierComponents: [String],
coder: NSCoder) -> UIViewController? {
guard let identifier = identifierComponents.last, identifier == RestorationKey.viewController.rawValue else {
return nil
}
let context = ContextManager.sharedInstance().mainContext
guard let postURL = coder.decodeObject(forKey: RestorationKey.post.rawValue) as? URL,
let postID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: postURL),
let post = try? context.existingObject(with: postID),
let reloadedPost = post as? Post
else {
return nil
}
return EditPostViewController(post: reloadedPost)
}
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
if let post = post {
coder.encode(post.objectID.uriRepresentation(), forKey: RestorationKey.post.rawValue)
}
}
}
|
gpl-2.0
|
1f078ede41eb67355bc52e6a4c7f4931
| 32.936937 | 153 | 0.620034 | 5.200644 | false | false | false | false |
davidozhang/spycodes
|
Spycodes/Objects/PageViewFlowEntry.swift
|
1
|
1852
|
import UIKit
import SwiftGifOrigin
class SCPageViewFlowEntry {
fileprivate var displayImage: UIImage?
fileprivate var displayImageType: DisplayImageType?
fileprivate var displayText: String?
fileprivate var headerText: String?
fileprivate var showIphone = false
enum DisplayImageType: Int {
case GIF
case Image
}
init(_ mapping: [String: Any]) {
if let displayImageType = mapping[SCConstants.pageViewFlowEntryKey.displayImageType.rawValue] as? DisplayImageType {
self.displayImageType = displayImageType
}
if let displayImageName = mapping[SCConstants.pageViewFlowEntryKey.displayImageName.rawValue] as? String {
if let displayImageType = self.displayImageType {
switch displayImageType {
case .GIF:
self.displayImage = UIImage.gif(name: displayImageName)
case .Image:
self.displayImage = UIImage(named: displayImageName)
}
}
}
if let displayText = mapping[SCConstants.pageViewFlowEntryKey.displayText.rawValue] as? String? {
self.displayText = displayText
}
if let headerText = mapping[SCConstants.pageViewFlowEntryKey.headerText.rawValue] as? String? {
self.headerText = headerText
}
if let showIphone = mapping[SCConstants.pageViewFlowEntryKey.showIphone.rawValue] as? Bool {
self.showIphone = showIphone
}
}
func getDisplayImage() -> UIImage? {
return self.displayImage
}
func getDisplayText() -> String? {
return self.displayText
}
func getHeaderText() -> String? {
return self.headerText
}
func shouldShowIphone() -> Bool {
return self.showIphone
}
}
|
mit
|
47a80bc747270416ccddd1ba33e3a2b5
| 29.866667 | 124 | 0.632289 | 5.130194 | false | false | false | false |
ehtd/HackerNews
|
Hackyto/Hackyto/AppDelegate.swift
|
1
|
2759
|
//
// AppDelegate.swift
// Hackyto
//
// Created by Ernesto Torres on 10/22/14.
// Copyright (c) 2014 ehtd. All rights reserved.
//
import UIKit
import MessageUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let tabbarControllerDelegate = TabbarControllerDelegate()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = ColorFactory.darkGrayColor()
let tabBarController: UITabBarController = UITabBarController()
tabBarController.delegate = tabbarControllerDelegate
var viewControllers: [UIViewController] = []
for i in 0..<ContentType.count {
let type: ContentType = ContentType(rawValue: i)!
let navigationController = UINavigationController(rootViewController: TableController(type: type))
let textAttributes = [NSForegroundColorAttributeName: ColorFactory.lightColor()]
navigationController.navigationBar.titleTextAttributes = textAttributes
viewControllers.append(navigationController)
}
tabBarController.viewControllers = viewControllers
if let startingController = viewControllers[0] as? UINavigationController {
tabbarControllerDelegate.setStartingController(startingController)
}
let tabBarImageNames = ["top", "new", "ask", "show", "jobs"]
let tabBarTitles = tabBarImageNames.map { $0.capitalized }
for i in 0..<viewControllers.count {
if let tab = tabBarController.tabBar.items?[i] {
tab.image = UIImage(named: tabBarImageNames[i])
tab.title = tabBarTitles[i]
}
}
configureAppearance()
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
// MARK: Apperance configuration
func configureAppearance() {
UINavigationBar.appearance().barTintColor = ColorFactory.lightColor()
UINavigationBar.appearance().tintColor = ColorFactory.darkGrayColor()
UINavigationBar.appearance().isTranslucent = false
UITabBar.appearance().tintColor = ColorFactory.darkGrayColor()
UITabBar.appearance().barTintColor = ColorFactory.lightColor()
UITabBar.appearance().isTranslucent = false
UIToolbar.appearance().barTintColor = ColorFactory.lightColor()
UIToolbar.appearance().tintColor = ColorFactory.darkGrayColor()
}
}
|
gpl-3.0
|
4a199904dd404fc0a8d1162848a758c0
| 35.302632 | 144 | 0.685393 | 5.870213 | false | false | false | false |
shu223/Pulsator
|
Pulsator/Pulsator.swift
|
1
|
8667
|
//
// Pulsator.swift
// Pulsator
//
// Created by Shuichi Tsutsumi on 4/9/16.
// Copyright © 2016 Shuichi Tsutsumi. All rights reserved.
//
// Objective-C version: https://github.com/shu223/PulsingHalo
#if os(iOS)
import UIKit
public typealias Color = UIColor
internal let screenScale = UIScreen.main.scale
internal let applicationWillBecomeActiveNotfication = UIApplication.willEnterForegroundNotification
internal let applicationDidResignActiveNotification = UIApplication.didEnterBackgroundNotification
#elseif os(macOS)
import Cocoa
public typealias Color = NSColor
internal let screenScale = NSScreen.main?.backingScaleFactor ?? 0.0
internal let applicationWillBecomeActiveNotfication = NSApplication.willBecomeActiveNotification
internal let applicationDidResignActiveNotification = NSApplication.didResignActiveNotification
#endif
import QuartzCore
internal let kPulsatorAnimationKey = "pulsator"
open class Pulsator: CAReplicatorLayer, CAAnimationDelegate {
fileprivate let pulse = CALayer()
fileprivate var animationGroup: CAAnimationGroup!
fileprivate var alpha: CGFloat = 0.45
override open var backgroundColor: CGColor? {
didSet {
pulse.backgroundColor = backgroundColor
guard let backgroundColor = backgroundColor else {return}
let oldAlpha = alpha
alpha = backgroundColor.alpha
if alpha != oldAlpha {
recreate()
}
}
}
override open var repeatCount: Float {
didSet {
if let animationGroup = animationGroup {
animationGroup.repeatCount = repeatCount
}
}
}
// MARK: - Public Properties
@objc open var animationCompletionBlock:(()->Void)?
/// The number of pulse.
@objc open var numPulse: Int = 1 {
didSet {
if numPulse < 1 {
numPulse = 1
}
instanceCount = numPulse
updateInstanceDelay()
}
}
/// The radius of pulse.
@objc open var radius: CGFloat = 60 {
didSet {
updatePulse()
}
}
/// The animation duration in seconds.
@objc open var animationDuration: TimeInterval = 3 {
didSet {
updateInstanceDelay()
}
}
/// If this property is `true`, the instanse will be automatically removed
/// from the superview, when it finishes the animation.
@objc open var autoRemove = false
/// fromValue for radius
/// It must be smaller than 1.0
@objc open var fromValueForRadius: Float = 0.0 {
didSet {
if fromValueForRadius >= 1.0 {
fromValueForRadius = 0.0
}
recreate()
}
}
/// The value of this property should be ranging from @c 0 to @c 1 (exclusive).
@objc open var keyTimeForHalfOpacity: Float = 0.2 {
didSet {
recreate()
}
}
/// The animation interval in seconds.
@objc open var pulseInterval: TimeInterval = 0
/// A function describing a timing curve of the animation.
@objc open var timingFunction: CAMediaTimingFunction? = CAMediaTimingFunction(name: .default) {
didSet {
if let animationGroup = animationGroup {
animationGroup.timingFunction = timingFunction
}
}
}
/// The value of this property showed a pulse is started
@objc open var isPulsating: Bool {
guard let keys = pulse.animationKeys() else {return false}
return keys.count > 0
}
/// private properties for resuming
fileprivate weak var prevSuperlayer: CALayer?
fileprivate var prevLayerIndex: Int?
// MARK: - Initializer
override public init() {
super.init()
setupPulse()
instanceDelay = 1
repeatCount = MAXFLOAT
backgroundColor = Color(red: 0, green: 0.455, blue: 0.756, alpha: 0.45).cgColor
NotificationCenter.default.addObserver(self,
selector: #selector(save),
name: applicationDidResignActiveNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(resume),
name: applicationWillBecomeActiveNotfication,
object: nil)
}
override public init(layer: Any) {
super.init(layer: layer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func removeFromSuperlayer() {
super.removeFromSuperlayer()
stop()
NotificationCenter.default.removeObserver(self)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Private Methods
fileprivate func setupPulse() {
pulse.contentsScale = screenScale
pulse.opacity = 0
addSublayer(pulse)
updatePulse()
}
fileprivate func setupAnimationGroup() {
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
scaleAnimation.fromValue = fromValueForRadius
scaleAnimation.toValue = 1.0
scaleAnimation.duration = animationDuration
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.duration = animationDuration
opacityAnimation.values = [alpha, alpha * 0.5, 0.0]
opacityAnimation.keyTimes = [0.0, NSNumber(value: keyTimeForHalfOpacity), 1.0]
animationGroup = CAAnimationGroup()
animationGroup.animations = [scaleAnimation, opacityAnimation]
animationGroup.duration = animationDuration + pulseInterval
animationGroup.repeatCount = repeatCount
if let timingFunction = timingFunction {
animationGroup.timingFunction = timingFunction
}
animationGroup.delegate = self
}
fileprivate func updatePulse() {
let diameter: CGFloat = radius * 2
pulse.bounds = CGRect(
origin: CGPoint.zero,
size: CGSize(width: diameter, height: diameter))
pulse.cornerRadius = radius
pulse.backgroundColor = backgroundColor
}
fileprivate func updateInstanceDelay() {
guard numPulse >= 1 else { fatalError() }
instanceDelay = (animationDuration + pulseInterval) / Double(numPulse)
}
fileprivate func recreate() {
guard animationGroup != nil else { return } // Not need to be recreated.
stop()
let when = DispatchTime.now() + Double(Int64(0.2 * double_t(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: when) { () -> Void in
self.start()
}
}
// MARK: - Internal Methods
@objc internal func save() {
prevSuperlayer = superlayer
prevLayerIndex = prevSuperlayer?.sublayers?.firstIndex(where: {$0 === self})
}
@objc internal func resume() {
if let prevSuperlayer = prevSuperlayer, let prevLayerIndex = prevLayerIndex {
prevSuperlayer.insertSublayer(self, at: UInt32(prevLayerIndex))
}
if pulse.superlayer == nil {
addSublayer(pulse)
}
let isAnimating = pulse.animation(forKey: kPulsatorAnimationKey) != nil
// if the animationGroup is not nil, it means the animation was not stopped
if let animationGroup = animationGroup, !isAnimating {
pulse.add(animationGroup, forKey: kPulsatorAnimationKey)
}
}
// MARK: - Public Methods
/// Start the animation.
@objc open func start() {
setupPulse()
setupAnimationGroup()
pulse.add(animationGroup, forKey: kPulsatorAnimationKey)
}
/// Stop the animation.
@objc open func stop() {
pulse.removeAllAnimations()
animationGroup = nil
}
// MARK: - Delegate methods for CAAnimation
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if let keys = pulse.animationKeys(), keys.count > 0 {
pulse.removeAllAnimations()
}
pulse.removeFromSuperlayer()
if autoRemove {
removeFromSuperlayer()
}
animationCompletionBlock?()
}
}
|
mit
|
aa5d079a4c5997a9f97a076c3d382f0f
| 30.74359 | 106 | 0.604777 | 5.355995 | false | false | false | false |
Samarkin/PixelEditor
|
PixelEditor/SolidColorView.swift
|
1
|
1508
|
import Cocoa
private let clearColorAlt1 = NSColor.grayColor()
private let clearColorAlt2 = NSColor.controlColor()
class SolidColorView: NSView {
var backgroundColor: NSColor = .clearColor() {
didSet {
self.needsDisplay = true
}
}
var click: (SolidColorView -> Void)?
var rightClick: (SolidColorView -> Void)?
var payload: Any?
override func drawRect(dirtyRect: NSRect) {
let quaterFrame = NSSize(width: frame.width/2, height: frame.height/2)
clearColorAlt1.set()
NSRectFill(NSRect(origin: NSZeroPoint, size: quaterFrame).intersect(dirtyRect))
NSRectFill(NSRect(origin: NSPoint(x: frame.width/2, y: frame.height/2), size: quaterFrame).intersect(dirtyRect))
clearColorAlt2.set()
NSRectFill(NSRect(origin: NSPoint(x: frame.width/2, y: 0), size: quaterFrame).intersect(dirtyRect))
NSRectFill(NSRect(origin: NSPoint(x: 0, y: frame.height/2), size: quaterFrame).intersect(dirtyRect))
backgroundColor.set()
NSRectFillUsingOperation(dirtyRect, NSCompositingOperation.CompositeSourceOver)
}
override func mouseDown(theEvent: NSEvent) {
guard let callback = click else {
super.mouseDown(theEvent)
return
}
callback(self)
}
override func rightMouseDown(theEvent: NSEvent) {
guard let callback = rightClick else {
super.rightMouseDown(theEvent)
return
}
callback(self)
}
}
|
mit
|
3eddef7e3051c8b94497ed0598659a11
| 31.804348 | 120 | 0.655172 | 4.396501 | false | false | false | false |
curiousurick/Rye
|
Login/AppDelegate.swift
|
1
|
3823
|
//
// AppDelegate.swift
// Login
//
// Created by Jason Kwok on 2/7/15.
// Copyright (c) 2015 Jason Kwok. All rights reserved.
//
import UIKit
import Parse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.enableLocalDatastore()
Parse.setApplicationId("zCY6tAOZOVCw8mI74mOpKinRsOnII7hkKcXPe5lg", clientKey: "ycyxfYQZAx5lGT6Dajj5FI6DmzJozDPuvqEgzNHc")
PFFacebookUtils.initializeFacebook()
// NSUserDefaults.standardUserDefaults()
var currentUser = PFUser.currentUser()
if currentUser != nil {
let storyboard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard
let main = storyboard.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController
self.window?.rootViewController = main
} else {
let storyboard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard
let land = storyboard.instantiateViewControllerWithIdentifier("Land") as UIViewController
self.window?.rootViewController = land
}
// if NSUserDefaults.standardUserDefaults().boolForKey("loggedIn") == true {
// let storyboard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard
// let main = storyboard.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController
// self.window?.rootViewController = main
// }
// Override point for customization after application launch.
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication,
withSession:PFFacebookUtils.session())
}
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) {
FBAppCall.handleDidBecomeActiveWithSession(PFFacebookUtils.session())
// 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
|
b1fe4715e65553f18ab60cf9037dc060
| 42.942529 | 285 | 0.705728 | 5.422695 | false | false | false | false |
codeOfRobin/Components-Personal
|
Sources/TagResultNode.swift
|
1
|
1249
|
//
// TagResultNode.swift
// BuildingBlocks-iOS
//
// Created by Robin Malhotra on 12/10/17.
// Copyright © 2017 BuildingBlocks. All rights reserved.
//
import AsyncDisplayKit
class TagResultNode: ASCellNode {
let tagInsertResult: TagInsertResult
let addTagImage = ASImageNode()
let textNode: DefaultTextNode
init(_ tagResult: TagInsertResult) {
self.tagInsertResult = tagResult
switch tagResult {
case .searchResult(let str):
self.textNode = DefaultTextNode.init(text: str)
case .textResult(let str):
self.textNode = DefaultTextNode.init(text: "Add " + str)
}
super.init()
addTagImage.image = FrameworkImage.add
addTagImage.style.width = ASDimensionMake(11)
addTagImage.style.height = ASDimensionMake(11)
self.automaticallyManagesSubnodes = true
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
switch tagInsertResult {
case .searchResult:
return ASStackLayoutSpec.init(direction: .horizontal, spacing: 9.0, justifyContent: .start, alignItems: .center, children: [textNode])
case .textResult:
return ASStackLayoutSpec.init(direction: .horizontal, spacing: 9.0, justifyContent: .start, alignItems: .center, children: [addTagImage, textNode])
}
}
}
|
mit
|
a018d4e851c3bb9ad4c5630a1e6ac2ca
| 28.714286 | 150 | 0.745994 | 3.535411 | false | false | false | false |
jvivas/OraChallenge
|
OraChallenge/OraChallenge/API/APIManager.swift
|
1
|
2386
|
//
// APIManager.swift
// OraChallenge
//
// Created by Jorge Vivas on 3/5/17.
// Copyright © 2017 JorgeVivas. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class APIManager: NSObject {
let baseUrl = "https://private-93240c-oracodechallenge.apiary-mock.com/"
func request(path:String, method: HTTPMethod, parameters: Parameters?, onSuccess:@escaping ((SwiftyJSON.JSON) -> Void), onFailed:@escaping ((String, Int) -> Void)) {
var headers: [String:String] = [
"Content-Type": "application/json; charset=UTF-8"
]
if let authToken = DefaultsManager.getAuthToken() {
headers["Authorization"] = authToken
}
Alamofire.request(baseUrl+path, method: method, parameters:parameters, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { response in
switch response.result {
case .success:
if let authToken = response.response?.allHeaderFields["Authorization"] as? String {
DefaultsManager.saveAuthToken(token: authToken)
}
if let value = response.result.value {
let json = SwiftyJSON.JSON(value)
onSuccess(json)
}
case .failure (let error):
// Handle status codes
if let statusCode = response.response?.statusCode {
self.handleStatusCode(statusCode: statusCode)
}
var errorMessage = error.localizedDescription
if let data = response.data {
let responseJSON = JSON(data: data)
if let message: String = responseJSON["message"].string {
if !message.isEmpty {
errorMessage = message
}
}
}
onFailed(errorMessage, (response.response?.statusCode)!)
}
}
}
func handleStatusCode(statusCode:Int) {
if statusCode == 401 { // TODO Unauthorized
}
}
}
|
apache-2.0
|
baa5105c7e57ab3196190afb626d252c
| 35.136364 | 169 | 0.500629 | 5.665083 | false | false | false | false |
rajeejones/SavingPennies
|
Saving Pennies/CharacterSelectionViewController.swift
|
1
|
1789
|
//
// CharacterSelectionViewController.swift
// Saving Pennies
//
// Created by Rajeé Jones on 11/20/16.
// Copyright © 2016 Rajee Jones. All rights reserved.
//
import UIKit
import AVFoundation
var backgroundMusicPlayer = AVAudioPlayer()
func playBackgroundMusic(filename: String) {
let url = Bundle.main.url(forResource: filename, withExtension: nil)
guard let newURL = url else {
print("Could not find file: \(filename)")
return
}
do {
backgroundMusicPlayer = try AVAudioPlayer(contentsOf: newURL)
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
backgroundMusicPlayer.volume = 0.7
} catch let error as NSError {
print(error.description)
}
}
class CharacterSelectionViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var playButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
playBackgroundMusic(filename: "Mining by Moonlight.mp3")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction public func unwindToCharacterSelectViewController(_ sender: UIStoryboardSegue) {
}
}
|
gpl-3.0
|
562c44cabf3aefe651f29876a412c421
| 27.822581 | 106 | 0.688304 | 5.048023 | false | false | false | false |
superk589/CGSSGuide
|
DereGuide/Model/ApiInfo.swift
|
2
|
627
|
//
// ApiInfo.swift
// DereGuide
//
// Created by zzk on 2016/9/13.
// Copyright © 2016 zzk. All rights reserved.
//
import Foundation
import SwiftyJSON
extension ApiInfo {
var apiVersion: (Int, Int) {
return (apiMajor, apiRevision)
}
}
class ApiInfo {
var apiMajor: Int!
var apiRevision: Int!
var truthVersion: String!
init(fromJson json: JSON!) {
if json == JSON.null {
return
}
apiMajor = json["api_major"].intValue
apiRevision = json["api_revision"].intValue
truthVersion = json["truth_version"].stringValue
}
}
|
mit
|
6955eefb096b4cb08831b2a84a94333a
| 17.969697 | 56 | 0.594249 | 3.817073 | false | false | false | false |
apple/swift-async-algorithms
|
Sources/AsyncAlgorithms/RangeReplaceableCollection.swift
|
1
|
876
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension RangeReplaceableCollection {
/// Creates a new instance of a collection containing the elements of an asynchronous sequence.
///
/// - Parameter source: The asynchronous sequence of elements for the new collection.
@inlinable
public init<Source: AsyncSequence>(_ source: Source) async rethrows where Source.Element == Element {
self.init()
for try await item in source {
append(item)
}
}
}
|
apache-2.0
|
c121e620a8ce8111f8f180e4262e89b4
| 37.086957 | 103 | 0.593607 | 5.509434 | false | false | false | false |
ZuoCaiSong/DouYuZB
|
DYZB/DYZB/Classes/Home/view/PageContentView.swift
|
1
|
3233
|
//
// PageContentView.swift
// DYZB
//
// Created by supin-tech on 2017/5/26.
// Copyright © 2017年 supin. All rights reserved.
//
import UIKit
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
// MARK: - 定义属性
fileprivate var childVcs: [UIViewController]
fileprivate weak var parentViewController : UIViewController?
// MARK:- 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
//1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//2.创建UIcollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
//MARK: - 自定义构造函数
init(frame: CGRect, childVcs : [UIViewController], parentViewController : UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
//添加UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension PageContentView{
fileprivate func setupUI(){
//1. 将所有的控制器加入到父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
// 2.添加UICollectionView,用于在Cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.创建Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
// 2.给Cell设置内容
for view in cell.contentView.subviews{
view.removeFromSuperview()
}
let childVc = childVcs[(indexPath as NSIndexPath).item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
// MARK:- 遵守UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate {
}
|
mit
|
cd5e12c0c39394990924516232c532a5
| 28.245283 | 121 | 0.644839 | 5.927342 | false | false | false | false |
psobot/hangover
|
Hangover/ConversationListItemView.swift
|
1
|
1599
|
//
// ConversationListItemView.swift
// Hangover
//
// Created by Peter Sobot on 6/11/15.
// Copyright © 2015 Peter Sobot. All rights reserved.
//
import Cocoa
class ConversationListItemView : NSTableCellView {
@IBOutlet weak var avatarView: NSImageView!
@IBOutlet weak var nameView: NSTextField!
@IBOutlet weak var lastMessageView: NSTextField!
@IBOutlet weak var timeView: NSTextField!
func configureWithConversation(conversation: Conversation) {
avatarView.wantsLayer = true
avatarView.layer?.borderWidth = 0.0
avatarView.layer?.cornerRadius = avatarView.frame.width / 2.0
avatarView.layer?.masksToBounds = true
let usersButNotMe = conversation.users.filter { !$0.isSelf }
if let user = usersButNotMe.first {
// TODO: This is racey, fast scrolling can result in misplaced images
ImageCache.sharedInstance.fetchImage(forUser: user) {
self.avatarView.image = $0 ?? NSImage(named: "NSUserGuest")
}
} else {
avatarView.image = NSImage(named: "NSUserGuest")
}
nameView.stringValue = conversation.name
lastMessageView.stringValue = conversation.messages.last?.text ?? ""
if conversation.hasUnreadEvents {
lastMessageView.font = NSFont.boldSystemFontOfSize(lastMessageView.font!.pointSize)
} else {
lastMessageView.font = NSFont.systemFontOfSize(lastMessageView.font!.pointSize)
}
timeView.stringValue = conversation.messages.last?.timestamp.shortFormat() ?? ""
}
}
|
mit
|
419f8be0b893aff7a275ee1dd65cc6ed
| 34.533333 | 95 | 0.671464 | 4.727811 | false | false | false | false |
Ryukie/Ryubo
|
Ryubo/Ryubo/Classes/Tools/RYGlobal.swift
|
1
|
1259
|
//
// RYGlobal.swift
// Ryubo
//
// Created by 王荣庆 on 16/2/5.
// Copyright © 2016年 Ryukie. All rights reserved.
//
import UIKit
let app_key = "4034367702"
let app_scret = "dc124878d20ce54c9b962ca22b3154cd"
let redirect_URL = "http://www.baidu.com"
let codeInURL = "17f81165d8b74790ff1e2d6c58a35975"
// 2.00bOzbGCo1nB6Ebfb2b2efa91nmLaD token
// https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00bOzbGCo1nB6Ebfb2b2efa91nmLaD
// MARK: - 各种通知
//切换到登陆后微博视图的通知
let didLoginChangeToWeiboView = "FireInTheHole"
//定义全局通用的错误提示
let netErrorText = "网络君正在睡觉中,请稍后再试..."
///自动布局margin
let margin : CGFloat = 10.0
///颜色
let col_darkGray = UIColor.darkGrayColor()
let col_lightGray = UIColor.lightGrayColor()
let col_white = UIColor.whiteColor()
let col_orange = UIColor.orangeColor()
let col_white95Gray = UIColor(white: 0.95, alpha: 1)
let col_retweetCol = UIColor(white: 0.9, alpha: 1)
/**
* 屏幕尺寸
*/
let scrWidth = UIScreen.mainScreen().bounds.size.width
let scrHeight = UIScreen.mainScreen().bounds.size.height
/**
* 图片配图间距
*/
let picCellMargin : CGFloat = 5
//emotionCellID
let emotionCellReuseID = "emotionCell"
|
mit
|
c39a5895920c20bab52ee50ddb462120
| 22.666667 | 100 | 0.740317 | 2.64186 | false | false | false | false |
jjatie/Charts
|
Source/Charts/Data/ChartDataSet/BarChartDataSet.swift
|
1
|
3619
|
//
// BarChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
open class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, BarChartDataSetProtocol {
private func initialize() {
highlightColor = NSUIColor.black
calcStackSize(entries: entries as! [BarChartDataEntry])
calcEntryCountIncludingStacks(entries: entries as! [BarChartDataEntry])
}
public required init() {
super.init()
initialize()
}
override public init(entries: [ChartDataEntry], label: String = "DataSet") {
super.init(entries: entries, label: label)
initialize()
}
// MARK: - Data functions and accessors
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
public private(set) var stackSize = 1
/// the overall entry count, including counting each stack-value individually
public private(set) var entryCountStacks = 0
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(entries: [BarChartDataEntry]) {
entryCountStacks = entries.lazy
.map(\.stackSize)
.reduce(into: 0, +=)
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(entries: [BarChartDataEntry]) {
stackSize = entries.lazy
.map(\.stackSize)
.max() ?? 1
}
override open func calcMinMax(entry e: ChartDataEntry) {
guard let e = e as? BarChartDataEntry,
!e.y.isNaN
else { return }
if e.yValues == nil {
yRange = merge(yRange, e.y)
} else {
yRange = merge(yRange, (-e.negativeSum, e.positiveSum))
}
calcMinMaxX(entry: e)
}
/// `true` if this DataSet is stacked (stacksize > 1) or not.
public var isStacked: Bool {
stackSize > 1
}
/// array of labels used to describe the different values of the stacked bars
open var stackLabels: [String] = []
// MARK: - Styling functions and accessors
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
open var barShadowColor = NSUIColor(red: 215.0 / 255.0, green: 215.0 / 255.0, blue: 215.0 / 255.0, alpha: 1.0)
/// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn.
open var barBorderWidth: CGFloat = 0.0
/// the color drawing borders around the bars.
open var barBorderColor = NSUIColor.black
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
open var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
override open func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone) as! BarChartDataSet
copy.stackSize = stackSize
copy.entryCountStacks = entryCountStacks
copy.stackLabels = stackLabels
copy.barShadowColor = barShadowColor
copy.barBorderWidth = barBorderWidth
copy.barBorderColor = barBorderColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
|
apache-2.0
|
0270f7844d5d3e743f8a678c6aa12e2d
| 32.82243 | 148 | 0.662338 | 4.768116 | false | false | false | false |
adamkornafeld/CocoaSkeleton
|
CocoaTouchSkeleton/MasterViewController.swift
|
1
|
3603
|
//
// MasterViewController.swift
// CocoaTouchSkeleton
//
// Created by Adam Kornafeld on 6/13/16.
// Copyright © 2016 Adam Kornafeld. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
|
mit
|
29c21f5cd4fb3fcf8c22ed86615de28c
| 37.731183 | 157 | 0.693226 | 5.72655 | false | false | false | false |
JohnnyHao/ForeignChat
|
ForeignChat/TabVCs/Friends/PrivateViewController.swift
|
1
|
9753
|
//
// PrivateViewController.swift
// ForeignChat
//
// Created by Tonny Hao on 2/20/15.
// Copyright (c) 2015 Tonny Hao. All rights reserved.
//
import UIKit
import AddressBook
import MessageUI
class PrivateViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {
var users1 = [APContact]()
var users2 = [PFUser]()
var indexSelected: NSIndexPath!
let addressBook = APAddressBook()
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanup", name: NOTIFICATION_USER_LOGGED_OUT, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
if PFUser.currentUser() != nil {
// Load address book
self.addressBook.fieldsMask = APContactField.Default | APContactField.Emails
self.addressBook.sortDescriptors = [NSSortDescriptor(key: "firstName", ascending: true), NSSortDescriptor(key: "lastName", ascending: true)]
self.addressBook.loadContacts({ (contacts: [AnyObject]!, error: NSError!) -> Void in
self.users1.removeAll(keepCapacity: false)
if contacts != nil {
for contact in contacts as [APContact]! {
self.users1.append(contact)
}
self.loadUsers()
} else if error != nil {
ProgressHUD.showError("Error loading contacts")
println(error)
}
})
}
else {
Utilities.loginUser(self)
}
}
// MARK: - User actions
func cleanup() {
users1.removeAll(keepCapacity: false)
users2.removeAll(keepCapacity: false)
self.tableView.reloadData()
}
func loadUsers() {
var emails = [String]()
for user in users1 {
if let userEmails = user.emails {
emails += userEmails as [String]
}
}
var user = PFUser.currentUser()
var query = PFQuery(className: PF_USER_CLASS_NAME)
query.whereKey(PF_USER_OBJECTID, notEqualTo: user.objectId)
query.whereKey(PF_USER_EMAILCOPY, containedIn: emails)
query.orderByAscending(PF_USER_FULLNAME)
query.limit = 1000
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
self.users2.removeAll(keepCapacity: false)
for user in objects as [PFUser]! {
self.users2.append(user)
self.removeUser(user[PF_USER_EMAILCOPY] as String)
}
self.tableView.reloadData()
} else {
ProgressHUD.showError("Network error")
}
}
}
func removeUser(removeEmail: String) {
var removeUsers = [APContact]()
for user in users1 {
if let userEmails = user.emails {
for email in userEmails as [String] {
if email == removeEmail {
removeUsers.append(user)
break
}
}
}
}
let filtered = self.users1.filter { !contains(removeUsers, $0) }
self.users1 = filtered
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return users2.count
}
if section == 1 {
return users1.count
}
return 0
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 && users2.count > 0 {
return "Registered users"
}
if section == 1 && users1.count > 0 {
return "Non-registered users"
}
return nil
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
if indexPath.section == 0 {
let user = users2[indexPath.row]
cell.textLabel?.text = user[PF_USER_FULLNAME] as? String
cell.detailTextLabel?.text = user[PF_USER_EMAILCOPY] as? String
}
else if indexPath.section == 1 {
let user = users1[indexPath.row]
let email = user.emails.first as? String
let phone = user.phones.first as? String
cell.textLabel?.text = "\(user.firstName) \(user.lastName)"
cell.detailTextLabel?.text = (email != nil) ? email : phone
}
cell.detailTextLabel?.textColor = UIColor.lightGrayColor()
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 0 {
let user1 = PFUser.currentUser()
let user2 = users2[indexPath.row]
let groupId = Messages.startPrivateChat(user1, user2: user2)
self.performSegueWithIdentifier("privateChatSegue", sender: groupId)
}
else if indexPath.section == 1 {
self.indexSelected = indexPath
self.inviteUser(self.users1[indexPath.row])
}
}
// MARK: - Prepare for segue to private chatVC
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "privateChatSegue" {
let chatVC = segue.destinationViewController as ChatViewController
chatVC.hidesBottomBarWhenPushed = true
let groupId = sender as String
chatVC.groupId = groupId
}
}
// MARK: - Invite helper method
func inviteUser(user: APContact) {
let emailsCount = countElements(user.emails)
let phonesCount = countElements(user.phones)
if emailsCount > 0 && phonesCount > 0 {
let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Email invitation", "SMS invitation")
actionSheet.showFromTabBar(self.tabBarController?.tabBar)
} else if emailsCount > 0 && phonesCount == 0 {
self.sendMail(user)
} else if emailsCount == 0 && phonesCount > 0 {
self.sendSMS(user)
} else {
ProgressHUD.showError("Contact has no email or phone number")
}
}
// MARK: - UIActionSheetDelegate
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex != actionSheet.cancelButtonIndex {
let user = users1[indexSelected.row]
if buttonIndex == 1 {
self.sendMail(user)
} else if buttonIndex == 2 {
self.sendSMS(user)
}
}
}
// MARK: - Mail sending method
func sendMail(user: APContact) {
if MFMailComposeViewController.canSendMail() {
var mailCompose = MFMailComposeViewController()
// TODO: Use one email rather than all emails
mailCompose.setToRecipients(user.emails as [String]!)
mailCompose.setSubject("")
mailCompose.setMessageBody(MESSAGE_INVITE, isHTML: true)
mailCompose.mailComposeDelegate = self
self.presentViewController(mailCompose, animated: true, completion: nil)
} else {
ProgressHUD.showError("Email not configured")
}
}
// MARK: - MailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
if result.value == MFMailComposeResultSent.value {
ProgressHUD.showSuccess("Invitation email sent successfully")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - SMS sending method
func sendSMS(user: APContact) {
if MFMessageComposeViewController.canSendText() {
var messageCompose = MFMessageComposeViewController()
// TODO: Use primary phone rather than all numbers
messageCompose.recipients = user.phones as [String]!
messageCompose.body = MESSAGE_INVITE
messageCompose.messageComposeDelegate = self
self.presentViewController(messageCompose, animated: true, completion: nil)
} else {
ProgressHUD.showError("SMS cannot be sent")
}
}
// MARK: - MessageComposeViewControllerDelegate
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
if result.value == MessageComposeResultSent.value {
ProgressHUD.showSuccess("Invitation SMS sent successfully")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
apache-2.0
|
6d0610bf37c6a97db92b0ee989b28f63
| 35.52809 | 196 | 0.599405 | 5.314986 | false | false | false | false |
barrymcandrews/aurora-ios
|
Aurora/RequestContainer.swift
|
1
|
8489
|
//
// RequestArray.swift
// Aurora
//
// Created by Barry McAndrews on 4/7/17.
// Copyright © 2017 Barry McAndrews. All rights reserved.
//
import UIKit
import WatchConnectivity
public protocol RequestContainerDelegate {
func requestsChanged()
}
public class RequestContainer: NSObject {
public static let shared = RequestContainer()
static let ApplicationSupportDirectory = FileManager().urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
static let ArchiveURL = ApplicationSupportDirectory.appendingPathComponent("requests.dat")
public var delegate: RequestContainerDelegate?
public var requests: [Request] = [
ColorRequest(name:"Off", color: UIColor.black),
ServiceRequest(name: "Spotify", service: ServiceType.LightShowService),
ColorRequest(name: "Blue", color: UIColor.blue),
ColorRequest(name: "Red", color: UIColor.red),
ColorRequest(name: "Orange", color: UIColor.orange),
ColorRequest(name: "Yellow", color: UIColor.yellow),
ColorRequest(name: "Green", color: UIColor.green),
ColorRequest(name: "White", color: UIColor.white),
ColorRequest(name: "Purple", color: UIColor.purple),
ColorRequest(name: "Pink", color: UIColor.magenta),
SequenceRequest(name: "Police", dict: [
"type":"sequence",
"delay":0.25,
"sequence":[
[
"type":"sequence",
"repeat":4,
"delay":0.0625,
"sequence":[
[
"type":"color",
"red":100,
"green":0,
"blue":0
],
[
"type":"color",
"red":0,
"green":0,
"blue":0
]
]
],
[
"type":"color",
"red":100,
"green":0,
"blue":0
],
[
"type":"sequence",
"repeat":4,
"delay":0.0625,
"sequence":[
[
"type":"color",
"red":0,
"green":0,
"blue":0
],
[
"type":"color",
"red":0,
"green":0,
"blue":100
]
]
],
[
"type":"color",
"red":0,
"green":0,
"blue":100
]
]
]),
SequenceRequest(name: "Rainbow", dict: [
"type": "fade",
"delay": 2,
"colors": [
[
"red": 100,
"green": 0,
"blue": 0
],
[
"red": 100,
"green": 100,
"blue": 0
],
[
"red": 0,
"green": 100,
"blue": 0
],
[
"red": 0,
"green": 100,
"blue": 100
],
[
"red": 0,
"green": 0,
"blue": 100
],
[
"red": 100,
"green": 0,
"blue": 100
],
[
"red": 100,
"green": 0,
"blue": 0
]
]
]),
SequenceRequest(name: "Sunset", dict: [
"type": "fade",
"delay": 2,
"colors": [
[
"red": 100,
"green": 30,
"blue": 0
],
[
"red": 100,
"green": 0,
"blue": 0
],
[
"red": 0,
"green": 0,
"blue": 0
],
[
"red": 100,
"green": 0,
"blue": 0
],
[
"red": 100,
"green": 30,
"blue": 0
]
]
]),
SequenceRequest(name: "Pitt", dict: [
"type": "sequence",
"delay": 1,
"sequence": [
[
"type": "color",
"red": 0,
"green": 0,
"blue": 100
],
[
"type": "color",
"red": 100,
"green": 25,
"blue": 0
]
]
]),
SequenceRequest(name: "Strobe", dict: [
"type": "sequence",
"delay": 0.0625,
"sequence": [
[
"type": "color",
"red": 100,
"green": 100,
"blue": 100
],
[
"type": "color",
"red": 0,
"green": 0,
"blue": 0
]
]
]),
SequenceRequest(name: "Acid Trip", dict: [
"type": "sequence",
"delay": 0.1,
"sequence": [
[
"type": "color",
"red": 100,
"green": 0,
"blue": 0
],
[
"type": "color",
"red": 0,
"green": 100,
"blue": 0
],
[
"type": "color",
"red": 0,
"green": 0,
"blue": 100
]
]
]),
SequenceRequest(name: "Cyclone", dict: [
"type": "fade",
"delay": 0.25,
"colors": [
[
"red": 100,
"green": 0,
"blue": 0
],
[
"red": 0,
"green": 100,
"blue": 0
],
[
"red": 0,
"green": 0,
"blue": 100
],
[
"red": 100,
"green": 0,
"blue": 0
]
]
])
] {
didSet {
#if os(iOS)
WatchSessionManager.shared.updateApplicationContext()
#endif
delegate?.requestsChanged()
}
}
public static func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
public static func saveRequests() -> Bool {
do {
try FileManager.default.createDirectory(atPath: ApplicationSupportDirectory.path, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
return NSKeyedArchiver.archiveRootObject(shared.requests, toFile: ArchiveURL.path)
}
public static func loadRequests() -> Bool {
if let loaded = NSKeyedUnarchiver.unarchiveObject(withFile: ArchiveURL.path) as? [Request] {
shared.requests = loaded
return true
} else {
return false
}
}
}
|
bsd-2-clause
|
c0fd44e5e3175688ce7b2ccde5693afe
| 28.574913 | 146 | 0.315386 | 5.529642 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigo/Image/Parameters/Tags/TagsViewController+Add.swift
|
1
|
4500
|
//
// TagsViewController+Add.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 19/06/2022.
// Copyright © 2022 Piwigo.org. All rights reserved.
//
import Foundation
extension TagsViewController
{
// MARK: - Add tag (for admins only)
@objc func requestNewTagName() {
let alert = UIAlertController(title: NSLocalizedString("tagsAdd_title", comment: "Add Tag"), message: NSLocalizedString("tagsAdd_message", comment: "Enter a name for this new tag"), preferredStyle: .alert)
alert.addTextField(configurationHandler: { textField in
textField.placeholder = NSLocalizedString("tagsAdd_placeholder", comment: "New tag")
textField.clearButtonMode = .always
textField.keyboardType = .default
textField.keyboardAppearance = AppVars.shared.isDarkPaletteActive ? .dark : .default
textField.autocapitalizationType = .sentences
textField.autocorrectionType = .yes
textField.returnKeyType = .continue
textField.delegate = self
})
let cancelAction = UIAlertAction(title: NSLocalizedString("alertCancelButton", comment: "Cancel"), style: .cancel, handler: { action in
})
addAction = UIAlertAction(title: NSLocalizedString("alertAddButton", comment: "Add"), style: .default, handler: { action in
// Rename album if possible
if (alert.textFields?.first?.text?.count ?? 0) > 0 {
self.addTag(withName: alert.textFields?.first?.text)
}
})
alert.addAction(cancelAction)
if let addAction = addAction {
alert.addAction(addAction)
}
alert.view.tintColor = .piwigoColorOrange()
if #available(iOS 13.0, *) {
alert.overrideUserInterfaceStyle = AppVars.shared.isDarkPaletteActive ? .dark : .light
} else {
// Fallback on earlier versions
}
present(alert, animated: true) {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alert.view.tintColor = .piwigoColorOrange()
}
}
func addTag(withName tagName: String?) {
// Check tag name
guard let tagName = tagName, tagName.count != 0 else {
return
}
// Display HUD during the update
showPiwigoHUD(withTitle: NSLocalizedString("tagsAddHUD_label", comment: "Creating Tag…"))
// Add new tag
DispatchQueue.global(qos: .userInteractive).async {
self.tagsProvider.addTag(with: tagName, completionHandler: { error in
guard let error = error else {
self.updatePiwigoHUDwithSuccess {
self.hidePiwigoHUD(afterDelay: kDelayPiwigoHUD, completion: {})
}
return
}
self.hidePiwigoHUD {
self.dismissPiwigoError(
withTitle: NSLocalizedString("tagsAddError_title", comment: "Create Fail"),
message: NSLocalizedString("tagsAddError_message", comment: "Failed to…"),
errorMessage: error.localizedDescription, completion: { })
}
})
}
}
}
// MARK: - UITextFieldDelegate Methods
extension TagsViewController: UITextFieldDelegate
{
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
// Disable Add/Delete Category action
addAction?.isEnabled = false
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Enable Add/Delete Tag action if text field not empty
let finalString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
let allTags = tagsProvider.fetchedResultsController.fetchedObjects ?? []
let existTagWithName = (allTags.first(where: {$0.tagName == finalString}) != nil)
addAction?.isEnabled = (((finalString?.count ?? 0) >= 1) && !existTagWithName)
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
// Disable Add/Delete Category action
addAction?.isEnabled = false
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
}
|
mit
|
d51d4a8042b8e516a400d05c3989463a
| 38.078261 | 213 | 0.618825 | 5.213457 | false | false | false | false |
ambientlight/Perfect
|
Sources/PerfectLib/Utilities.swift
|
1
|
18996
|
//
// Utilities.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/17/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import Foundation
#if os(Linux)
import LinuxBridge
#else
import Darwin
#endif
/// This class permits an UnsafeMutablePointer to be used as a GeneratorType
public struct GenerateFromPointer<T> : IteratorProtocol {
public typealias Element = T
var count = 0
var pos = 0
var from: UnsafeMutablePointer<T>
/// Initialize given an UnsafeMutablePointer and the number of elements pointed to.
public init(from: UnsafeMutablePointer<T>, count: Int) {
self.from = from
self.count = count
}
/// Return the next element or nil if the sequence has been exhausted.
mutating public func next() -> Element? {
guard count > 0 else {
return nil
}
self.count -= 1
let result = self.from[self.pos]
self.pos += 1
return result
}
}
/// A generalized wrapper around the Unicode codec operations.
public struct Encoding {
/// Return a String given a character generator.
public static func encode<D : UnicodeCodec, G : IteratorProtocol>(codec inCodec: D, generator: G) -> String where G.Element == D.CodeUnit, G.Element == D.CodeUnit {
var encodedString = ""
var finished: Bool = false
var mutableDecoder = inCodec
var mutableGenerator = generator
repeat {
let decodingResult = mutableDecoder.decode(&mutableGenerator)
switch decodingResult {
case .scalarValue(let char):
encodedString.append(String(char))
case .emptyInput:
finished = true
/* ignore errors and unexpected values */
case .error:
finished = true
}
} while !finished
return encodedString
}
}
/// Utility wrapper permitting a UTF-8 character generator to encode a String. Also permits a String to be converted into a UTF-8 byte array.
public struct UTF8Encoding {
/// Use a character generator to create a String.
public static func encode<G : IteratorProtocol>(generator gen: G) -> String where G.Element == UTF8.CodeUnit {
return Encoding.encode(codec: UTF8(), generator: gen)
}
/// Use a character sequence to create a String.
public static func encode<S : Sequence>(bytes byts: S) -> String where S.Iterator.Element == UTF8.CodeUnit {
return encode(generator: byts.makeIterator())
}
/// Decode a String into an array of UInt8.
public static func decode(string str: String) -> Array<UInt8> {
return [UInt8](str.utf8)
}
}
extension UInt8 {
var shouldURLEncode: Bool {
let cc = self
return ( ( cc >= 128 )
|| ( cc < 33 )
|| ( cc >= 34 && cc < 38 )
|| ( ( cc > 59 && cc < 61) || cc == 62 || cc == 58)
|| ( ( cc >= 91 && cc < 95 ) || cc == 96 )
|| ( cc >= 123 && cc <= 126 )
|| self == 43 )
}
// same as String(self, radix: 16)
// but outputs two characters. i.e. 0 padded
var hexString: String {
var s = ""
let b = self >> 4
s.append(String(Character(UnicodeScalar(b > 9 ? b - 10 + 65 : b + 48))))
let b2 = self & 0x0F
s.append(String(Character(UnicodeScalar(b2 > 9 ? b2 - 10 + 65 : b2 + 48))))
return s
}
}
extension String {
/// Returns the String with all special HTML characters encoded.
public var stringByEncodingHTML: String {
var ret = ""
var g = self.unicodeScalars.makeIterator()
var lastWasCR = false
while let c = g.next() {
if c == UnicodeScalar(10) {
if lastWasCR {
lastWasCR = false
ret.append("\n")
} else {
ret.append("<br>\n")
}
continue
} else if c == UnicodeScalar(13) {
lastWasCR = true
ret.append("<br>\r")
continue
}
lastWasCR = false
if c < UnicodeScalar(0x0009) {
if let scale = UnicodeScalar(0x0030 + UInt32(c)) {
ret.append("&#x")
ret.append(String(Character(scale)))
ret.append(";")
}
} else if c == UnicodeScalar(0x0022) {
ret.append(""")
} else if c == UnicodeScalar(0x0026) {
ret.append("&")
} else if c == UnicodeScalar(0x0027) {
ret.append("'")
} else if c == UnicodeScalar(0x003C) {
ret.append("<")
} else if c == UnicodeScalar(0x003E) {
ret.append(">")
} else if c > UnicodeScalar(126) {
ret.append("&#\(UInt32(c));")
} else {
ret.append(String(Character(c)))
}
}
return ret
}
/// Returns the String with all special URL characters encoded.
public var stringByEncodingURL: String {
var ret = ""
var g = self.utf8.makeIterator()
while let c = g.next() {
if c.shouldURLEncode {
ret.append(String(Character(UnicodeScalar(37))))
ret.append(c.hexString)
} else {
ret.append(String(Character(UnicodeScalar(c))))
}
}
return ret
}
// Utility - not sure if it makes the most sense to have here or outside or elsewhere
static func byteFromHexDigits(one c1v: UInt8, two c2v: UInt8) -> UInt8? {
let capA: UInt8 = 65
let capF: UInt8 = 70
let lowA: UInt8 = 97
let lowF: UInt8 = 102
let zero: UInt8 = 48
let nine: UInt8 = 57
var newChar = UInt8(0)
if c1v >= capA && c1v <= capF {
newChar = c1v - capA + 10
} else if c1v >= lowA && c1v <= lowF {
newChar = c1v - lowA + 10
} else if c1v >= zero && c1v <= nine {
newChar = c1v - zero
} else {
return nil
}
newChar *= 16
if c2v >= capA && c2v <= capF {
newChar += c2v - capA + 10
} else if c2v >= lowA && c2v <= lowF {
newChar += c2v - lowA + 10
} else if c2v >= zero && c2v <= nine {
newChar += c2v - zero
} else {
return nil
}
return newChar
}
/// Decode the % encoded characters in a URL and return result
public var stringByDecodingURL: String? {
let percent: UInt8 = 37
let plus: UInt8 = 43
let space: UInt8 = 32
var bytesArray = [UInt8]()
var g = self.utf8.makeIterator()
while let c = g.next() {
if c == percent {
guard let c1v = g.next() else {
return nil
}
guard let c2v = g.next() else {
return nil
}
guard let newChar = String.byteFromHexDigits(one: c1v, two: c2v) else {
return nil
}
bytesArray.append(newChar)
} else if c == plus {
bytesArray.append(space)
} else {
bytesArray.append(c)
}
}
return UTF8Encoding.encode(bytes: bytesArray)
}
/// Decode a hex string into resulting byte array
public var decodeHex: [UInt8]? {
var bytesArray = [UInt8]()
var g = self.utf8.makeIterator()
while let c1v = g.next() {
guard let c2v = g.next() else {
return nil
}
guard let newChar = String.byteFromHexDigits(one: c1v, two: c2v) else {
return nil
}
bytesArray.append(newChar)
}
return bytesArray
}
}
public struct UUID {
let uuid: uuid_t
public init() {
let u = UnsafeMutablePointer<UInt8>.allocate(capacity: MemoryLayout<uuid_t>.size)
defer {
u.deallocate(capacity: MemoryLayout<uuid_t>.size)
}
uuid_generate_random(u)
self.uuid = UUID.uuidFromPointer(u)
}
public init(_ string: String) {
let u = UnsafeMutablePointer<UInt8>.allocate(capacity: MemoryLayout<uuid_t>.size)
defer {
u.deallocate(capacity: MemoryLayout<uuid_t>.size)
}
uuid_parse(string, u)
self.uuid = UUID.uuidFromPointer(u)
}
init(_ uuid: uuid_t) {
self.uuid = uuid
}
private static func uuidFromPointer(_ u: UnsafeMutablePointer<UInt8>) -> uuid_t {
// is there a better way?
return uuid_t(u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7], u[8], u[9], u[10], u[11], u[12], u[13], u[14], u[15])
}
public var string: String {
let u = UnsafeMutablePointer<UInt8>.allocate(capacity: MemoryLayout<uuid_t>.size)
let unu = UnsafeMutablePointer<Int8>.allocate(capacity: 37) // as per spec. 36 + null
defer {
u.deallocate(capacity: MemoryLayout<uuid_t>.size)
unu.deallocate(capacity: 37)
}
var uu = self.uuid
memcpy(u, &uu, MemoryLayout<uuid_t>.size)
uuid_unparse_lower(u, unu)
return String(validatingUTF8: unu)!
}
}
extension String {
@available(*, unavailable, message: "Use UUID(_:String)")
public func asUUID() -> uuid_t {
return UUID(self).uuid
}
@available(*, unavailable, message: "Use UUID.string")
public static func fromUUID(uuid: uuid_t) -> String {
return UUID(uuid).string
}
}
@available(*, unavailable, renamed: "UUID()")
public func random_uuid() -> uuid_t {
return UUID().uuid
}
extension String {
/// Parse an HTTP Digest authentication header returning a Dictionary containing each part.
public func parseAuthentication() -> [String:String] {
var ret = [String:String]()
if let _ = self.range(ofString: "Digest ") {
ret["type"] = "Digest"
let wantFields = ["username", "nonce", "nc", "cnonce", "response", "uri", "realm", "qop", "algorithm"]
for field in wantFields {
if let foundField = String.extractField(from: self, named: field) {
ret[field] = foundField
}
}
}
return ret
}
private static func extractField(from frm: String, named: String) -> String? {
guard let range = frm.range(ofString: named + "=") else {
return nil
}
var currPos = range.upperBound
var ret = ""
let quoted = frm[currPos] == "\""
if quoted {
currPos = frm.index(after: currPos)
let tooFar = frm.endIndex
while currPos != tooFar {
if frm[currPos] == "\"" {
break
}
ret.append(frm[currPos])
currPos = frm.index(after: currPos)
}
} else {
let tooFar = frm.endIndex
while currPos != tooFar {
if frm[currPos] == "," {
break
}
ret.append(frm[currPos])
currPos = frm.index(after: currPos)
}
}
return ret
}
}
extension String {
/// Replace all occurrences of `string` with `withString`.
public func stringByReplacing(string strng: String, withString: String) -> String {
guard !strng.isEmpty else {
return self
}
guard !self.isEmpty else {
return self
}
var ret = ""
var idx = self.startIndex
let endIdx = self.endIndex
while idx != endIdx {
if self[idx] == strng[strng.startIndex] {
var newIdx = self.index(after: idx)
var findIdx = strng.index(after: strng.startIndex)
let findEndIdx = strng.endIndex
while newIdx != endIndex && findIdx != findEndIdx && self[newIdx] == strng[findIdx] {
newIdx = self.index(after: newIdx)
findIdx = strng.index(after: findIdx)
}
if findIdx == findEndIdx { // match
ret.append(withString)
idx = newIdx
continue
}
}
ret.append(self[idx])
idx = self.index(after: idx)
}
return ret
}
// For compatibility due to shifting swift
public func contains(string strng: String) -> Bool {
return nil != self.range(ofString: strng)
}
}
extension String {
func begins(with str: String) -> Bool {
return self.characters.starts(with: str.characters)
}
func ends(with str: String) -> Bool {
let mine = self.characters
let theirs = str.characters
guard mine.count >= theirs.count else {
return false
}
return str.begins(with: self[self.index(self.endIndex, offsetBy: -theirs.count)..<mine.endIndex])
}
}
/// Returns the current time according to ICU
/// ICU dates are the number of milliseconds since the reference date of Thu, 01-Jan-1970 00:00:00 GMT
public func getNow() -> Double {
var posixTime = timeval()
gettimeofday(&posixTime, nil)
return Double((posixTime.tv_sec * 1000) + (Int(posixTime.tv_usec)/1000))
}
/// Converts the milliseconds based ICU date to seconds since the epoch
public func icuDateToSeconds(_ icuDate: Double) -> Int {
return Int(icuDate / 1000)
}
/// Converts the seconds since the epoch into the milliseconds based ICU date
public func secondsToICUDate(_ seconds: Int) -> Double {
return Double(seconds * 1000)
}
/// Format a date value according to the indicated format string and return a date string.
/// - parameter date: The date value
/// - parameter format: The format by which the date will be formatted
/// - parameter timezone: The optional timezone in which the date is expected to be based. Default is the local timezone.
/// - parameter locale: The optional locale which will be used when parsing the date. Default is the current global locale.
/// - returns: The resulting date string
/// - throws: `PerfectError.ICUError`
/// - Seealso [Date Time Format Syntax](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax)
public func formatDate(_ date: Double, format: String, timezone inTimezone: String? = nil, locale inLocale: String? = nil) throws -> String {
var t = tm()
var time = time_t(date / 1000.0)
gmtime_r(&time, &t)
let maxResults = 1024
let results = UnsafeMutablePointer<Int8>.allocate(capacity: maxResults)
defer {
results.deallocate(capacity: maxResults)
}
let res = strftime(results, maxResults, format, &t)
if res > 0 {
let formatted = String(validatingUTF8: results)
return formatted!
}
try ThrowSystemError()
}
extension UnicodeScalar {
/// Returns true if the UnicodeScalar is a white space character
public func isWhiteSpace() -> Bool {
return isspace(Int32(self.value)) != 0
}
/// Returns true if the UnicodeScalar is a digit character
public func isDigit() -> Bool {
return isdigit(Int32(self.value)) != 0
}
/// Returns true if the UnicodeScalar is an alpha-numeric character
public func isAlphaNum() -> Bool {
return isalnum(Int32(self.value)) != 0
}
/// Returns true if the UnicodeScalar is a hexadecimal character
public func isHexDigit() -> Bool {
if self.isDigit() {
return true
}
switch self {
case "A", "B", "C", "D", "E", "F", "a", "b", "c", "d", "e", "f":
return true
default:
return false
}
}
}
//public extension NetNamedPipe {
// /// Send the existing & opened `File`'s descriptor over the connection to the recipient
// /// - parameter file: The `File` whose descriptor to send
// /// - parameter callBack: The callback to call when the send completes. The parameter passed will be `true` if the send completed without error.
// /// - throws: `PerfectError.NetworkError`
// public func sendFile(_ file: File, callBack: @escaping (Bool) -> ()) throws {
// try self.sendFd(Int32(file.fd), callBack: callBack)
// }
//
// /// Receive an existing opened `File` descriptor from the sender
// /// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received `File` object or nil.
// /// - throws: `PerfectError.NetworkError`
// public func receiveFile(callBack: @escaping (File?) -> ()) throws {
// try self.receiveFd {
// fd in
//
// if fd == invalidSocket {
// callBack(nil)
// } else {
// callBack(File("", fd: fd))
// }
// }
// }
//}
//
//import OpenSSL
//
//extension String.UTF8View {
// var sha1: [UInt8] {
// let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(SHA_DIGEST_LENGTH))
// defer { bytes.deallocate(capacity: Int(SHA_DIGEST_LENGTH)) }
//
// SHA1(Array<UInt8>(self), (self.count), bytes)
//
// var r = [UInt8]()
// for idx in 0..<Int(SHA_DIGEST_LENGTH) {
// r.append(bytes[idx])
// }
// return r
// }
//}
extension String {
var filePathSeparator: UnicodeScalar {
return UnicodeScalar(47)
}
var fileExtensionSeparator: UnicodeScalar {
return UnicodeScalar(46)
}
public var beginsWithFilePathSeparator: Bool {
let unis = self.characters
guard unis.count > 0 else {
return false
}
return unis[unis.startIndex] == Character(filePathSeparator)
}
public var endsWithFilePathSeparator: Bool {
let unis = self.characters
guard unis.count > 0 else {
return false
}
return unis[unis.index(before: unis.endIndex)] == Character(filePathSeparator)
}
private func filePathComponents(addFirstLast addfl: Bool) -> [String] {
var r = [String]()
let unis = self.characters
guard unis.count > 0 else {
return r
}
if addfl && self.beginsWithFilePathSeparator {
r.append(String(filePathSeparator))
}
r.append(contentsOf: self.characters.split(separator: Character(filePathSeparator)).map { String($0) })
if addfl && self.endsWithFilePathSeparator {
if !self.beginsWithFilePathSeparator || r.count > 1 {
r.append(String(filePathSeparator))
}
}
return r
}
public var filePathComponents: [String] {
return self.filePathComponents(addFirstLast: true)
}
public var lastFilePathComponent: String {
let last = self.filePathComponents(addFirstLast: false).last ?? ""
if last.isEmpty && self.characters.first == Character(filePathSeparator) {
return String(filePathSeparator)
}
return last
}
public var deletingLastFilePathComponent: String {
var comps = self.filePathComponents(addFirstLast: false)
guard comps.count > 1 else {
if self.beginsWithFilePathSeparator {
return String(filePathSeparator)
}
return ""
}
comps.removeLast()
let joined = comps.joined(separator: String(filePathSeparator))
if self.beginsWithFilePathSeparator {
return String(filePathSeparator) + joined
}
return joined
}
private func lastPathSeparator(in unis: String.CharacterView) -> String.CharacterView.Index {
let startIndex = unis.startIndex
var endIndex = unis.endIndex
while endIndex != startIndex {
if unis[unis.index(before: endIndex)] != Character(filePathSeparator) {
break
}
endIndex = unis.index(before: endIndex)
}
return endIndex
}
private func lastExtensionSeparator(in unis: String.CharacterView, endIndex: String.CharacterView.Index) -> String.CharacterView.Index {
var endIndex = endIndex
while endIndex != startIndex {
endIndex = unis.index(before: endIndex)
if unis[endIndex] == Character(fileExtensionSeparator) {
break
}
}
return endIndex
}
public var deletingFileExtension: String {
let unis = self.characters
let startIndex = unis.startIndex
var endIndex = lastPathSeparator(in: unis)
let noTrailsIndex = endIndex
endIndex = lastExtensionSeparator(in: unis, endIndex: endIndex)
guard endIndex != startIndex else {
if noTrailsIndex == startIndex {
return self
}
return self[startIndex..<noTrailsIndex]
}
return self[startIndex..<endIndex]
}
public var filePathExtension: String {
let unis = self.characters
let startIndex = unis.startIndex
var endIndex = lastPathSeparator(in: unis)
let noTrailsIndex = endIndex
endIndex = lastExtensionSeparator(in: unis, endIndex: endIndex)
guard endIndex != startIndex else {
return ""
}
return self[unis.index(after: endIndex)..<noTrailsIndex]
}
public var resolvingSymlinksInFilePath: String {
return File(self).realPath
}
}
|
apache-2.0
|
86bb5009688d690bcf0b097c97a56320
| 26.610465 | 165 | 0.653401 | 3.362124 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/PromiseKit/Sources/AnyPromise.swift
|
4
|
6107
|
import Foundation
/**
__AnyPromise is an implementation detail.
Because of how ObjC/Swift compatability work we have to compose our AnyPromise
with this internal object, however this is still part of the public interface.
Sadly. Please don’t use it.
*/
@objc(__AnyPromise) public class __AnyPromise: NSObject {
fileprivate let box: Box<Any?>
@objc public init(resolver body: (@escaping (Any?) -> Void) -> Void) {
box = EmptyBox<Any?>()
super.init()
body {
if let p = $0 as? AnyPromise {
p.d.__pipe(self.box.seal)
} else {
self.box.seal($0)
}
}
}
@objc public func __thenOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise {
return AnyPromise(__D: __AnyPromise(resolver: { resolve in
self.__pipe { obj in
if !(obj is NSError) {
q.async {
resolve(execute(obj))
}
} else {
resolve(obj)
}
}
}))
}
@objc public func __catchOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise {
return AnyPromise(__D: __AnyPromise(resolver: { resolve in
self.__pipe { obj in
if obj is NSError {
q.async {
resolve(execute(obj))
}
} else {
resolve(obj)
}
}
}))
}
@objc public func __ensureOn(_ q: DispatchQueue, execute: @escaping () -> Void) -> AnyPromise {
return AnyPromise(__D: __AnyPromise(resolver: { resolve in
self.__pipe { obj in
q.async {
execute()
resolve(obj)
}
}
}))
}
@objc public func __wait() -> Any? {
if Thread.isMainThread {
conf.logHandler(.waitOnMainThread)
}
var result = __value
if result == nil {
let group = DispatchGroup()
group.enter()
self.__pipe { obj in
result = obj
group.leave()
}
group.wait()
}
return result
}
/// Internal, do not use! Some behaviors undefined.
@objc public func __pipe(_ to: @escaping (Any?) -> Void) {
let to = { (obj: Any?) -> Void in
if obj is NSError {
to(obj) // or we cannot determine if objects are errors in objc land
} else {
to(obj)
}
}
switch box.inspect() {
case .pending:
box.inspect {
switch $0 {
case .pending(let handlers):
handlers.append { obj in
to(obj)
}
case .resolved(let obj):
to(obj)
}
}
case .resolved(let obj):
to(obj)
}
}
@objc public var __value: Any? {
switch box.inspect() {
case .resolved(let obj):
return obj
default:
return nil
}
}
@objc public var __pending: Bool {
switch box.inspect() {
case .pending:
return true
case .resolved:
return false
}
}
}
extension AnyPromise: Thenable, CatchMixin {
/// - Returns: A new `AnyPromise` bound to a `Promise<Any>`.
public convenience init<U: Thenable>(_ bridge: U) {
self.init(__D: __AnyPromise(resolver: { resolve in
bridge.pipe {
switch $0 {
case .rejected(let error):
resolve(error as NSError)
case .fulfilled(let value):
resolve(value)
}
}
}))
}
public func pipe(to body: @escaping (Result<Any?>) -> Void) {
func fulfill() {
// calling through to the ObjC `value` property unwraps (any) PMKManifold
// and considering this is the Swift pipe; we want that.
body(.fulfilled(self.value(forKey: "value")))
}
switch box.inspect() {
case .pending:
box.inspect {
switch $0 {
case .pending(let handlers):
handlers.append {
if let error = $0 as? Error {
body(.rejected(error))
} else {
fulfill()
}
}
case .resolved(let error as Error):
body(.rejected(error))
case .resolved:
fulfill()
}
}
case .resolved(let error as Error):
body(.rejected(error))
case .resolved:
fulfill()
}
}
fileprivate var d: __AnyPromise {
return value(forKey: "__d") as! __AnyPromise
}
var box: Box<Any?> {
return d.box
}
public var result: Result<Any?>? {
guard let value = __value else {
return nil
}
if let error = value as? Error {
return .rejected(error)
} else {
return .fulfilled(value)
}
}
public typealias T = Any?
}
#if swift(>=3.1)
public extension Promise where T == Any? {
convenience init(_ anyPromise: AnyPromise) {
self.init {
anyPromise.pipe(to: $0.resolve)
}
}
}
#else
extension AnyPromise {
public func asPromise() -> Promise<Any?> {
return Promise(.pending, resolver: { resolve in
pipe { result in
switch result {
case .rejected(let error):
resolve.reject(error)
case .fulfilled(let obj):
resolve.fulfill(obj)
}
}
})
}
}
#endif
|
mit
|
a9cbb5149b3674a46f773328858e403e
| 26.254464 | 102 | 0.445209 | 4.876198 | false | false | false | false |
KoalaTeaCode/KoalaTeaPlayer
|
KoalaTeaPlayer/Classes/YTView/NavVC.swift
|
1
|
3806
|
//
// NavVC.swift
// KoalaTeaPlayer
//
// Created by Craig Holliday on 8/18/17.
// Copyright © 2017 Koala Tea. All rights reserved.
//
import UIKit
public class YTPlayerViewNavigationController: UINavigationController {
//MARK: Properties
var ytPlayerView: YTPlayerView!
let hiddenOrigin: CGPoint = {
let y = UIScreen.main.bounds.height - (UIScreen.main.bounds.width * 9 / 32) - 10
let x = -UIScreen.main.bounds.width
let coordinate = CGPoint.init(x: x, y: y)
return coordinate
}()
let minimizedOrigin: CGPoint = {
let x = UIScreen.main.bounds.width/2 - 10
let y = UIScreen.main.bounds.height - (UIScreen.main.bounds.width * 9 / 32) - 10
let coordinate = CGPoint.init(x: x, y: y)
return coordinate
}()
let fullScreenOrigin = CGPoint.init(x: 0, y: 0)
override public func viewDidLoad() {
super.viewDidLoad()
let videoUrl = URL(string: "http://wpc.1765A.taucdn.net/801765A/video/uploads/videos/65c3a707-016e-474c-8838-c295bb491a16/index.m3u8")
let asset = Asset(assetName: "test", url: videoUrl!)
let frame = CGRect(x: 0, y: 0, width: self.view.width, height: (self.view.width / (16/9)))
ytPlayerView = YTPlayerView(frame: frame)
ytPlayerView.asset = asset
self.ytPlayerView.delegate = self
self.view.addSubview(ytPlayerView)
NotificationCenter.default.addObserver(self, selector: #selector(self.orientationChange), name: .UIDeviceOrientationDidChange, object: nil)
}
@objc func orientationChange() {
self.ytPlayerView.orientationChange()
}
override public var shouldAutorotate: Bool {
return false
}
}
extension YTPlayerViewNavigationController: YTPlayerViewDelegate {
func animatePlayView(toState: YTPlayerState) {
// switch toState {
// case .fullScreen:
// UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 5, options: [.beginFromCurrentState], animations: {
// self.ytPlayerView.frame.origin = self.fullScreenOrigin
// })
// case .minimized:
// UIView.animate(withDuration: 0.3, animations: {
// self.ytPlayerView.frame.origin = self.minimizedOrigin
// })
// case .hidden:
// UIView.animate(withDuration: 0.3, animations: {
// self.ytPlayerView.frame.origin = self.hiddenOrigin
// })
// }
}
func positionDuringSwipe(scaleFactor: CGFloat) -> CGPoint {
let width = UIScreen.main.bounds.width * 0.5 * scaleFactor
let height = width * 9 / 16
let x = (UIScreen.main.bounds.width - 10) * scaleFactor - width
let y = (UIScreen.main.bounds.height - 10) * scaleFactor - height
let coordinate = CGPoint.init(x: x, y: y)
return coordinate
}
//MARK: Delegate methods
public func didMinimize() {
// self.animatePlayView(toState: .minimized)
}
public func didmaximize(){
// self.animatePlayView(toState: .portrait)
}
public func didEndedSwipe(toState: YTPlayerState){
// self.animatePlayView(toState: toState)
}
public func swipeToMinimize(translation: CGFloat, toState: YTPlayerState){
// switch toState {
// case .fullScreen:
// self.ytPlayerView.frame.origin = self.positionDuringSwipe(scaleFactor: translation)
// case .hidden:
// self.ytPlayerView.frame.origin.x = UIScreen.main.bounds.width/2 - abs(translation) - 10
// case .minimized:
// self.ytPlayerView.frame.origin = self.positionDuringSwipe(scaleFactor: translation)
// }
}
}
|
mit
|
6fe047c379031e69e9f5620c4bd51e21
| 35.238095 | 159 | 0.626281 | 4.017951 | false | false | false | false |
stripe/stripe-ios
|
StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/PostDetectionAlgorithm.swift
|
1
|
8679
|
import Foundation
/// Organize the boxes to find possible numbers.
///
/// After running detection, the post processing algorithm will try to find
/// sequences of boxes that are plausible card numbers. The basic techniques
/// that it uses are non-maximum suppression and depth first search on box
/// sequences to find likely numbers. There are also a number of heuristics
/// for filtering out unlikely sequences.
struct PostDetectionAlgorithm {
let kNumberWordCount = 4
let kAmexWordCount = 5
let kMaxBoxesToDetect = 20
let kDeltaRowForCombine = 2
let kDeltaColForCombine = 2
let kDeltaRowForHorizontalNumbers = 1
let kDeltaColForVerticalNumbers = 1
let sortedBoxes: [DetectedBox]
let numRows: Int
let numCols: Int
init(
boxes: [DetectedBox]
) {
self.sortedBoxes = boxes.sorted { $0.confidence > $1.confidence }.prefix(kMaxBoxesToDetect)
.map { $0 }
// it's ok if this doesn't match the card row/col counts because we only
// use this for our internal algorithms. I prefer doing this as it make
// proving array bounds easier since everything is local and as long as
// we only access arrays using row/col from our boxes then we'll always
// be in bounds
self.numRows = (self.sortedBoxes.map { $0.row }.max() ?? 0) + 1
self.numCols = (self.sortedBoxes.map { $0.col }.max() ?? 0) + 1
}
/// Finds traditional numbers that are horizontal on a 16 digit card.
func horizontalNumbers() -> [[DetectedBox]] {
let boxes = self.combineCloseBoxes(
deltaRow: kDeltaRowForCombine,
deltaCol: kDeltaColForCombine
)
let lines = self.findHorizontalNumbers(words: boxes, numberOfBoxes: kNumberWordCount)
// boxes should be roughly evenly spaced, reject any that aren't
return lines.filter { line in
let deltas = zip(line, line.dropFirst()).map { box, nextBox in nextBox.col - box.col }
let maxDelta = deltas.max() ?? 0
let minDelta = deltas.min() ?? 0
return (maxDelta - minDelta) <= 2
}
}
/// Used for Visa quick read where the digits are in groups of four but organized veritcally
func verticalNumbers() -> [[DetectedBox]] {
let boxes = self.combineCloseBoxes(
deltaRow: kDeltaRowForCombine,
deltaCol: kDeltaColForCombine
)
let lines = self.findVerticalNumbers(words: boxes, numberOfBoxes: kNumberWordCount)
// boxes should be roughly evenly spaced, reject any that aren't
return lines.filter { line in
let deltas = zip(line, line.dropFirst()).map { box, nextBox in nextBox.row - box.row }
let maxDelta = deltas.max() ?? 0
let minDelta = deltas.min() ?? 0
return (maxDelta - minDelta) <= 2
}
}
/// Finds 15 digit horizontal Amex card numbers.
///
/// Amex has groups of 4 6 5 numbers and our detection algorithm detects clusters of four
/// digits, but we did design it to detect the groups of four within the clusters of 5 and 6.
/// Thus, our goal with Amex is to find enough boxes of 4 to cover all of the amex digits.
func amexNumbers() -> [[DetectedBox]] {
let boxes = self.combineCloseBoxes(deltaRow: kDeltaRowForCombine, deltaCol: 1)
let lines = self.findHorizontalNumbers(words: boxes, numberOfBoxes: kAmexWordCount)
return lines.filter { line in
let colDeltas = zip(line, line.dropFirst()).map { box, nextBox in nextBox.col - box.col
}
// we have roughly evenly spaced clusters. A single box of four, a cluster of 6 and then
// a cluster of 5. We try to recognize the first and last few digits of the 5 and 6
// cluster, and the 5 and 6 cluster are roughly evenly spaced but the boxes within
// are close
let evenColDeltas = colDeltas.enumerated().filter { $0.0 % 2 == 0 }.map { $0.1 }
let oddColDeltas = colDeltas.enumerated().filter { $0.0 % 2 == 1 }.map { $0.1 }
let evenOddDeltas = zip(evenColDeltas, oddColDeltas).map { even, odd in
Double(even) / Double(odd)
}
return evenOddDeltas.reduce(true) { $0 && $1 >= 2.0 }
}
}
/// Combine close boxes favoring high confidence boxes.
func combineCloseBoxes(deltaRow: Int, deltaCol: Int) -> [DetectedBox] {
var cardGrid: [[Bool]] = Array(
repeating: Array(repeating: false, count: self.numCols),
count: self.numRows
)
for box in self.sortedBoxes {
cardGrid[box.row][box.col] = true
}
// since the boxes are sorted by confidence, go through them in order to
// result in only high confidence boxes winning. There are corner cases
// where this will leave extra boxes, but that's ok because we don't
// need to be perfect here
for box in self.sortedBoxes {
if cardGrid[box.row][box.col] == false {
continue
}
for row in (box.row - deltaRow)...(box.row + deltaRow) {
for col in (box.col - deltaCol)...(box.col + deltaCol) {
if row >= 0 && row < numRows && col >= 0 && col < numCols {
cardGrid[row][col] = false
}
}
}
// add this box back
cardGrid[box.row][box.col] = true
}
return self.sortedBoxes.filter { cardGrid[$0.row][$0.col] }
}
/// Find all boxes that form a sequence of four boxes.
///
/// Does a depth first search on all boxes to find all boxes that form
/// a line with four boxes. The predicate dictates which boxes are added
/// so we have a separate prediate for horizontal vs vertical numbers.
func findNumbers(
currentLine: [DetectedBox],
words: [DetectedBox],
predicate: ((DetectedBox, DetectedBox) -> Bool),
numberOfBoxes: Int,
lines: inout [[DetectedBox]]
) {
if currentLine.count == numberOfBoxes {
lines.append(currentLine)
return
}
if words.count == 0 {
return
}
guard let currentWord = currentLine.last else {
return
}
for (idx, word) in words.enumerated() {
if predicate(currentWord, word) {
findNumbers(
currentLine: (currentLine + [word]),
words: words.dropFirst(idx + 1).map { $0 },
predicate: predicate,
numberOfBoxes: numberOfBoxes,
lines: &lines
)
}
}
}
func verticalAddBoxPredicate(_ currentWord: DetectedBox, _ nextWord: DetectedBox) -> Bool {
let deltaCol = kDeltaColForVerticalNumbers
return nextWord.row > currentWord.row && nextWord.col >= (currentWord.col - deltaCol)
&& nextWord.col <= (currentWord.col + deltaCol)
}
func horizontalAddBoxPredicate(_ currentWord: DetectedBox, _ nextWord: DetectedBox) -> Bool {
let deltaRow = kDeltaRowForHorizontalNumbers
return nextWord.col > currentWord.col && nextWord.row >= (currentWord.row - deltaRow)
&& nextWord.row <= (currentWord.row + deltaRow)
}
// Note: this is simple but inefficient. Since we're dealing with small
// lists (eg 20 items) it should be fine
func findHorizontalNumbers(words: [DetectedBox], numberOfBoxes: Int) -> [[DetectedBox]] {
let sortedWords = words.sorted { $0.col < $1.col }
var lines: [[DetectedBox]] = [[]]
for (idx, word) in sortedWords.enumerated() {
findNumbers(
currentLine: [word],
words: sortedWords.dropFirst(idx + 1).map { $0 },
predicate: horizontalAddBoxPredicate,
numberOfBoxes: numberOfBoxes,
lines: &lines
)
}
return lines
}
func findVerticalNumbers(words: [DetectedBox], numberOfBoxes: Int) -> [[DetectedBox]] {
let sortedWords = words.sorted { $0.row < $1.row }
var lines: [[DetectedBox]] = [[]]
for (idx, word) in sortedWords.enumerated() {
findNumbers(
currentLine: [word],
words: sortedWords.dropFirst(idx + 1).map { $0 },
predicate: verticalAddBoxPredicate,
numberOfBoxes: numberOfBoxes,
lines: &lines
)
}
return lines
}
}
|
mit
|
2407366d636a70cadbdb4875b62f5e51
| 38.094595 | 100 | 0.591773 | 4.376702 | false | false | false | false |
zzgo/v2ex
|
v2ex/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
|
56
|
13245
|
//
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2017 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 os(macOS)
import AppKit
#else
import UIKit
#endif
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
base.image = placeholder
setWebURL(nil)
completionHandler?(nil, nil, .none, nil)
return .empty
}
var options = options ?? KingfisherEmptyOptionsInfo
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
if base.shouldPreloadAllGIF() {
options.append(.preloadAllGIFData)
}
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.webURL else {
return
}
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
return
}
self.setImageTask(nil)
guard let image = image else {
maybeIndicator?.stopAnimatingView()
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
maybeIndicator?.stopAnimatingView()
strongBase.image = image
completionHandler?(image, error, cacheType, imageURL)
return
}
#if !os(macOS)
UIView.transition(with: strongBase, duration: 0.0, options: [],
animations: { maybeIndicator?.stopAnimatingView() },
completion: { _ in
UIView.transition(with: strongBase, duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: {
// Set image property in the animation.
transition.animations?(strongBase, image)
},
completion: { finished in
transition.completion?(finished)
completionHandler?(image, error, cacheType, imageURL)
})
})
#endif
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: ImageView {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL?) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
public var indicatorType: IndicatorType {
get {
let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
return indicator ?? .none
}
set {
switch newValue {
case .none:
indicator = nil
case .activity:
indicator = ActivityIndicator()
case .image(let data):
indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator):
indicator = anIndicator
}
objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public fileprivate(set) var indicator: Indicator? {
get {
return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
newIndicator.view.frame = base.frame
newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
newIndicator.view.isHidden = true
base.addSubview(newIndicator.view)
}
// Save in associated object
objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web. Deprecated. Use `kf` namespacing instead.
*/
extension ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage")
@discardableResult
public func kf_setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
/// Get the image URL binded to this image view.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")
public var kf_webURL: URL? { return kf.webURL }
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType")
public var kf_indicatorType: IndicatorType {
get { return kf.indicatorType }
set { kf.indicatorType = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator")
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `kf_indicatorType` is `.none`.
public private(set) var kf_indicator: Indicator? {
get { return kf.indicator }
set { kf.indicator = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask")
fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask")
fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL")
fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) }
}
extension ImageView {
func shouldPreloadAllGIF() -> Bool { return true }
}
|
mit
|
7f4ea88f5a9c6737bd4fb4f5e7153c6f
| 44.359589 | 173 | 0.601284 | 5.593328 | false | false | false | false |
nodes-ios/NStackSDK
|
NStackSDK/NStackSDK/Classes/Translations/Translatable.swift
|
1
|
4201
|
//
// Translatable.swift
// NStack
//
// Created by Chris Combs on 08/09/15.
// Copyright © 2015 Nodes. All rights reserved.
//
import Foundation
import TranslationManager
public struct Localizable: LocalizableModel {
public subscript(key: String) -> LocalizableSection? {
// switch key {
// case CodingKeys.oneMoreSection.stringValue: return oneMoreSection
// case CodingKeys.otherSection.stringValue: return otherSection
// case CodingKeys.defaultSection.stringValue: return defaultSection
// default: return nil
// }
print("DEFAULT IMPL: ABOUT TO RETURN NIL FROM NStackSDK.Translatable")
return nil
}
/*
public var oneMoreSection = OneMoreSection()
public var otherSection = OtherSection()
public var defaultSection = DefaultSection()
enum CodingKeys: String, CodingKey {
case oneMoreSection
case otherSection
case defaultSection = "default"
}
public init() { }
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
oneMoreSection = try container.decodeIfPresent(OneMoreSection.self, forKey: .oneMoreSection) ?? oneMoreSection
otherSection = try container.decodeIfPresent(OtherSection.self, forKey: .otherSection) ?? otherSection
defaultSection = try container.decodeIfPresent(DefaultSection.self, forKey: .defaultSection) ?? defaultSection
}
public subscript(key: String) -> LocalizableSection? {
switch key {
case CodingKeys.oneMoreSection.stringValue: return oneMoreSection
case CodingKeys.otherSection.stringValue: return otherSection
case CodingKeys.defaultSection.stringValue: return defaultSection
default: return nil
}
}
public final class OneMoreSection: LocalizableSection {
public var test2 = ""
public var soManyKeys = ""
public var test1 = ""
public init() { }
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
test2 = try container.decodeIfPresent(String.self, forKey: .test2) ?? "__test2"
soManyKeys = try container.decodeIfPresent(String.self, forKey: .soManyKeys) ?? "__soManyKeys"
test1 = try container.decodeIfPresent(String.self, forKey: .test1) ?? "__test1"
}
public subscript(key: String) -> String? {
switch key {
case CodingKeys.test2.stringValue: return test2
case CodingKeys.soManyKeys.stringValue: return soManyKeys
case CodingKeys.test1.stringValue: return test1
default: return nil
}
}
}
public final class OtherSection: LocalizableSection {
public var otherString = ""
public init() { }
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
otherString = try container.decodeIfPresent(String.self, forKey: .otherString) ?? "__otherString"
}
public subscript(key: String) -> String? {
switch key {
case CodingKeys.otherString.stringValue: return otherString
default: return nil
}
}
}
public final class DefaultSection: LocalizableSection {
public var keyys = ""
public var successKey = ""
public init() { }
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
keyys = try container.decodeIfPresent(String.self, forKey: .keyys) ?? "__keyys"
successKey = try container.decodeIfPresent(String.self, forKey: .successKey) ?? "__successKey"
}
public subscript(key: String) -> String? {
switch key {
case CodingKeys.keyys.stringValue: return keyys
case CodingKeys.successKey.stringValue: return successKey
default: return nil
}
}
}
*/
}
|
mit
|
4a5a660b6cc344d42210f905a400981e
| 35.521739 | 118 | 0.62881 | 4.849885 | false | true | false | false |
tcamin/CustomCoreImageFilteringDemo
|
CustomCoreImageFilteringDemo/CoreImageFiltering/OneColorFocusCoreImageFilter.swift
|
1
|
2368
|
//
// OneColorFocusCoreImageFilter.swift
// CustomCoreImageFilteringDemo
//
// Created by Tomas Camin on 08/10/15.
// Copyright © 2015 Tomas Camin. All rights reserved.
//
import UIKit
class OneColorFocusCoreImageFilter: CIFilter {
private static var kernel: CIColorKernel?
private static var context: CIContext?
private var _inputImage: CIImage?
private var inputImage: CIImage? {
get { return _inputImage }
set { _inputImage = newValue }
}
private var focusColor: CIColor?
init(image: UIImage, focusColorRed: Int, focusColorGreen: Int, focusColorBlue: Int) {
super.init()
OneColorFocusCoreImageFilter.preload()
inputImage = CIImage(image: image)
focusColor = CIColor(red: CGFloat(focusColorRed) / 255.0, green: CGFloat(focusColorGreen) / 255.0, blue: CGFloat(focusColorBlue) / 255.0)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
OneColorFocusCoreImageFilter.preload()
}
override var outputImage : CIImage! {
if let inputImage = inputImage,
let kernel = OneColorFocusCoreImageFilter.kernel,
let fc = focusColor {
return kernel.applyWithExtent(inputImage.extent, roiCallback: { (_, _) -> CGRect in return inputImage.extent }, arguments: [inputImage, fc]) // to support iOS8
// return kernel.applyWithExtent(inputImage.extent, arguments: [inputImage, fc.red, fc.green, fc.blue]) // iOS9 and newer
}
return nil
}
func outputUIImage() -> UIImage {
let ciimage = self.outputImage
return UIImage(CGImage: OneColorFocusCoreImageFilter.context!.createCGImage(ciimage, fromRect: ciimage.extent))
}
private class func createKernel() -> CIColorKernel {
let kernelString = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("OneColorFocusCoreImageFilter", ofType: "cikernel")!, encoding: NSUTF8StringEncoding)
return CIColorKernel(string: kernelString)!
}
class func preload() {
// preloading kernel speeds up first execution of filter
if kernel != nil {
return
}
kernel = createKernel()
context = CIContext(options: [kCIContextWorkingColorSpace: NSNull()])
}
}
|
mit
|
6e007ff9eb0e89a95cb5b2546080c751
| 34.878788 | 178 | 0.65357 | 4.543186 | false | false | false | false |
hgl888/firefox-ios
|
Utils/Extensions/NSURLExtensions.swift
|
1
|
11210
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
private struct ETLDEntry: CustomStringConvertible {
let entry: String
var isNormal: Bool { return isWild || !isException }
var isWild: Bool = false
var isException: Bool = false
init(entry: String) {
self.entry = entry
self.isWild = entry.hasPrefix("*")
self.isException = entry.hasPrefix("!")
}
private var description: String {
return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }"
}
}
private typealias TLDEntryMap = [String:ETLDEntry]
private func loadEntriesFromDisk() -> TLDEntryMap? {
if let data = NSString.contentsOfFileWithResourceName("effective_tld_names", ofType: "dat", fromBundle: NSBundle(identifier: "org.mozilla.Shared")!, encoding: NSUTF8StringEncoding, error: nil) {
let lines = data.componentsSeparatedByString("\n")
let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" }
var entries = TLDEntryMap()
for line in trimmedLines {
let entry = ETLDEntry(entry: line)
let key: String
if entry.isWild {
// Trim off the '*.' part of the line
key = line.substringFromIndex(line.startIndex.advancedBy(2))
} else if entry.isException {
// Trim off the '!' part of the line
key = line.substringFromIndex(line.startIndex.advancedBy(1))
} else {
key = line
}
entries[key] = entry
}
return entries
}
return nil
}
private var etldEntries: TLDEntryMap? = {
return loadEntriesFromDisk()
}()
// MARK: - Local Resource URL Extensions
extension NSURL {
public func getResourceValueForKey(key: String) -> AnyObject? {
var val: AnyObject?
do {
try getResourceValue(&val, forKey: key)
} catch _ {
return nil
}
return val
}
public func getResourceLongLongForKey(key: String) -> Int64? {
return (getResourceValueForKey(key) as? NSNumber)?.longLongValue
}
public func getResourceBoolForKey(key: String) -> Bool? {
return getResourceValueForKey(key) as? Bool
}
public var isRegularFile: Bool {
return getResourceBoolForKey(NSURLIsRegularFileKey) ?? false
}
public func lastComponentIsPrefixedBy(prefix: String) -> Bool {
return (pathComponents?.last?.hasPrefix(prefix) ?? false)
}
}
extension NSURL {
public func withQueryParams(params: [NSURLQueryItem]) -> NSURL {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
var items = (components.queryItems ?? [])
for param in params {
items.append(param)
}
components.queryItems = items
return components.URL!
}
public func withQueryParam(name: String, value: String) -> NSURL {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
let item = NSURLQueryItem(name: name, value: value)
components.queryItems = (components.queryItems ?? []) + [item]
return components.URL!
}
public func getQuery() -> [String: String] {
var results = [String: String]()
let keyValues = self.query?.componentsSeparatedByString("&")
if keyValues?.count > 0 {
for pair in keyValues! {
let kv = pair.componentsSeparatedByString("=")
if kv.count > 1 {
results[kv[0]] = kv[1]
}
}
}
return results
}
public var hostPort: String? {
if let host = self.host {
if let port = self.port?.intValue {
return "\(host):\(port)"
}
return host
}
return nil
}
public func normalizedHostAndPath() -> String? {
if let normalizedHost = self.normalizedHost() {
return normalizedHost + (self.path ?? "/")
}
return nil
}
public func absoluteDisplayString() -> String? {
var urlString = self.absoluteString
// For http URLs, get rid of the trailing slash if the path is empty or '/'
if (self.scheme == "http" || self.scheme == "https") && (self.path == "/" || self.path == nil) && urlString.endsWith("/") {
urlString = urlString.substringToIndex(urlString.endIndex.advancedBy(-1))
}
// If it's basic http, strip out the string but leave anything else in
if urlString.hasPrefix("http://") ?? false {
return urlString.substringFromIndex(urlString.startIndex.advancedBy(7))
} else {
return urlString
}
}
/**
Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix
with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain
would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc).
:returns: The base domain string for the given host name.
*/
public func baseDomain() -> String? {
if let host = self.host {
// If this is just a hostname and not a FQDN, use the entire hostname.
if !host.contains(".") {
return host
}
return publicSuffixFromHost(host, withAdditionalParts: 1)
} else {
return nil
}
}
/**
* Returns just the domain, but with the same scheme, and a trailing '/'.
*
* E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/
*
* Any failure? Return this URL.
*/
public func domainURL() -> NSURL {
if let normalized = self.normalizedHost() {
return NSURL(scheme: self.scheme, host: normalized, path: "/") ?? self
}
return self
}
public func normalizedHost() -> String? {
if var host = self.host {
if let range = host.rangeOfString("^(www|mobile|m)\\.", options: .RegularExpressionSearch) {
host.replaceRange(range, with: "")
}
return host
}
return nil
}
/**
Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/.
For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk.
:returns: The public suffix for within the given hostname.
*/
public func publicSuffix() -> String? {
if let host = self.host {
return publicSuffixFromHost(host, withAdditionalParts: 0)
} else {
return nil
}
}
}
//MARK: Private Helpers
private extension NSURL {
private func publicSuffixFromHost( host: String, withAdditionalParts additionalPartCount: Int) -> String? {
if host.isEmpty {
return nil
}
// Check edge case where the host is either a single or double '.'.
if host.isEmpty || NSString(string: host).lastPathComponent == "." {
return ""
}
/**
* The following algorithm breaks apart the domain and checks each sub domain against the effective TLD
* entries from the effective_tld_names.dat file. It works like this:
*
* Example Domain: test.bbc.co.uk
* TLD Entry: bbc
*
* 1. Start off by checking the current domain (test.bbc.co.uk)
* 2. Also store the domain after the next dot (bbc.co.uk)
* 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks:
* i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches
* since it satisfies the wildcard requirement.
* ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then
* currentDomain is a valid TLD
* iii. If the entry we matched is an exception case, then the base domain is the part after the next dot
*
* On the next run through the loop, we set the new domain to check as the part after the next dot,
* update the next dot reference to be the string after the new next dot, and check the TLD entries again.
* If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the
* top domain level so we use it by default.
*/
let tokens = host.componentsSeparatedByString(".")
let tokenCount = tokens.count
var suffix: String?
var previousDomain: String? = nil
var currentDomain: String = host
for offset in 0..<tokenCount {
// Store the offset for use outside of this scope so we can add additional parts if needed
let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joinWithSeparator(".") : nil
if let entry = etldEntries?[currentDomain] {
if entry.isWild && (previousDomain != nil) {
suffix = previousDomain
break;
} else if entry.isNormal || (nextDot == nil) {
suffix = currentDomain
break;
} else if entry.isException {
suffix = nextDot
break;
}
}
previousDomain = currentDomain
if let nextDot = nextDot {
currentDomain = nextDot
} else {
break
}
}
var baseDomain: String?
if additionalPartCount > 0 {
if let suffix = suffix {
// Take out the public suffixed and add in the additional parts we want.
let literalFromEnd: NSStringCompareOptions = [NSStringCompareOptions.LiteralSearch, // Match the string exactly.
NSStringCompareOptions.BackwardsSearch, // Search from the end.
NSStringCompareOptions.AnchoredSearch] // Stick to the end.
let suffixlessHost = host.stringByReplacingOccurrencesOfString(suffix, withString: "", options: literalFromEnd, range: nil)
let suffixlessTokens = suffixlessHost.componentsSeparatedByString(".").filter { $0 != "" }
let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount)
let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count]
let partsString = additionalParts.joinWithSeparator(".")
baseDomain = [partsString, suffix].joinWithSeparator(".")
} else {
return nil
}
} else {
baseDomain = suffix
}
return baseDomain
}
}
|
mpl-2.0
|
92d2f07785681cc686190ef7d0a710d9
| 36.61745 | 198 | 0.587779 | 4.714045 | false | false | false | false |
dunkelstern/unchained
|
Unchained/responseClasses/json_response.swift
|
1
|
1212
|
//
// json_response.swift
// unchained
//
// Created by Johannes Schriewer on 13/12/15.
// Copyright © 2015 Johannes Schriewer. All rights reserved.
//
import TwoHundred
import DEjson
/// JSON response, automatically sets correct headers and serializes JSON
public class JSONResponse: HTTPResponseBase {
/// Init with JSONObject
///
/// - parameter statusCode: HTTP Status code to send
/// - parameter body: JSONObject to send
/// - parameter headers: (optional) additional headers to send
/// - parameter contentType: (optional) content type to send (defaults to `application/json`)
public init(_ statusCode: HTTPStatusCode, body: JSONObject, headers: [HTTPHeader]? = nil, contentType: String = "application/json") {
super.init()
guard let jsonData = JSONEncoder(body).jsonString else {
return
}
self.statusCode = statusCode
if let headers = headers {
self.headers.appendContentsOf(headers)
}
self.headers.append(HTTPHeader("Content-Type", contentType))
self.headers.append(HTTPHeader("Accept", "application/json"))
self.body.append(.StringData(jsonData))
}
}
|
bsd-3-clause
|
1475b0e8bfbf9a05777d67110532d216
| 30.894737 | 137 | 0.663088 | 4.657692 | false | false | false | false |
Valine/mr-inspiration
|
ProjectChartSwift/Mr. Inspiration/AppDelegate.swift
|
2
|
7709
|
//
// AppDelegate.swift
// Mr. Inspiration
//
// Created by Lukas Valine on 12/1/15.
// Copyright © 2015 Lukas Valine. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let window = window {
window.backgroundColor = UIColor.whiteColor()
window.rootViewController = RootViewController()
window.makeKeyAndVisible()
}
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.translucent = false
navigationBarAppearace.barStyle = .Black
navigationBarAppearace.tintColor = color1
navigationBarAppearace.barTintColor = UIColor(netHex: 0x808080) //UIColor(netHex: 0xf8f8f8)
//navigationBarAppearace.setBackgroundImage(UIImage(named: "background.bmp"), forBarMetrics: UIBarMetrics.Default)
//navigationBarAppearace.shadowImage = UIImage()
// navigationBarAppearace.translucent = true
navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:color1]
let font = UIFont(name: "HelveticaNeue-Medium", size: 18)
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font!]
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.valine.Mr__Inspiration" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Mr__Inspiration", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
|
gpl-2.0
|
928375abf610e75e3d671de75248a2ac
| 50.731544 | 291 | 0.703166 | 5.626277 | false | false | false | false |
KoheiHayakawa/Form
|
Form/KHAForm/KHATextViewFormCell.swift
|
1
|
3928
|
//
// KHATextViewCell.swift
// KHAForm
//
// Created by Kohei Hayakawa on 3/8/15.
// Copyright (c) 2015 Kohei Hayakawa. All rights reserved.
//
import UIKit
class KHATextViewFormCell: KHAFormCell {
let textView: UIPlaceholderTextView = UIPlaceholderTextView()
private let kCellHeight: CGFloat = 144
private let kFontSize: CGFloat = 16
class var cellID: String {
return "KHATextViewCell"
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
super.selectionStyle = .None
super.frame = CGRect(
x: super.frame.origin.x,
y: super.frame.origin.y,
width: super.frame.width,
height: kCellHeight)
super.contentView.addSubview(textView)
textView.font = UIFont.systemFontOfSize(kFontSize)
textView.setTranslatesAutoresizingMaskIntoConstraints(false)
// TODO: Fix constant value of left and right.
// Current value is optimized for iPhone 6.
// I don't have any good solution for this problem...
contentView.addConstraints([
NSLayoutConstraint(
item: textView,
attribute: .Left,
relatedBy: .Equal,
toItem: contentView,
attribute: .Left,
multiplier: 1,
constant: 10),
NSLayoutConstraint(
item: textView,
attribute: .Right,
relatedBy: .Equal,
toItem: contentView,
attribute: .Right,
multiplier: 1,
constant: -5),
NSLayoutConstraint(
item: textView,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: kCellHeight)]
)
}
}
class UIPlaceholderTextView: UITextView {
lazy var placeholderLabel:UILabel = UILabel()
var placeholderColor:UIColor = UIColor.lightGrayColor()
var placeholder:NSString = ""
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setText(text:NSString) {
super.text = text
self.textChanged(nil)
}
override internal func drawRect(rect: CGRect) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged:", name: UITextViewTextDidChangeNotification, object: nil)
if(self.placeholder.length > 0) {
self.placeholderLabel.frame = CGRectMake(4,8,self.bounds.size.width - 16,0)
self.placeholderLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
self.placeholderLabel.numberOfLines = 0
self.placeholderLabel.font = self.font
self.placeholderLabel.backgroundColor = UIColor.clearColor()
self.placeholderLabel.textColor = self.placeholderColor
self.placeholderLabel.alpha = 0
self.placeholderLabel.tag = 999
self.placeholderLabel.text = self.placeholder
self.placeholderLabel.sizeToFit()
self.addSubview(placeholderLabel)
}
self.sendSubviewToBack(placeholderLabel)
if(self.text.utf16Count == 0 && self.placeholder.length > 0){
self.viewWithTag(999)?.alpha = 1
}
super.drawRect(rect)
}
internal func textChanged(notification:NSNotification?) -> (Void) {
if(self.placeholder.length == 0){
return
}
if(countElements(self.text) == 0) {
self.viewWithTag(999)?.alpha = 1
}else{
self.viewWithTag(999)?.alpha = 0
}
}
}
|
mit
|
c1ffa3567b53660455cfc1066300d31d
| 32.581197 | 144 | 0.577138 | 5.265416 | false | false | false | false |
CaoRuiming/Academy-Life-iOS-App
|
CA Life/NewsTableViewController.swift
|
1
|
7731
|
//
// NewsTableViewController.swift
// CA Life
//
// Created by Raymond Cao on 5/18/17.
// Copyright © 2017 The Academy Life. All rights reserved.
//
import UIKit
import Foundation
import SystemConfiguration
class NewsTableViewController: UITableViewController, XMLParserDelegate {
//MARK: Properties
var articles = [Article]()
//Parallel arrays to store parsed XML data before making Article abojects
var titles = [String]()
var contents = [String]()
var urls = [String]()
//Variables for XML parser functions
var currentElement:String = ""
var passTitle:Bool = false
var passURL:Bool = false
var passContent:Bool = false
var parser = XMLParser()
override func viewDidLoad() {
super.viewDidLoad()
reloadArticles()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return articles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "TableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TableViewCell else { fatalError("The dequeued cell is not an instance of TopStoriesTableViewCell")}
let article = articles[indexPath.row]
// Configuring the cell...
cell.cellTitle.text = article.title
cell.cellImage.image = article.photo
cell.cellContent.text = article.content
cell.cellUrl = article.url
return cell
}
//MARK: XMLParserDelegate Functions
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName;
if(elementName=="title" || elementName=="link" || elementName=="pubDate") {
if (elementName == "title") {
passTitle = true;
}
else if (elementName == "link") {
passURL = true;
}
else if (elementName == "pubDate") {
passContent = true;
}
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement="";
if (elementName=="title" || elementName=="link" || elementName=="pubDate") {
if (elementName == "title") {
passTitle = false;
}
else if (elementName == "link") {
passURL = false
}
else if (elementName == "pubDate") {
passContent = false
}
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if (passTitle) {
if (string.substring(to: string.index(string.startIndex, offsetBy: 1)) == "’" || string.substring(to: string.index(string.startIndex, offsetBy: 1)) == " " || string.substring(to: string.index(string.startIndex, offsetBy: 1)) == "–" || string.substring(to: string.index(string.startIndex, offsetBy: 1)) == "“" || string.substring(to: string.index(string.startIndex, offsetBy: 1)) == "”" || string.substring(to: string.index(string.startIndex, offsetBy: 1)) == "s") {
titles[titles.count-1] = titles[titles.count-1]+string
}
else {
titles.append(string)
}
}
else if (passURL) {
urls.append(string)
}
else if (passContent) {
contents.append(string.substring(to: string.index(string.startIndex, offsetBy: 16)))
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print("failure error: ", parseError)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//print("You selected cell number: \(indexPath.row)")
performSegue(withIdentifier: "viewArticle", sender: articles[indexPath.row].url)
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewArticle" {
let articleViewVC = segue.destination as! ArticleViewController
articleViewVC.articleUrl = sender as! URL
}
}
//MARK: Populating Table Cells
func reloadArticles(){
if isInternetAvailable() {
//reset everything to prevent duplicate articles
articles.removeAll()
titles.removeAll()
urls.removeAll()
contents.removeAll()
parser = XMLParser(contentsOf: URL(string: "http://ca-life.org/category/news/feed/")!)!
parser.delegate = self
let success:Bool = parser.parse()
if success {
print("parse succeeded")
titles.remove(at: 0)
//print(titles)
urls.remove(at: 0)
//print(urls)
//print(contents)
} else {
print("parse failed")
}
loadArticles()
}
else {
print("error: no internet connection available")
}
}
func loadArticles(){
let defaultImage = UIImage(named: "DefaultImage")
for index in 0...(titles.count-1) {
guard let newArticle = Article(title: titles[index], photo: defaultImage!, content: contents[index], url: URL(string:urls[index])!) else { fatalError("Unable to instatiate article at index \(index)")}
articles.append(newArticle)
}
}
@IBAction func refresh(_ sender: UIRefreshControl) {
reloadArticles()
tableView.reloadData()
print("refresh succeeded")
sender.endRefreshing()
}
//MARK: Check internet availability
func isInternetAvailable() -> Bool
{
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
|
gpl-3.0
|
0e618f74a19dd5ddb9885dc2cf25eb13
| 35.253521 | 477 | 0.602823 | 5.076923 | false | false | false | false |
apple/swift-nio
|
IntegrationTests/tests_04_performance/test_01_resources/test_encode_1000_ws_frames.swift
|
1
|
3622
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOEmbedded
import NIOWebSocket
func doSendFramesHoldingBuffer(channel: EmbeddedChannel, number numberOfFrameSends: Int, data originalData: [UInt8], spareBytesAtFront: Int) throws -> Int {
var data = channel.allocator.buffer(capacity: originalData.count + spareBytesAtFront)
data.moveWriterIndex(forwardBy: spareBytesAtFront)
data.moveReaderIndex(forwardBy: spareBytesAtFront)
data.writeBytes(originalData)
let frame = WebSocketFrame(opcode: .binary, data: data, extensionData: nil)
// We're interested in counting allocations, so this test reads the data from the EmbeddedChannel
// to force the data out of memory.
for _ in 0..<numberOfFrameSends {
channel.writeAndFlush(frame, promise: nil)
_ = try channel.readOutbound(as: ByteBuffer.self)
_ = try channel.readOutbound(as: ByteBuffer.self)
}
return numberOfFrameSends
}
func doSendFramesNewBuffer(channel: EmbeddedChannel, number numberOfFrameSends: Int, data originalData: [UInt8], spareBytesAtFront: Int) throws -> Int {
for _ in 0..<numberOfFrameSends {
// We need a new allocation every time to drop the original data ref.
var data = channel.allocator.buffer(capacity: originalData.count + spareBytesAtFront)
data.moveWriterIndex(forwardBy: spareBytesAtFront)
data.moveReaderIndex(forwardBy: spareBytesAtFront)
data.writeBytes(originalData)
let frame = WebSocketFrame(opcode: .binary, data: data, extensionData: nil)
// We're interested in counting allocations, so this test reads the data from the EmbeddedChannel
// to force the data out of memory.
channel.writeAndFlush(frame, promise: nil)
_ = try channel.readOutbound(as: ByteBuffer.self)
_ = try channel.readOutbound(as: ByteBuffer.self)
}
return numberOfFrameSends
}
func run(identifier: String) {
let channel = EmbeddedChannel()
try! channel.pipeline.addHandler(WebSocketFrameEncoder()).wait()
let data = Array(repeating: UInt8(0), count: 1024)
measure(identifier: identifier + "_holding_buffer") {
let numberDone = try! doSendFramesHoldingBuffer(channel: channel, number: 1000, data: data, spareBytesAtFront: 0)
precondition(numberDone == 1000)
return numberDone
}
measure(identifier: identifier + "_holding_buffer_with_space") {
let numberDone = try! doSendFramesHoldingBuffer(channel: channel, number: 1000, data: data, spareBytesAtFront: 8)
precondition(numberDone == 1000)
return numberDone
}
measure(identifier: identifier + "_new_buffer") {
let numberDone = try! doSendFramesNewBuffer(channel: channel, number: 1000, data: data, spareBytesAtFront: 0)
precondition(numberDone == 1000)
return numberDone
}
measure(identifier: identifier + "_new_buffer_with_space") {
let numberDone = try! doSendFramesNewBuffer(channel: channel, number: 1000, data: data, spareBytesAtFront: 8)
precondition(numberDone == 1000)
return numberDone
}
_ = try! channel.finish()
}
|
apache-2.0
|
f484875f26d896b4d262a5f240439447
| 39.696629 | 156 | 0.680287 | 4.411693 | false | false | false | false |
realm/SwiftLint
|
Source/SwiftLintFramework/Rules/Style/VerticalWhitespaceClosingBracesRuleExamples.swift
|
1
|
3117
|
// swiftlint:disable:next type_name
internal struct VerticalWhitespaceClosingBracesRuleExamples {
private static let beforeTrivialLinesConfiguration = ["only_enforce_before_trivial_lines": true]
static let nonTriggeringExamples = [
Example("[1, 2].map { $0 }.filter { true }"),
Example("[1, 2].map { $0 }.filter { num in true }"),
Example("""
/*
class X {
let x = 5
}
*/
"""),
Example("""
if bool1 {
// do something
// do something
} else if bool2 {
// do something
// do something
// do something
} else {
// do something
// do something
}
""", configuration: beforeTrivialLinesConfiguration)
]
static let violatingToValidExamples = [
Example("""
do {
print("x is 5")
↓
}
"""):
Example("""
do {
print("x is 5")
}
"""),
Example("""
do {
print("x is 5")
↓
}
"""):
Example("""
do {
print("x is 5")
}
"""),
Example("""
do {
print("x is 5")
↓\n \n}
"""):
Example("""
do {
print("x is 5")
}
"""),
Example("""
[
1,
2,
3
↓
]
"""):
Example("""
[
1,
2,
3
]
"""),
Example("""
foo(
x: 5,
y:6
↓
)
"""):
Example("""
foo(
x: 5,
y:6
)
"""),
Example("""
func foo() {
run(5) { x in
print(x)
}
↓
}
"""): Example("""
func foo() {
run(5) { x in
print(x)
}
}
"""),
Example("""
print([
1
↓
])
""", configuration: beforeTrivialLinesConfiguration):
Example("""
print([
1
])
""", configuration: beforeTrivialLinesConfiguration),
Example("""
print([foo {
var sum = 0
for i in 1...5 { sum += i }
return sum
}, foo {
var mul = 1
for i in 1...5 { mul *= i }
return mul
↓
}])
""", configuration: beforeTrivialLinesConfiguration):
Example("""
print([foo {
var sum = 0
for i in 1...5 { sum += i }
return sum
}, foo {
var mul = 1
for i in 1...5 { mul *= i }
return mul
}])
""", configuration: beforeTrivialLinesConfiguration)
]
}
|
mit
|
820d3e93388aefaad897a70ebea2ba6a
| 20.095238 | 100 | 0.325379 | 5.291809 | false | true | false | false |
Samiabo/Weibo
|
Weibo/Weibo/Classes/Discover/DiscoverViewController.swift
|
1
|
2978
|
//
// DiscoverViewController.swift
// Weibo
//
// Created by han xuelong on 2016/12/27.
// Copyright © 2016年 han xuelong. All rights reserved.
//
import UIKit
class DiscoverViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
visitorView.setupVisitorViewInfo(iconName: "visitordiscover_image_message", title: "登录后,别人评论你的微博,给你发消息,都会在这里收到通知")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
1df83dfd8cab1d2bd6d941e3293774a4
| 31.076923 | 136 | 0.667009 | 5.148148 | false | false | false | false |
pkrll/ComicZipper-2
|
ComicZipper/Support/ImageType.swift
|
2
|
711
|
//
// ImageType.swift
// ComicZipper
//
// Created by Ardalan Samimi on 04/01/16.
// Copyright © 2016 Ardalan Samimi. All rights reserved.
//
import Foundation
public enum ImageType: String {
case ButtonCancel = "buttonCancel"
case ButtonDelete = "buttonDelete"
case ButtonClose = "buttonClose"
case ButtonCloseHover = "buttonCloseHover"
case ButtonClosePressed = "buttonClosePressed"
case StatusError = "statusError"
case StatusSuccess = "statusSuccess"
case SettingsAdvanced = "SettingsAdvanced"
case SettingsExcludeFiles = "SettingsExcludeFiles"
case SettingsGeneral = "SettingsGeneral"
case SettingsGeneralAlt = "SettingsGeneralAlt"
case ApplicationIcon = "ComicZipper"
}
|
mit
|
9ba426914e872a67d6cf35c7ba4fcc61
| 27.44 | 57 | 0.756338 | 3.988764 | false | false | false | false |
hyperoslo/Orchestra
|
Source/Data/Sound.swift
|
1
|
374
|
public enum Sound: String {
case Launch = "soundLaunch"
case Push = "soundPush"
case Pop = "soundPop"
case Present = "soundPresent"
case Dismiss = "soundDismiss"
case Button = "soundButton"
case TabBar = "soundTabBar"
case Error = "soundError"
case Warning = "soundWarning"
case RefreshBegin = "soundRefreshBegin"
case RefreshEnd = "soundRefreshEnd"
}
|
mit
|
c70be79cc857d6cce92c153c12f85f30
| 27.769231 | 41 | 0.71123 | 3.70297 | false | false | false | false |
touchopia/HackingWithSwift
|
project22/Project22/ViewController.swift
|
1
|
2109
|
//
// ViewController.swift
// Project22
//
// Created by TwoStraws on 19/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import CoreLocation
import UIKit
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var distanceReading: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
view.backgroundColor = UIColor.gray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
startScanning()
}
}
}
}
func startScanning() {
let uuid = UUID(uuidString: "5A4BCFCE-174E-4BAC-A814-092E77F6B7E5")!
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 123, minor: 456, identifier: "MyBeacon")
locationManager.startMonitoring(for: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
}
func update(distance: CLProximity) {
UIView.animate(withDuration: 0.8) { [unowned self] in
switch distance {
case .unknown:
self.view.backgroundColor = UIColor.gray
self.distanceReading.text = "UNKNOWN"
case .far:
self.view.backgroundColor = UIColor.blue
self.distanceReading.text = "FAR"
case .near:
self.view.backgroundColor = UIColor.orange
self.distanceReading.text = "NEAR"
case .immediate:
self.view.backgroundColor = UIColor.red
self.distanceReading.text = "RIGHT HERE"
}
}
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if beacons.count > 0 {
let beacon = beacons[0]
update(distance: beacon.proximity)
} else {
update(distance: .unknown)
}
}
}
|
unlicense
|
59963dceb176fab14a4133a9750ec5c9
| 25.024691 | 117 | 0.736717 | 3.954972 | false | false | false | false |
slavapestov/swift
|
stdlib/public/core/ImplicitlyUnwrappedOptional.swift
|
1
|
4528
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An optional type that allows implicit member access (via compiler
/// magic).
///
/// The compiler has special knowledge of the existence of
/// `ImplicitlyUnwrappedOptional<Wrapped>`, but always interacts with it using
/// the library intrinsics below.
public enum ImplicitlyUnwrappedOptional<Wrapped> : NilLiteralConvertible {
case None
case Some(Wrapped)
@available(*, unavailable, renamed="Wrapped")
public typealias T = Wrapped
/// Construct a `nil` instance.
public init() { self = .None }
/// Construct a non-`nil` instance that stores `some`.
public init(_ some: Wrapped) { self = .Some(some) }
/// Construct an instance from an explicitly unwrapped optional
/// (`Wrapped?`).
public init(_ v: Wrapped?) {
switch v {
case .Some(let some):
self = .Some(some)
case .None:
self = .None
}
}
/// Create an instance initialized with `nil`.
@_transparent public
init(nilLiteral: ()) {
self = .None
}
/// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`.
@warn_unused_result
public func map<U>(@noescape f: (Wrapped) throws -> U)
rethrows -> ImplicitlyUnwrappedOptional<U> {
switch self {
case .Some(let y):
return .Some(try f(y))
case .None:
return .None
}
}
/// Returns `nil` if `self` is `nil`, `f(self!)` otherwise.
@warn_unused_result
public func flatMap<U>(
@noescape f: (Wrapped) throws -> ImplicitlyUnwrappedOptional<U>
) rethrows -> ImplicitlyUnwrappedOptional<U> {
switch self {
case .Some(let y):
return try f(y)
case .None:
return .None
}
}
}
extension ImplicitlyUnwrappedOptional : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch self {
case .Some(let value):
return String(value)
case .None:
return "nil"
}
}
}
/// Directly conform to CustomDebugStringConvertible to support
/// optional printing. Implementation of that feature relies on
/// _isOptional thus cannot distinguish ImplicitlyUnwrappedOptional
/// from Optional. When conditional conformance is available, this
/// outright conformance can be removed.
extension ImplicitlyUnwrappedOptional : CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _getImplicitlyUnwrappedOptionalValue<Wrapped>(v: Wrapped!) -> Wrapped {
switch v {
case .Some(let x):
return x
case .None:
_preconditionFailure(
"unexpectedly found nil while unwrapping an Optional value")
}
}
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _injectValueIntoImplicitlyUnwrappedOptional<Wrapped>(
v: Wrapped
) -> Wrapped! {
return .Some(v)
}
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _injectNothingIntoImplicitlyUnwrappedOptional<Wrapped>() -> Wrapped! {
return .None
}
#if _runtime(_ObjC)
extension ImplicitlyUnwrappedOptional : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return Swift._getBridgedObjectiveCType(Wrapped.self)!
}
public func _bridgeToObjectiveC() -> AnyObject {
switch self {
case .None:
_preconditionFailure("attempt to bridge an implicitly unwrapped optional containing nil")
case .Some(let x):
return Swift._bridgeToObjectiveC(x)!
}
}
public static func _forceBridgeFromObjectiveC(
x: AnyObject,
inout result: Wrapped!?
) {
result = Swift._forceBridgeFromObjectiveC(x, Wrapped.self)
}
public static func _conditionallyBridgeFromObjectiveC(
x: AnyObject,
inout result: Wrapped!?
) -> Bool {
let bridged: Wrapped? =
Swift._conditionallyBridgeFromObjectiveC(x, Wrapped.self)
if let value = bridged {
result = value
}
return false
}
public static func _isBridgedToObjectiveC() -> Bool {
return Swift._isBridgedToObjectiveC(Wrapped.self)
}
}
#endif
|
apache-2.0
|
b3144cd2d199431520937070370642ce
| 26.113772 | 95 | 0.667182 | 4.541625 | false | false | false | false |
zmian/xcore.swift
|
Sources/Xcore/Swift/Components/Console.swift
|
1
|
8700
|
//
// Xcore
// Copyright © 2015 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
public enum Console {
/// The default value is `.all`.
public static var levelOptions: LevelOptions = .all
/// The default value is `.basic`.
public static var prefixOptions: PrefixOptions = .basic
/// Writes the textual representations of debug message, separated by separator
/// and terminated by terminator, into the standard output.
///
/// - Parameters:
/// - items: Items to write to standard output.
/// - condition: To achieve assert like behavior, you can pass condition that
/// must be met to write ouput.
/// - separator: The separator to use between items.
/// - terminator: To print without a trailing newline, pass `terminator: ""`.
/// - context: The source where this log is executed.
public static func log(_ items: Any..., condition: Bool = true, separator: String = " ", terminator: String = "\n", context: SourceContext = .init()) {
internalPrint(level: .debug, items: items, condition: condition, separator: separator, terminator: terminator, context: context)
}
/// Writes the textual representations of info message, separated by separator
/// and terminated by terminator, into the standard output.
///
/// - Parameters:
/// - items: Items to write to standard output.
/// - condition: To achieve assert like behavior, you can pass condition that
/// must be met to write ouput.
/// - separator: The separator to use between items.
/// - terminator: To print without a trailing newline, pass `terminator: ""`.
/// - context: The source where this log is executed.
public static func info(_ items: Any..., condition: Bool = true, separator: String = " ", terminator: String = "\n", context: SourceContext = .init()) {
internalPrint(level: .info, items: items, condition: condition, separator: separator, terminator: terminator, context: context)
}
/// Writes the textual representations of warning message, separated by
/// separator and terminated by terminator, into the standard output.
///
/// - Parameters:
/// - items: Items to write to standard output.
/// - condition: To achieve assert like behavior, you can pass condition that
/// must be met to write ouput.
/// - separator: The separator to use between items.
/// - terminator: To print without a trailing newline, pass `terminator: ""`.
/// - context: The source where this log is executed.
public static func warn(_ items: Any..., condition: Bool = true, separator: String = " ", terminator: String = "\n", context: SourceContext = .init()) {
internalPrint(level: .warn, items: items, condition: condition, separator: separator, terminator: terminator, context: context)
}
/// Writes the textual representations of error message, separated by separator
/// and terminated by terminator, into the standard output.
///
/// - Parameters:
/// - items: Items to write to standard output.
/// - condition: To achieve assert like behavior, you can pass condition that
/// must be met to write ouput.
/// - separator: The separator to use between items.
/// - terminator: To print without a trailing newline, pass `terminator: ""`.
/// - context: The source where this log is executed.
public static func error(_ items: Any..., condition: Bool = true, separator: String = " ", terminator: String = "\n", context: SourceContext = .init()) {
internalPrint(level: .error, items: items, condition: condition, separator: separator, terminator: terminator, context: context)
}
/// Writes the textual representations of items, separated by separator and
/// terminated by terminator, into the standard output.
///
/// - Parameters:
/// - level: The log level option. The default value is `.debug`.
/// - items: Items to write to standard output.
/// - condition: To achieve assert like behavior, you can pass condition that
/// must be met to write ouput.
/// - separator: The separator to use between items.
/// - terminator: To print without a trailing newline, pass `terminator: ""`.
/// - context: The source where this log is executed.
public static func print(level: LevelOptions = .debug, _ items: Any..., condition: Bool = true, separator: String = " ", terminator: String = "\n", context: SourceContext = .init()) {
internalPrint(level: level, items: items, condition: condition, separator: separator, terminator: terminator, context: context)
}
}
extension Console {
/// Writes the textual representations of items, separated by separator and
/// terminated by terminator, into the standard output.
///
/// - Parameters:
/// - level: The log level option.
/// - items: Items to write to standard output.
/// - condition: To achieve assert like behavior, you can pass condition that
/// must be met to write ouput.
/// - separator: The separator to use between items.
/// - terminator: To print without a trailing newline, pass `terminator: ""`.
/// - context: The source where this log is executed.
private static func internalPrint(level: LevelOptions, items: [Any], condition: Bool = true, separator: String = " ", terminator: String = "\n", context: SourceContext) {
guard levelOptions.contains(level), condition else { return }
let items = items.map { "\($0)" }.joined(separator: separator)
let prefix = prefixOptions(level: level, context: context)
if prefix.isEmpty {
Swift.print(items, terminator: terminator)
} else {
Swift.print(prefix, items, terminator: terminator)
}
}
private static func prefixOptions(level: LevelOptions, context: SourceContext) -> String {
var result: String = ""
if prefixOptions.isEmpty, level.consoleDescription == nil {
return result
}
let contains = prefixOptions.contains
if contains(.date) {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSZ "
result += formatter.string(from: date)
}
if contains(.className) {
result += context.class.lastPathComponent.deletingPathExtension
}
if contains(.functionName) {
let separator = contains(.className) ? "." : ""
result += "\(separator)\(context.function)"
}
if contains(.lineNumber) {
let separator = contains(.className) || contains(.functionName) ? ":" : ""
result += "\(separator)\(context.line)"
}
if !prefixOptions.isEmpty {
result = "[\(result)]"
}
if let description = level.consoleDescription {
let separator = prefixOptions.isEmpty ? "" : " "
result += "\(separator)\(description):"
}
return result
}
}
extension Console {
/// A list of log levels available.
public struct LevelOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let debug = Self(rawValue: 1 << 0)
public static let info = Self(rawValue: 1 << 1)
public static let warn = Self(rawValue: 1 << 2)
public static let error = Self(rawValue: 1 << 3)
public static let all: Self = [debug, info, warn, error]
fileprivate var consoleDescription: String? {
switch self {
case .debug:
return nil
case .info:
return "INFO"
case .warn:
return "WARNING"
case .error:
return "ERROR"
default:
return nil
}
}
}
/// A list of log prefix available.
public struct PrefixOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let className = Self(rawValue: 1 << 0)
public static let functionName = Self(rawValue: 1 << 1)
public static let lineNumber = Self(rawValue: 1 << 2)
public static let date = Self(rawValue: 1 << 3)
public static let all: Self = [className, functionName, lineNumber, date]
public static let basic: Self = [className, lineNumber]
}
}
|
mit
|
5c62912fad51d0c147fb47883e73cf1a
| 42.064356 | 187 | 0.618462 | 4.664343 | false | false | false | false |
ljshj/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Ringtones/AARingtonesViewController.swift
|
1
|
6622
|
//
// AARingtonesViewController.swift
// ActorSDK
//
// Created by Alexey Galaev on 5/27/16.
// Copyright © 2016 Steve Kite. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
public class AARingtonesViewController: AATableViewController {
var audioPlayer: AVAudioPlayer!
var selectedRingtone: String = ""
var completion: ((String) -> ())!
let rootSoundDirectories: [String] = ["/Library/Ringtones"/*,"/System/Library/Audio/UISounds"*/]
var directories: [String] = []
var soundFiles: [(directory: String, files: [String])] = []
init() {
super.init(style: UITableViewStyle.Plain)
self.title = AALocalized("Ringtones")
let cancelButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss"))
let doneButtonItem = UIBarButtonItem(title: AALocalized("NavigationDone"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss"))
self.navigationItem.setLeftBarButtonItem(cancelButtonItem, animated: false)
self.navigationItem.setRightBarButtonItem(doneButtonItem, animated: false)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
for directory in rootSoundDirectories {
directories.append(directory)
let newSoundFile: (directory: String, files: [String]) = (directory, [])
soundFiles.append(newSoundFile)
}
getDirectories()
loadSoundFiles()
tableView.rowHeight = 44.0
tableView.sectionIndexBackgroundColor = UIColor.clearColor()
}
override public func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(true)
if(audioPlayer != nil && audioPlayer.playing){
audioPlayer.stop()
}
}
public override func viewDidDisappear(animated: Bool) {
completion(selectedRingtone)
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getDirectories() {
let fileManager: NSFileManager = NSFileManager()
for directory in rootSoundDirectories {
let directoryURL: NSURL = NSURL(fileURLWithPath: "\(directory)", isDirectory: true)
do {
if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) {
var urlIsaDirectory: ObjCBool = ObjCBool(false)
for url in URLs {
if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) {
if urlIsaDirectory {
let directory: String = "\(url.relativePath!)"
let files: [String] = []
let newSoundFile: (directory: String, files: [String]) = (directory, files)
directories.append("\(directory)")
soundFiles.append(newSoundFile)
}
}
}
}
} catch {
debugPrint("\(error)")
}
}
}
func loadSoundFiles() {
for i in 0...directories.count-1 {
let fileManager: NSFileManager = NSFileManager()
let directoryURL: NSURL = NSURL(fileURLWithPath: directories[i], isDirectory: true)
do {
if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) {
var urlIsaDirectory: ObjCBool = ObjCBool(false)
for url in URLs {
if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) {
if !urlIsaDirectory {
soundFiles[i].files.append("\(url.lastPathComponent!)")
}
}
}
}
} catch {
debugPrint("\(error)")
}
}
}
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return soundFiles[section].files.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Ringtones"
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let fileName: String = soundFiles[indexPath.section].files[indexPath.row]
let cell: AACommonCell = tableView.dequeueCell(indexPath)
cell.style = .Normal
let name = fileName.componentsSeparatedByString(".m4r")
cell.textLabel?.text = name.first
return cell
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? AACommonCell {
cell.style = .Normal
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let directory: String = soundFiles[indexPath.section].directory
let fileName: String = soundFiles[indexPath.section].files[indexPath.row]
let fileURL: NSURL = NSURL(fileURLWithPath: "\(directory)/\(fileName)")
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: fileURL)
audioPlayer.play()
} catch {
debugPrint("\(error)")
selectedRingtone = ""
}
let cell = tableView.cellForRowAtIndexPath(indexPath) as! AACommonCell
selectedRingtone = soundFiles[indexPath.section].files[indexPath.row]
cell.style = .Checkmark
}
}
|
mit
|
69f00c0cbb9216f1cde10244a2d87d37
| 38.177515 | 188 | 0.606555 | 5.611017 | false | false | false | false |
erdikanik/EKMediaView
|
Example/EKMediaView/MediaListTableViewController.swift
|
1
|
2495
|
//
// MediaListTableViewController.swift
// EKMediaViewExample
//
// Created by Erdi Kanık on 31.01.2017.
// Copyright © 2017 ekmediaview. All rights reserved.
//
import UIKit
class MediaListTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
setTableViewProperties()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setTableViewProperties() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
tableView .register(UINib.init(nibName: "EKListTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "EKListTableViewCell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return MockManager().mediaViews().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:EKListTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EKListTableViewCell", for: indexPath) as! EKListTableViewCell
cell.titleLabel.text = "Index: \(indexPath.row)"
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell:EKListTableViewCell = cell as! EKListTableViewCell
if cell.mediaView.medias == nil {
let media = MockManager().mediaViews()[indexPath.row]
cell.layoutIfNeeded()
cell.setMedia(media: media)
}
cell.mediaView.muted = true
if let mediaView = cell.mediaView {
mediaView.stopAll = false
}
}
override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell:EKListTableViewCell = cell as! EKListTableViewCell
if let mediaView = cell.mediaView {
mediaView.stopAll = true
}
}
}
|
mit
|
058428acb1d1d7948fe0b33290e8cad9
| 29.777778 | 147 | 0.651424 | 5.54 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT
|
WeiBo/WeiBo/Classes/Tools(工具类)/NetworkTool(网络中间层)/NetworkTool+compose.swift
|
1
|
1365
|
//
// WB.swift
// WeiBo
//
// Created by chenWei on 2017/4/12.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
extension NetworkTool {
/// 发布文本微博的借口封装
///
/// - Parameters:
/// - status: 微博文字
/// - callBack: 完成回调
func updateStatus(status: String,imageData: Data?, callBack: @escaping (Any?)->()) {
if let imageData = imageData {
//上传接口
let url = "https://upload.api.weibo.com/2/statuses/upload.json"
let parameters = ["access_token": (WBUserAccount.shared.access_token)!, "status": status]
// 调用网络中间层的接口发布微博
self.upload(url: url, parameters: parameters, data: imageData, name: "pic", fileName: "abc.png", callBack: { (response) in
callBack(response)
})
}else {
let url = "https://api.weibo.com/2/statuses/update.json"
let parameters = ["access_token": (WBUserAccount.shared.access_token)!, "status": status]
// 调用网络中间层的接口发布微博
self.requeset(url: url, method: "POST", parameters: parameters, callBack: { (response) in
callBack(response)
})
}
}
}
|
mit
|
57729c550d112341011a0ae803329e24
| 28.209302 | 134 | 0.532643 | 4 | false | false | false | false |
mmrmmlrr/ExamMaster
|
ExamMaster/Exam Creation Flow/Subject Picker/ExamSubjectPickerModel.swift
|
1
|
1137
|
//
// ExamSubjectPickerModel.swift
// ExamMaster
//
// Created by aleksey on 28.02.16.
// Copyright © 2016 aleksey chernish. All rights reserved.
//
import Foundation
import ModelsTreeKit
typealias Subject = String
class ExamSubjectPickerModel: UnorderedList<String> {
let title = "Subject"
let progressSignal = Observable(false)
private weak var flowModel: ExamCreationFlow!
init(parent: ExamCreationFlow) {
super.init(parent: parent)
flowModel = parent
}
func cancelFlow() {
flowModel.childModelDidCancelFlow(self)
}
func fetchSubjects() {
progressSignal.sendNext(true)
let client: APIClient = session.services.getService()
client.fetchSubjects { [ weak self] subjects, error in
guard let _self = self else { return }
_self.progressSignal.sendNext(false)
guard error == nil else {
_self.raise(error!)
return
}
_self.performUpdates {
$0.insert(subjects!)
}
}
}
func selectSubject(subject: String) {
flowModel.child(self, didSelectSubject: subject)
}
}
|
mit
|
263ec56747c91d81c8c867c155fa0fec
| 19.303571 | 59 | 0.645246 | 4.145985 | false | false | false | false |
ObjectAlchemist/OOUIKit
|
Sources/_UIKitDelegate/UITableViewDelegate/ReorderingTableRows/UITableViewDelegateReorderPrinting.swift
|
1
|
1332
|
//
// UITableViewDelegateReorderPrinting.swift
// OOUIKit
//
// Created by Karsten Litsche on 04.11.17.
//
import UIKit
public final class UITableViewDelegateReorderPrinting: NSObject, UITableViewDelegate {
// MARK: - init
convenience override init() {
fatalError("Not supported!")
}
public init(_ decorated: UITableViewDelegate, filterKey: String = "") {
self.decorated = decorated
// add space if exist to separate following log
self.filterKey = filterKey.count == 0 ? "" : "\(filterKey) "
}
// MARK: - protocol: UITableViewDelegate
public func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
printUI("\(filterKey)table targetIndexPathForMoveFromRowAt source=(\(sourceIndexPath.section)-\(sourceIndexPath.row)) to=(\(proposedDestinationIndexPath.section)-\(proposedDestinationIndexPath.row)) called")
return decorated.tableView?(tableView, targetIndexPathForMoveFromRowAt: sourceIndexPath, toProposedIndexPath: proposedDestinationIndexPath) ?? proposedDestinationIndexPath
}
// MARK: - private
private let decorated: UITableViewDelegate
private let filterKey: String
}
|
mit
|
887e5fea6a4fd7c404396c4e775398c5
| 36 | 215 | 0.718468 | 5.893805 | false | false | false | false |
btanner/Eureka
|
Example/Example/Controllers/DisabledRowsExample.swift
|
4
|
1319
|
//
// DisabledRowsExample.swift
// Example
//
// Created by Mathias Claassen on 3/15/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Eureka
class DisabledRowsExample : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form = Section()
<<< SegmentedRow<String>("segments"){
$0.options = ["Enabled", "Disabled"]
$0.value = "Disabled"
}
<<< TextRow(){
$0.title = "choose enabled, disable above..."
$0.disabled = "$segments = 'Disabled'"
}
<<< SwitchRow("Disable Next Section?"){
$0.title = $0.tag
$0.disabled = "$segments = 'Disabled'"
}
+++ Section()
<<< TextRow() {
$0.title = "Gonna be disabled soon.."
$0.disabled = Eureka.Condition.function(["Disable Next Section?"], { (form) -> Bool in
let row: SwitchRow! = form.rowBy(tag: "Disable Next Section?")
return row.value ?? false
})
}
+++ Section()
<<< SegmentedRow<String>(){
$0.options = ["Always Disabled"]
$0.disabled = true
}
}
}
|
mit
|
7f92631a8ad5e5f6e4d46249809eb2e1
| 25.36 | 102 | 0.467375 | 4.758123 | false | false | false | false |
mobgeek/swift
|
Swift em 4 Semanas/App Lista (7.0)/ListaData Solução 1/Lista/ListaTableViewController.swift
|
1
|
3919
|
//
// ListaTableViewController.swift
// Lista
//
// Created by Fabio Santos on 11/3/14.
// Copyright (c) 2014 Fabio Santos. All rights reserved.
//
import UIKit
class ListaTableViewController: UITableViewController {
// MARK - Propriedades
var itens: [ItemLista] = []
lazy var dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
// Configure o estilo
dateFormatter.dateStyle = .ShortStyle
// Outros: NoStyle, ShortStyle, MediumStyle, FullStyle
// Eventualmente:
// dateFormatter.timeStyle = .ShortStyle
// Cool Stuff: Hoje, Amanhã, etc..
// dateFormatter.doesRelativeDateFormatting = true
// Alternativa: Há também a opção de criar formatos customizados...Para uma lista de especificadores consulte a documentação Data Formatting Guide: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
// dateFormatter.dateFormat = "'Criado em' dd/MM/yyyy 'às' HH:mm"
// dateFormatter.dateFormat = "EEE, MMM d"
// Estabeleça o Português como preferência. NSLocale
dateFormatter.locale = NSLocale(localeIdentifier:"pt_BR")
return dateFormatter
} ()
// MARK - Helper Methods
func carregarDadosIniciais() {
var item1 = ItemLista(nome: "Comprar Maças")
itens.append(item1)
var item2 = ItemLista(nome: "Estudar Swift")
itens.append(item2)
var item3 = ItemLista(nome: "Ligar para o Banco")
itens.append(item3)
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
carregarDadosIniciais()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return itens.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ListaPrototypeCell", forIndexPath: indexPath)as! UITableViewCell
// Configure the cell...
var itemDaLista = itens[indexPath.row]
cell.textLabel!.text = itemDaLista.nome
cell.accessoryType = itemDaLista.concluido ? UITableViewCellAccessoryType.Checkmark :UITableViewCellAccessoryType.None
cell.detailTextLabel?.text = dateFormatter.stringFromDate(itemDaLista.dataCriacao) // Passo 04
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
var itemTocado = itens[indexPath.row]
itemTocado.concluido = !itemTocado.concluido
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
// MARK: - Navigation
@IBAction func voltaParaLista(segue: UIStoryboardSegue!) {
var sourceVC = segue.sourceViewController as! AdicionarItemViewController
if let item = sourceVC.novoItemDaLista {
itens.append(item)
tableView.reloadData()
}
}
}
|
mit
|
f602fcf1c3a2e2fd5c7fccea9884ff6f
| 27.940741 | 311 | 0.62452 | 5.113874 | false | false | false | false |
efa85/WeatherApp
|
WeatherAppTests/Model/Location/CoreDataLocationStoreTests.swift
|
1
|
3309
|
//
// CoreDataLocationStoreTests.swift
// WeatherApp
//
// Created by Emilio Fernandez on 06/01/15.
// Copyright (c) 2015 Emilio Fernandez. All rights reserved.
//
import XCTest
import CoreData
import WeatherApp
class CoreDataLocationStoreTests: XCTestCase {
let modelName = "Locations.momd"
let storeName = "TestLocations.sqlite"
var sut: LocationStore!
var coreDataStack: CoreDataStack!
override func setUp() {
super.setUp()
coreDataStack = CoreDataStack.withModelName(modelName, storeType: .SQLite(storeName: storeName), substitutionSwiftModuleName:"WeatherAppTests")
deleteStore()
sut = CoreDataLocationStore(context: coreDataStack.mainQueueContext)
}
override func tearDown() {
deleteStore()
sut = nil
coreDataStack = nil
super.tearDown()
}
func test__initially_there_are_no_locations() {
XCTAssertEqual(sut.fetchLocations().count, 0)
}
func test__adding_a_location() {
// prepare
XCTAssertEqual(sut.fetchLocations().count, 0)
let name = "aName"
let latitude = "aLat"
let longitude = "aLong"
// test
sut.addLocationWithName(name, latitude: latitude, longitude: longitude)
// verify
let locations = sut.fetchLocations()
if locations.count == 1 {
let location = locations[0]
XCTAssertEqual(location.name, name)
XCTAssertEqual(location.latitude, latitude)
XCTAssertEqual(location.longitude, longitude)
}
else {
XCTFail()
}
}
func test__add_a_location_then_tear_down_the_stack_and_add_a_new_one() {
XCTAssertEqual(sut.fetchLocations().count, 0)
let name1 = "aName"
sut.addLocationWithName(name1, latitude: "aLat", longitude: "aLong")
XCTAssertEqual(sut.fetchLocations().count, 1)
coreDataStack = CoreDataStack.withModelName(modelName, storeType: .SQLite(storeName: storeName), substitutionSwiftModuleName:"WeatherAppTests")
sut = CoreDataLocationStore(context: coreDataStack.mainQueueContext)
XCTAssertEqual(sut.fetchLocations().count, 1)
let name2 = "otherName"
sut.addLocationWithName(name2, latitude: "aLat", longitude: "aLong")
XCTAssertEqual(sut.fetchLocations().count, 2)
let names = sut.fetchLocations().map() {
(location) -> String in
return location.name
}
XCTAssertTrue(contains(names, name1))
XCTAssertTrue(contains(names, name2))
}
func test__deleteLocation() {
XCTAssertEqual(sut.fetchLocations().count, 0)
sut.addLocationWithName("aName", latitude: "aLat", longitude: "aLong")
XCTAssertEqual(sut.fetchLocations().count, 1)
let location = sut.fetchLocations()[0]
sut.deleteLocation(location)
XCTAssertEqual(sut.fetchLocations().count, 0)
}
private func deleteStore() {
let storeUrl = coreDataStack.storeUrl!
NSFileManager.defaultManager().removeItemAtURL(storeUrl, error: nil)
}
}
|
apache-2.0
|
4694297bcac3b16d4c8c762f70b5fe37
| 28.810811 | 151 | 0.613176 | 4.733906 | false | true | false | false |
Djecksan/MobiTask
|
MobiTask/Controllers/RatesViewController/RatesViewController.swift
|
1
|
2174
|
//
// RatesViewController.swift
// MobiTask
//
// Created by Evgenyi Tyulenev on 01.08.15.
// Copyright (c) 2015 VoltMobi. All rights reserved.
//
import UIKit
protocol RatesDelegate:NSObjectProtocol {
func setRate(value:Float, currency:String)
}
private let cellIdentifier = "rateIdentifier"
class RatesViewController: UITableViewController {
weak var delegate:RatesDelegate?
var rates:[String:Float]? {
didSet
{
self.displayItems = rates?.keys.array
self.tableView.reloadData()
self.selectedCellWithDefaultCurrency()
}
}
var displayItems:[String]!
override func viewDidLoad() {
super.viewDidLoad()
}
private func selectedCellWithDefaultCurrency() {
for (index, item) in enumerate(self.displayItems) {
if item == DEFAULT_CURRENCY {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false)
}
}
}
}
// MARK: - Table view data source
extension RatesViewController:UITableViewDataSource {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rates?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RateCell
var item = self.displayItems[indexPath.row]
cell.title.text = "\(DEFAULT_BASE_CURRENCY) ➔ \(item)"
return cell
}
}
// MARK: - Table view delegate
extension RatesViewController:UITableViewDelegate {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var key = self.displayItems[indexPath.row]
if let value = self.rates?[key] {
self.delegate?.setRate(value, currency: key)
}
}
}
|
mit
|
b9a034703f6a36087e9c9c959b5fd15d
| 30.028571 | 118 | 0.664825 | 4.815965 | false | false | false | false |
pollarm/MondoKit
|
MondoKitTestApp/CurrencyFormatter.swift
|
1
|
4570
|
//
// CurrencyFormatter.swift
// MondoKit
//
// Created by Mike Pollard on 01/02/2016.
// Copyright © 2016 Mike Pollard. All rights reserved.
//
import Foundation
struct CurrencyFormatter {
let isoCode : String
let currencySymbol : String
let scale : Double
let formatter : NSNumberFormatter
init(isoCode : String) {
self.isoCode = isoCode
let locale = NSLocale.currentLocale()
currencySymbol = locale.displayNameForKey(NSLocaleCurrencySymbol, value: isoCode) ?? "?"
formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyAccountingStyle
formatter.currencySymbol = currencySymbol
scale = Double(CurrencyFormatter.currencyCodeToMinorUnit[isoCode] ?? 2)
}
func stringFromMinorUnitsValue(minorUnitValue: Int) -> String? {
return formatter.stringFromNumber(Double(minorUnitValue) / pow(10.0, scale))
}
static var currencyCodeToMinorUnit : [String:Int] = {
let fileLocation = NSBundle.mainBundle().pathForResource("iso4217", ofType: "csv")!
var error: NSErrorPointer = nil
let csv = CSV(contentsOfFile: fileLocation, error: error)!
var result = [String:Int]()
for row in csv.rows {
if let code = row["currencyCode"],
minorUnit = row["minorUnit"],
unitInt = Int(minorUnit) {
result[code] = unitInt
}
}
return result
}()
}
// https://github.com/naoty/SwiftCSV
// CSV.swift
// SwiftCSV
//
// Created by naoty on 2014/06/09.
// Copyright (c) 2014年 Naoto Kaneko. All rights reserved.
//
public class CSV {
public var headers: [String] = []
public var rows: [Dictionary<String, String>] = []
public var columns = Dictionary<String, [String]>()
var delimiter = NSCharacterSet(charactersInString: ",")
public init?(contentsOfFile file: String, delimiter: NSCharacterSet, encoding: UInt, error: NSErrorPointer) {
let csvString : String
do {
csvString = try String(contentsOfFile: file);
let csvStringToParse = csvString
self.delimiter = delimiter
let newline = NSCharacterSet.newlineCharacterSet()
var lines: [String] = []
csvStringToParse.stringByTrimmingCharactersInSet(newline).enumerateLines { line, stop in lines.append(line) }
self.headers = self.parseHeaders(fromLines: lines)
self.rows = self.parseRows(fromLines: lines)
self.columns = self.parseColumns(fromLines: lines)
}
catch {
csvString = ""
}
}
public convenience init?(contentsOfFile file: String, error: NSErrorPointer) {
let comma = NSCharacterSet(charactersInString: ",")
self.init(contentsOfFile: file, delimiter: comma, encoding: NSUTF8StringEncoding, error: error)
}
public convenience init?(contentsOfURL file: String, encoding: UInt, error: NSErrorPointer) {
let comma = NSCharacterSet(charactersInString: ",")
self.init(contentsOfFile: file, delimiter: comma, encoding: encoding, error: error)
}
func parseHeaders(fromLines lines: [String]) -> [String] {
return lines[0].componentsSeparatedByCharactersInSet(self.delimiter)
}
func parseRows(fromLines lines: [String]) -> [Dictionary<String, String>] {
var rows: [Dictionary<String, String>] = []
for (lineNumber, line) in lines.enumerate() {
if lineNumber == 0 {
continue
}
var row = Dictionary<String, String>()
let values = line.componentsSeparatedByCharactersInSet(self.delimiter)
for (index, header) in self.headers.enumerate() {
if index < values.count {
row[header] = values[index]
} else {
row[header] = ""
}
}
rows.append(row)
}
return rows
}
func parseColumns(fromLines lines: [String]) -> Dictionary<String, [String]> {
var columns = Dictionary<String, [String]>()
for header in self.headers {
let column = self.rows.map { row in row[header] != nil ? row[header]! : "" }
columns[header] = column
}
return columns
}
}
|
mit
|
bf8d8d7a15ea2c5894d1c15de95a5510
| 32.101449 | 121 | 0.589446 | 4.937297 | false | false | false | false |
digoreis/swift-proposal-analyzer
|
swift-proposal-analyzer.playground/Pages/SE-0089.xcplaygroundpage/Contents.swift
|
2
|
6843
|
/*:
# Renaming `String.init<T>(_: T)`
* Proposal: [SE-0089](0089-rename-string-reflection-init.md)
* Authors: [Austin Zheng](https://github.com/austinzheng), [Brent Royal-Gordon](https://github.com/brentdax)
* Review Manager: [Chris Lattner](http://github.com/lattner)
* Status: **Implemented (Swift 3)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-June/000190.html)
* Bug: [SR-1881](https://bugs.swift.org/browse/SR-1881)
* Previous Revisions: [1](https://github.com/apple/swift-evolution/blob/40aecf3647c19ae37730e39aa9e54b67fcc2be86/proposals/0089-rename-string-reflection-init.md)
## Introduction
Swift's `String` type ships with a large number of initializers that take one unlabeled argument. One of these initializers, defined as `init<T>(_: T)`, is used to create a string containing the textual representation of an object. It is very easy to write code which accidentally invokes this initializer, when one of the other synonymous initializers was desired. Such code will compile without warnings and can be very difficult to detect.
Discussion threads: [pre-proposal part 1](https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160502/001846.html), [pre-proposal part 2](https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160509/001867.html), [review thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160516/017881.html), [post-review thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160523/019018.html)
## Motivation
`String` ships with a number of initializers which take a single unlabeled argument. These include non-failable initializers which create a `String` out of a `Character`, `NSString`, `CharacterView`, or `UnicodeScalarView`, initializers which build a string out of a number, and failable initializers which take a `UTF8View` or a `UTF16View`.
There are at least two possible situations in which a user may write incorrect code which nevertheless compiles successfully:
* The user means to call one of the non-failable initializers besides the `init<T>(_: T)` initializer, but passes in an argument of incorrect type.
* The user means to call one of the failable initializers, but accidentally assigns the created object to a value of non-nullable type.
In both cases the compiler silently infers the use of the `init<T>(_: T)` initializer in lieu of the desired initializer. This may result in code which inadvertently utilizes the expensive reflection machinery and/or produces an unintentionally lossy representation of the value.
## Proposed solution
A proposed solution to this problem follows:
* The current reflection-based `String.init<T>(_: T)` initializer will be renamed to `String.init<T>(describing: T)`. This initializer will rarely be invoked directly by user code.
* A new protocol will be introduced: `LosslessStringConvertible`, which refines/narrows `CustomStringConvertible`. This protocol will be defined as follows:
```swift
protocol LosslessStringConvertible : CustomStringConvertible {
/// Instantiate an instance of the conforming type from a string representation.
init?(_ description: String)
}
```
Values of types that conform to `LosslessStringConvertible` are capable of being represented in a lossless, unambiguous manner as a string. For example, the integer value `1050` can be represented in its entirety as the string `"1050"`. The `description` property for such a type must be a value-preserving representation of the original value. As such, it should be possible to attempt to create an instance of a `LosslessStringConvertible` conforming type from a string representation.
A possible alternate name for this protocol is `ValuePreservingStringLiteral`. The core team may wish to choose this name instead, or another name that better describes the protocol's contract.
* A new `String` initializer will be introduced: `init<T: LosslessStringConvertible>(_ v: T) { self = v.description }`. This allows the `String(x)` syntax to continue to be used on all values of types that can be converted to a string in a value-preserving way.
* As a performance optimization, the implementation of the string literal interpolation syntax will be changed to prefer the unlabeled initializer when interpolating a type that is `LosslessStringConvertible` or that otherwise has an unlabeled `String` initializer, but use the `String.init<T>(describing: T)` initializer if not.
### Standard library types to conform
The following standard library types and protocols should be changed to conform to `LosslessStringConvertible`.
#### Protocols
* `FloatingPoint`: "FP types should be able to conform. There are algorithms that are guaranteed to turn IEEE floating point values into a decimal representation in a reversible way. I don’t think we care about NaN payloads, but an encoding could be created for them as well." (Chris Lattner)
* `Integer`
#### Types
* `Bool`: either "true" or "false", since these are their canonical representations.
* `Character`
* `UnicodeScalar`
* `String`
* `String.UTF8View`
* `String.UTF16View`
* `String.CharacterView`
* `String.UnicodeScalarView`
* `StaticString`
## Future directions
### Additional conformances to `LosslessStringLiteral`
Once [conditional conformance of generic types to protocols](https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#conditional-conformances-) is implemented, the additional protocols and types below are candidates for conformance to `LosslessStringLiteral`:
#### Protocols
* `RangeReplaceableCollection where Iterator.Element == Character`
* `RangeReplaceableCollection where Iterator.Element == UnicodeScalar`
* `SetAlgebra where Iterator.Element == Character`
* `SetAlgebra where Iterator.Element == UnicodeScalar`
#### Types
* `ClosedRange where Bound : LosslessStringConvertible`
* `CountableClosedRange where Bound : LosslessStringConvertible`
* `CountableRange where Bound : LosslessStringConvertible`
* `Range where Bound : LosslessStringConvertible`
## Impact on existing code
This API change may impact existing code.
Code which intends to invoke `init<T>(_: T)` will need to be modified so that the proper initializer is called. In addition, it is possible that this change may uncover instances of the erroneous behavior described previously.
## Alternatives considered
One alternative solution might be to make `LosslessStringConvertible` a separate protocol altogether from `CustomStringConvertible` and `CustomDebugStringConvertible`. Arguments for and against that approach can be found in this [earlier version of this proposal](https://github.com/austinzheng/swift-evolution/blob/27ba68c2fbb8978aac6634c02d8a572f4f5123eb/proposals/0089-rename-string-reflection-init.md).
----------
[Previous](@previous) | [Next](@next)
*/
|
mit
|
ab8e3c6543509e7df78f21830dd8728b
| 62.342593 | 488 | 0.785704 | 4.294413 | false | false | false | false |
Daij-Djan/DDUtils
|
swift/ddutils-ios/ui/DDSlidingImageView [ios + demo]/DDSlidingImageView/ViewController.swift
|
1
|
1387
|
//
// ViewController.swift
// DDSlidingImageView
//
// Created by Dominik Pich on 29/04/15.
// Copyright (c) 2015 Dominik Pich. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var slider1: DDSlidingImageView!
@IBOutlet var slider2: DDSlidingImageView!
@IBOutlet var slider3: DDSlidingImageView!
@IBOutlet var slider4: DDSlidingImageView!
override func viewDidLoad() {
super.viewDidLoad()
let delayTime1 = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime1) {
self.slider1.sliderValue = 0.7;
}
let delayTime2 = DispatchTime.now() + Double(Int64(1.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime2) {
self.slider2.sliderValue = 0.4;
}
let delayTime3 = DispatchTime.now() + Double(Int64(2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime3) {
self.slider3.sliderValue = 1;
}
let delayTime4 = DispatchTime.now() + Double(Int64(2.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime4) {
self.slider4.sliderValue = 0.6;
}
}
}
|
mit
|
fae059842795e70bb43c3e395ad239a7
| 32.02381 | 110 | 0.649603 | 3.659631 | false | false | false | false |
coinbase/coinbase-ios-sdk
|
Source/Resources/Addresses/Address.swift
|
1
|
2770
|
//
// Address.swift
// Coinbase
//
// Copyright © 2018 Coinbase, Inc. All rights reserved.
//
import Foundation
/// Represents a bitcoin, bitcoin cash, litecoin or ethereum address for an account.
/// Account can have unlimited amount of addresses and they should be used only once.
///
open class Address: Decodable {
/// Address ID.
public let id: String
/// Bitcoin, Bitcoin Cash, Litecoin or Ethereum address.
public let address: String?
/// User defined label for the address.
public let name: String?
/// Name of blockchain.
public let network: String?
/// Resource creation date.
public let createdAt: Date?
/// Resource update date.
public let updatedAt: Date?
/// Resource type. Constant: **"address"**.
public let resource: String
/// Path for the location under `api.coinbase.com`.
public let resourcePath: String
/// Crypto currency URI scheme.
public let uriScheme: String?
/// Warning title.
public let warningTitle: String?
/// Warning details.
public let warningDetails: String?
/// Legacy address.
public let legacyAddress: String?
/// Callback URL.
public let callbackURL: String?
/// Address info.
public let addressInfo: AddressInfo?
private enum CodingKeys: String, CodingKey {
case id, address, name, network, createdAt, updatedAt, resource, resourcePath,
uriScheme, warningTitle, warningDetails, legacyAddress, callbackURL = "callbackUrl",
addressInfo
}
public required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(String.self, forKey: .id)
address = try values.decodeIfPresent(String.self, forKey: .address)
name = try values.decodeIfPresent(String.self, forKey: .name)
network = try values.decodeIfPresent(String.self, forKey: .network)
createdAt = try values.decodeIfPresent(Date.self, forKey: .createdAt)
updatedAt = try values.decodeIfPresent(Date.self, forKey: .updatedAt)
resource = try values.decode(String.self, forKey: .resource)
resourcePath = try values.decode(String.self, forKey: .resourcePath)
uriScheme = try values.decodeIfPresent(String.self, forKey: .uriScheme)
warningTitle = try values.decodeIfPresent(String.self, forKey: .warningTitle)
warningDetails = try values.decodeIfPresent(String.self, forKey: .warningDetails)
legacyAddress = try values.decodeIfPresent(String.self, forKey: .legacyAddress)
callbackURL = try values.decodeIfPresent(String.self, forKey: .callbackURL)
addressInfo = try values.decodeIfPresent(AddressInfo.self, forKey: .addressInfo)
}
}
|
apache-2.0
|
a6f2b33ce8e8768975074a2f046e32d5
| 39.720588 | 92 | 0.692308 | 4.487844 | false | false | false | false |
AnRanScheme/MagiRefresh
|
MagiRefresh/Classes/MagiRefreshCore/MagiRefreshFooterConrol.swift
|
3
|
7282
|
//
// MagiRefreshFooterConrol.swift
// MagiRefresh
//
// Created by anran on 2018/9/3.
// Copyright © 2018年 anran. All rights reserved.
//
import UIKit
public class MagiRefreshFooterConrol: MagiRefreshBaseConrol {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
magi_top = scrollView?.contentHeight ?? 0
}
override public func setScrollViewToRefreshLocation() {
super.setScrollViewToRefreshLocation()
DispatchQueue.main.async {
if let realContentInset = self.scrollView?.realContentInset {
self.presetContentInsets = realContentInset
}
UIView.setAnimate(animations: {
self.setAnimated()
}, completion: { (isFinished) in
self.setCompletion()
})
}
}
override public func setScrollViewToOriginalLocation() {
super.setScrollViewToOriginalLocation()
UIView.setAnimate(animations: {
self.isAnimating = true
self.scrollView?.insetBottom = self.presetContentInsets.bottom
}, completion: { (isFinished) in
self.isAnimating = false
self.isTriggeredRefreshByUser = false
self.refreshStatus = .none
})
}
override public func privateContentOffsetOfScrollViewDidChange(_ contentOffset: CGPoint) {
super.privateContentOffsetOfScrollViewDidChange(contentOffset)
if refreshStatus != .refreshing {
if isTriggeredRefreshByUser {return}
presetContentInsets = scrollView?.realContentInset ?? UIEdgeInsets.zero
var originY: CGFloat = 0.0
var maxY: CGFloat = 0.0
var minY: CGFloat = 0.0
var contentOffsetYInBottom: CGFloat = 0.0
if (scrollView?.contentHeight ?? 0.0) + presetContentInsets.top <= (scrollView?.magi_height ?? 0.0) {
maxY = stretchOffsetYAxisThreshold*magi_height
minY = 0
originY = contentOffset.y+presetContentInsets.top
if refreshStatus == .scrolling {
let progress = abs(originY) / magi_height
if progress <= stretchOffsetYAxisThreshold {
self.progress = progress
}
}
} else {
maxY = MagiRefreshFooterConrol.OffsetOfTriggeringFootRefreshControlToRefresh(self)
minY = MagiRefreshFooterConrol.OffsetOfFootRefreshControlToRestore(self)
originY = contentOffset.y
contentOffsetYInBottom = (scrollView?.contentHeight ?? 0.0) - (scrollView?.magi_height ?? 0.0)
/////////////////////////
///uncontinuous callback
/////////////////////////
let uncontinuousOpt: CGFloat = 50.0
if originY < minY - uncontinuousOpt {return}
if refreshStatus == .scrolling {
let progress = abs((originY - contentOffsetYInBottom - presetContentInsets.bottom))/magi_height
if progress <= stretchOffsetYAxisThreshold {
self.progress = progress
}
}
if isAutoRefreshOnFoot {
if (scrollView?.isDragging ?? false) &&
originY > MagiRefreshFooterConrol.OffsetOfTriggeringFootRefreshControlToAutoRefresh(self) &&
!isAnimating &&
refreshStatus == .none &&
!isShouldNoLongerRefresh {
beginRefreshing()
}
return
}
}
if !(scrollView?.isDragging ?? false)
&& refreshStatus == .ready {
isTriggeredRefreshByUser = false
refreshStatus = .refreshing
setScrollViewToRefreshLocation()
}
else if originY <= minY && !isAnimating {
refreshStatus = .none
}
else if (scrollView?.isDragging ?? false)
&& originY >= minY
&& originY <= maxY
&& refreshStatus != .scrolling {
refreshStatus = .scrolling
}
else if (scrollView?.isDragging ?? false)
&& originY > maxY
&& !isAnimating
&& refreshStatus != .ready
&& !isShouldNoLongerRefresh {
refreshStatus = .ready
}
}
}
}
extension MagiRefreshFooterConrol {
/// 静态发发内部是获取不到self的对象的
static func RefreshingPoint(_ control: MagiRefreshFooterConrol)->CGPoint {
guard let sc = control.scrollView else { return CGPoint.zero }
return CGPoint(x: sc.magi_left,
y: MagiRefreshFooterConrol.OffsetOfTriggeringFootRefreshControlToRefresh(control))
}
static func OffsetOfTriggeringFootRefreshControlToRefresh(_ control: MagiRefreshBaseConrol)->CGFloat {
guard let sc = control.scrollView else { return 0 }
let y = sc.contentHeight - sc.magi_height
+ control.stretchOffsetYAxisThreshold*control.magi_height
+ control.presetContentInsets.bottom
return y
}
static func OffsetOfTriggeringFootRefreshControlToAutoRefresh(_ control: MagiRefreshBaseConrol)->CGFloat {
guard let sc = control.scrollView else { return 0 }
let y = sc.contentHeight - sc.magi_height + control.presetContentInsets.bottom
return y
}
static func OffsetOfFootRefreshControlToRestore(_ control: MagiRefreshBaseConrol)->CGFloat {
guard let sc = control.scrollView else { return 0 }
let y = sc.contentHeight - sc.magi_height + control.presetContentInsets.bottom
return y
}
fileprivate func setAnimated() {
if isTriggeredRefreshByUser {
refreshStatus = .scrolling
if (scrollView?.contentHeight ?? 0.0) > (scrollView?.magi_height ?? 0.0) &&
(scrollView?.offsetY ?? 0.0) >= MagiRefreshFooterConrol.OffsetOfTriggeringFootRefreshControlToRefresh(self) {
scrollView?.setContentOffset(MagiRefreshFooterConrol.RefreshingPoint(self),
animated: true)
magiDidScrollWithProgress(progress: 0.5,
max: stretchOffsetYAxisThreshold)
}
}
scrollView?.insetBottom = presetContentInsets.bottom+magi_height
}
fileprivate func setCompletion() {
if isTriggeredRefreshByUser {
refreshStatus = .ready
refreshStatus = .refreshing
magiDidScrollWithProgress(progress: 1.0,
max: stretchOffsetYAxisThreshold)
}
refreshClosure?()
}
}
|
mit
|
5ff5302f3a6e3afc91e5836985198bd2
| 38.183784 | 125 | 0.562422 | 5.49583 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
src/AsciiArtPlayer/Pods/PromiseKit/Sources/Promise.swift
|
5
|
24878
|
import class Dispatch.DispatchQueue
import class Foundation.NSError
import func Foundation.NSLog
/**
A *promise* represents the future value of a (usually) asynchronous task.
To obtain the value of a promise we call `then`.
Promises are chainable: `then` returns a promise, you can call `then` on
that promise, which returns a promise, you can call `then` on that
promise, et cetera.
Promises start in a pending state and *resolve* with a value to become
*fulfilled* or an `Error` to become rejected.
- SeeAlso: [PromiseKit `then` Guide](http://promisekit.org/docs/)
*/
open class Promise<T> {
let state: State<T>
/**
Create a new, pending promise.
func fetchAvatar(user: String) -> Promise<UIImage> {
return Promise { fulfill, reject in
MyWebHelper.GET("\(user)/avatar") { data, err in
guard let data = data else { return reject(err) }
guard let img = UIImage(data: data) else { return reject(MyError.InvalidImage) }
guard let img.size.width > 0 else { return reject(MyError.ImageTooSmall) }
fulfill(img)
}
}
}
- Parameter resolvers: The provided closure is called immediately on the active thread; commence your asynchronous task, calling either fulfill or reject when it completes.
- Parameter fulfill: Fulfills this promise with the provided value.
- Parameter reject: Rejects this promise with the provided error.
- Returns: A new promise.
- Note: If you are wrapping a delegate-based system, we recommend
to use instead: `Promise.pending()`
- SeeAlso: http://promisekit.org/docs/sealing-promises/
- SeeAlso: http://promisekit.org/docs/cookbook/wrapping-delegation/
- SeeAlso: pending()
*/
required public init(resolvers: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void) {
var resolve: ((Resolution<T>) -> Void)!
do {
state = UnsealedState(resolver: &resolve)
try resolvers({ resolve(.fulfilled($0)) }, { error in
#if !PMKDisableWarnings
if self.isPending {
resolve(Resolution(error))
} else {
NSLog("PromiseKit: warning: reject called on already rejected Promise: \(error)")
}
#else
resolve(Resolution(error))
#endif
})
} catch {
resolve(Resolution(error))
}
}
/**
Create an already fulfilled promise.
To create a resolved `Void` promise, do: `Promise(value: ())`
*/
required public init(value: T) {
state = SealedState(resolution: .fulfilled(value))
}
/**
Create an already rejected promise.
*/
required public init(error: Error) {
state = SealedState(resolution: Resolution(error))
}
/**
Careful with this, it is imperative that sealant can only be called once
or you will end up with spurious unhandled-errors due to possible double
rejections and thus immediately deallocated ErrorConsumptionTokens.
*/
init(sealant: (@escaping (Resolution<T>) -> Void) -> Void) {
var resolve: ((Resolution<T>) -> Void)!
state = UnsealedState(resolver: &resolve)
sealant(resolve)
}
/**
A `typealias` for the return values of `pending()`. Simplifies declaration of properties that reference the values' containing tuple when this is necessary. For example, when working with multiple `pendingPromise(value: ())`s within the same scope, or when the promise initialization must occur outside of the caller's initialization.
class Foo: BarDelegate {
var task: Promise<Int>.PendingTuple?
}
- SeeAlso: pending()
*/
public typealias PendingTuple = (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void)
/**
Making promises that wrap asynchronous delegation systems or other larger asynchronous systems without a simple completion handler is easier with pending.
class Foo: BarDelegate {
let (promise, fulfill, reject) = Promise<Int>.pending()
func barDidFinishWithResult(result: Int) {
fulfill(result)
}
func barDidError(error: NSError) {
reject(error)
}
}
- Returns: A tuple consisting of:
1) A promise
2) A function that fulfills that promise
3) A function that rejects that promise
*/
public final class func pending() -> PendingTuple {
var fulfill: ((T) -> Void)!
var reject: ((Error) -> Void)!
let promise = self.init { fulfill = $0; reject = $1 }
return (promise, fulfill, reject)
}
/**
The provided closure is executed when this promise is resolved.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The closure that is executed when this Promise is fulfilled.
- Returns: A new promise that is resolved with the value returned from the provided closure. For example:
URLSession.GET(url).then { data -> Int in
//…
return data.length
}.then { length in
//…
}
*/
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U> {
return Promise<U> { resolve in
state.then(on: q, else: resolve) { value in
resolve(.fulfilled(try body(value)))
}
}
}
/**
The provided closure executes when this promise resolves.
This variant of `then` allows chaining promises, the promise returned by the provided closure is resolved before the promise returned by this closure resolves.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise fulfills.
- Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example:
URLSession.GET(url1).then { data in
return CLLocationManager.promise()
}.then { location in
//…
}
*/
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U> {
var resolve: ((Resolution<U>) -> Void)!
let rv = Promise<U>{ resolve = $0 }
state.then(on: q, else: resolve) { value in
let promise = try body(value)
guard promise !== rv else { throw PMKError.returnedSelf }
promise.state.pipe(resolve)
}
return rv
}
/**
The provided closure executes when this promise resolves.
This variant of `then` allows returning a tuple of promises within provided closure. All of the returned
promises needs be fulfilled for this promise to be marked as resolved.
- Note: At maximum 5 promises may be returned in a tuple
- Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error.
- Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise fulfills.
- Returns: A new promise that resolves when all promises returned from the provided closure resolve. For example:
loginPromise.then { _ -> (Promise<Data>, Promise<UIImage>)
return (URLSession.GET(userUrl), URLSession.dataTask(with: avatarUrl).asImage())
}.then { userData, avatarImage in
//…
}
*/
public func then<U, V>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>)) -> Promise<(U, V)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1) }
}
/// This variant of `then` allows returning a tuple of promises within provided closure.
public func then<U, V, X>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>)) -> Promise<(U, V, X)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2) }
}
/// This variant of `then` allows returning a tuple of promises within provided closure.
public func then<U, V, X, Y>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>, Promise<Y>)) -> Promise<(U, V, X, Y)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) }
}
/// This variant of `then` allows returning a tuple of promises within provided closure.
public func then<U, V, X, Y, Z>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>, Promise<Y>, Promise<Z>)) -> Promise<(U, V, X, Y, Z)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) }
}
/// utility function to serve `then` implementations with `body` returning tuple of promises
private func then<U, V>(on q: DispatchQueue, execute body: @escaping (T) throws -> V, when: @escaping (V) -> Promise<U>) -> Promise<U> {
return Promise<U> { resolve in
state.then(on: q, else: resolve) { value in
let promise = try body(value)
// since when(promise) switches to `zalgo`, we have to pipe back to `q`
when(promise).state.pipe(on: q, to: resolve)
}
}
}
/**
The provided closure executes when this promise rejects.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- Returns: `self`
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
- Important: The promise that is returned is `self`. `catch` cannot affect the chain, in PromiseKit 3 no promise was returned to strongly imply this, however for PromiseKit 4 we started returning a promise so that you can `always` after a catch or return from a function that has an error handler.
*/
@discardableResult
public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) -> Promise {
state.catch(on: q, policy: policy, else: { _ in }, execute: body)
return self
}
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
CLLocationManager.promise().recover { error in
guard error == CLError.unknownLocation else { throw error }
return CLLocation.Chicago
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise) -> Promise {
var resolve: ((Resolution<T>) -> Void)!
let rv = Promise{ resolve = $0 }
state.catch(on: q, policy: policy, else: resolve) { error in
let promise = try body(error)
guard promise !== rv else { throw PMKError.returnedSelf }
promise.state.pipe(resolve)
}
return rv
}
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
CLLocationManager.promise().recover { error in
guard error == CLError.unknownLocation else { throw error }
return CLLocation.Chicago
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> T) -> Promise {
return Promise { resolve in
state.catch(on: q, policy: policy, else: resolve) { error in
resolve(.fulfilled(try body(error)))
}
}
}
/**
The provided closure executes when this promise resolves.
firstly {
UIApplication.shared.networkActivityIndicatorVisible = true
}.then {
//…
}.always {
UIApplication.shared.networkActivityIndicatorVisible = false
}.catch {
//…
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
@discardableResult
public func always(on q: DispatchQueue = .default, execute body: @escaping () -> Void) -> Promise {
state.always(on: q) { resolution in
body()
}
return self
}
/**
Allows you to “tap” into a promise chain and inspect its result.
The function you provide cannot mutate the chain.
URLSession.GET(/*…*/).tap { result in
print(result)
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
@discardableResult
public func tap(on q: DispatchQueue = .default, execute body: @escaping (Result<T>) -> Void) -> Promise {
state.always(on: q) { resolution in
body(Result(resolution))
}
return self
}
/**
Void promises are less prone to generics-of-doom scenarios.
- SeeAlso: when.swift contains enlightening examples of using `Promise<Void>` to simplify your code.
*/
public func asVoid() -> Promise<Void> {
return then(on: zalgo) { _ in return }
}
//MARK: deprecations
@available(*, unavailable, renamed: "always()")
public func finally(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() }
@available(*, unavailable, renamed: "always()")
public func ensure(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() }
@available(*, unavailable, renamed: "pending()")
public class func `defer`() -> PendingTuple { fatalError() }
@available(*, unavailable, renamed: "pending()")
public class func `pendingPromise`() -> PendingTuple { fatalError() }
@available(*, unavailable, message: "deprecated: use then(on: .global())")
public func thenInBackground<U>(execute body: (T) throws -> U) -> Promise<U> { fatalError() }
@available(*, unavailable, renamed: "catch")
public func onError(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func errorOnQueue(_ on: DispatchQueue, policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func error(policy: CatchPolicy, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func report(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "init(value:)")
public init(_ value: T) { fatalError() }
//MARK: disallow `Promise<Error>`
@available(*, unavailable, message: "cannot instantiate Promise<Error>")
public init<T: Error>(resolvers: (_ fulfill: (T) -> Void, _ reject: (Error) -> Void) throws -> Void) { fatalError() }
@available(*, unavailable, message: "cannot instantiate Promise<Error>")
public class func pending<T: Error>() -> (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void) { fatalError() }
//MARK: disallow returning `Error`
@available (*, unavailable, message: "instead of returning the error; throw")
public func then<U: Error>(on: DispatchQueue = .default, execute body: (T) throws -> U) -> Promise<U> { fatalError() }
@available (*, unavailable, message: "instead of returning the error; throw")
public func recover<T: Error>(on: DispatchQueue = .default, execute body: (Error) throws -> T) -> Promise { fatalError() }
//MARK: disallow returning `Promise?`
@available(*, unavailable, message: "unwrap the promise")
public func then<U>(on: DispatchQueue = .default, execute body: (T) throws -> Promise<U>?) -> Promise<U> { fatalError() }
@available(*, unavailable, message: "unwrap the promise")
public func recover(on: DispatchQueue = .default, execute body: (Error) throws -> Promise?) -> Promise { fatalError() }
}
extension Promise: CustomStringConvertible {
public var description: String {
return "Promise: \(state)"
}
}
/**
Judicious use of `firstly` *may* make chains more readable.
Compare:
URLSession.GET(url1).then {
URLSession.GET(url2)
}.then {
URLSession.GET(url3)
}
With:
firstly {
URLSession.GET(url1)
}.then {
URLSession.GET(url2)
}.then {
URLSession.GET(url3)
}
*/
public func firstly<T>(execute body: () throws -> Promise<T>) -> Promise<T> {
return firstly(execute: body) { $0 }
}
/**
Judicious use of `firstly` *may* make chains more readable.
Firstly allows to return tuple of promises
Compare:
when(fulfilled: URLSession.GET(url1), URLSession.GET(url2)).then {
URLSession.GET(url3)
}.then {
URLSession.GET(url4)
}
With:
firstly {
(URLSession.GET(url1), URLSession.GET(url2))
}.then { _, _ in
URLSession.GET(url2)
}.then {
URLSession.GET(url3)
}
- Note: At maximum 5 promises may be returned in a tuple
- Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error.
*/
public func firstly<T, U>(execute body: () throws -> (Promise<T>, Promise<U>)) -> Promise<(T, U)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1) }
}
/// Firstly allows to return tuple of promises
public func firstly<T, U, V>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>)) -> Promise<(T, U, V)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2) }
}
/// Firstly allows to return tuple of promises
public func firstly<T, U, V, W>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>, Promise<W>)) -> Promise<(T, U, V, W)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) }
}
/// Firstly allows to return tuple of promises
public func firstly<T, U, V, W, X>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>, Promise<W>, Promise<X>)) -> Promise<(T, U, V, W, X)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) }
}
/// utility function to serve `firstly` implementations with `body` returning tuple of promises
fileprivate func firstly<U, V>(execute body: () throws -> V, when: (V) -> Promise<U>) -> Promise<U> {
do {
return when(try body())
} catch {
return Promise(error: error)
}
}
@available(*, unavailable, message: "instead of returning the error; throw")
public func firstly<T: Error>(execute body: () throws -> T) -> Promise<T> { fatalError() }
@available(*, unavailable, message: "use DispatchQueue.promise")
public func firstly<T>(on: DispatchQueue, execute body: () throws -> Promise<T>) -> Promise<T> { fatalError() }
/**
- SeeAlso: `DispatchQueue.promise(group:qos:flags:execute:)`
*/
@available(*, deprecated: 4.0, renamed: "DispatchQueue.promise")
public func dispatch_promise<T>(_ on: DispatchQueue, _ body: @escaping () throws -> T) -> Promise<T> {
return Promise(value: ()).then(on: on, execute: body)
}
/**
The underlying resolved state of a promise.
- Remark: Same as `Resolution<T>` but without the associated `ErrorConsumptionToken`.
*/
public enum Result<T> {
/// Fulfillment
case fulfilled(T)
/// Rejection
case rejected(Error)
init(_ resolution: Resolution<T>) {
switch resolution {
case .fulfilled(let value):
self = .fulfilled(value)
case .rejected(let error, _):
self = .rejected(error)
}
}
/**
- Returns: `true` if the result is `fulfilled` or `false` if it is `rejected`.
*/
public var boolValue: Bool {
switch self {
case .fulfilled:
return true
case .rejected:
return false
}
}
}
/**
An object produced by `Promise.joint()`, along with a promise to which it is bound.
Joining with a promise via `Promise.join(_:)` will pipe the resolution of that promise to
the joint's bound promise.
- SeeAlso: `Promise.joint()`
- SeeAlso: `Promise.join(_:)`
*/
public class PMKJoint<T> {
fileprivate var resolve: ((Resolution<T>) -> Void)!
}
extension Promise {
/**
Provides a safe way to instantiate a `Promise` and resolve it later via its joint and another
promise.
class Engine {
static func make() -> Promise<Engine> {
let (enginePromise, joint) = Promise<Engine>.joint()
let cylinder: Cylinder = Cylinder(explodeAction: {
// We *could* use an IUO, but there are no guarantees about when
// this callback will be called. Having an actual promise is safe.
enginePromise.then { engine in
engine.checkOilPressure()
}
})
firstly {
Ignition.default.start()
}.then { plugs in
Engine(cylinders: [cylinder], sparkPlugs: plugs)
}.join(joint)
return enginePromise
}
}
- Returns: A new promise and its joint.
- SeeAlso: `Promise.join(_:)`
*/
public final class func joint() -> (Promise<T>, PMKJoint<T>) {
let pipe = PMKJoint<T>()
let promise = Promise(sealant: { pipe.resolve = $0 })
return (promise, pipe)
}
/**
Pipes the value of this promise to the promise created with the joint.
- Parameter joint: The joint on which to join.
- SeeAlso: `Promise.joint()`
*/
public func join(_ joint: PMKJoint<T>) {
state.pipe(joint.resolve)
}
}
extension Promise where T: Collection {
/**
Transforms a `Promise` where `T` is a `Collection` into a `Promise<[U]>`
URLSession.shared.dataTask(url: /*…*/).asArray().map { result in
return download(result)
}.then { images in
// images is `[UIImage]`
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter transform: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
public func map<U>(on: DispatchQueue = .default, transform: @escaping (T.Iterator.Element) throws -> Promise<U>) -> Promise<[U]> {
return Promise<[U]> { resolve in
return state.then(on: zalgo, else: resolve) { tt in
when(fulfilled: try tt.map(transform)).state.pipe(resolve)
}
}
}
}
|
mit
|
fa10acb122af8e6f28d4d4a937b3617d
| 38.573248 | 339 | 0.624618 | 4.307106 | false | false | false | false |
andrashatvani/bcHealth
|
bcHealth/Parser.swift
|
1
|
3183
|
import Foundation
import Kanna
import SwiftyBeaver
class Parser {
public static let dateFormatter:DateFormatter = {
let dateFormatter:DateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy hh:mm:ss a"
return dateFormatter
}()
func parse(trackListHtml:String) throws -> ([Track], [Track]) {
let console = ConsoleDestination()
let log = SwiftyBeaver.self
log.addDestination(console)
var completeTracks:[Track] = []
var incompleteTracks:[Track] = []
guard let doc:HTMLDocument = HTML(html: trackListHtml, encoding: .utf8) else {
throw ParseError.emptyDocument
}
let tracklist:XPathObject = doc.css(".tracklist > li[ng-repeat]")
for element:XMLElement in tracklist {
var track:Track = Track()
parseMetrics(element, &track)
parseCity(element, &track)
parseDate(element, &track)
if (track.isComplete()) {
completeTracks.append(track)
log.info("Track: \(track)")
} else {
incompleteTracks.append(track)
log.warning("Track: \(track)")
}
}
return (completeTracks, incompleteTracks)
}
fileprivate func parseCity(_ element: XMLElement, _ track: inout Track) {
if let city:String = element.at_css("h3")?.text {
track.city = city
.replacingOccurrences(of: "track in", with: "", options: .caseInsensitive)
.trimmingCharacters(in: .whitespacesAndNewlines)
} else {
print("Couldn't find city")
}
}
fileprivate func parseMetrics(_ element: XMLElement, _ track: inout Track) {
for entry:XMLElement in element.css("ul > li") {
if let label:String = entry.at_css("label")?.text {
switch label {
case "Distance":
(track.distance, track.distanceUnit) = parseProperty(entry: entry)
case "Time":
(track.time, track.timeUnit) = parseProperty(entry: entry)
case "Speed":
(track.averageSpeed, track.speedUnit) = parseProperty(entry: entry)
default:
print("Unknown element ", label )
}
} else {
print("Couldn't find labels")
}
}
}
fileprivate func parseDate(_ element: XMLElement, _ track: inout Track) {
if let rawDate:String = element .at_css("p")?.text {
track.date = Parser.dateFormatter.date(from: rawDate)
} else {
print("Couldn't find date")
}
}
fileprivate func parseProperty(entry:XMLElement) -> (Decimal?, String?) {
var decimalValue:Decimal?
var stringValue:String?
if let rawText = entry.at_xpath("text()")?.text {
decimalValue = 0.0
Scanner(string: rawText).scanDecimal(&decimalValue!)
stringValue = entry.at_css("span")?.text
}
return (decimalValue, stringValue)
}
}
|
apache-2.0
|
9206a4ba11904572f7ae3ba78a3c7f8d
| 35.586207 | 90 | 0.553252 | 4.808157 | false | false | false | false |
maxprig/APDynamicHeaderTableViewController
|
APDynamicHeaderTableViewController/APDynamicHeaderTableViewController.swift
|
2
|
7647
|
//
// APDynamicHeaderTableViewController.swift
//
// Created by Aaron Pang on 2015-04-27.
// Copyright (c) 2015 Aaron Pang. All rights reserved.
//
import Foundation
import UIKit
class APDynamicHeaderTableViewController : UIViewController {
let headerView = APDynamicHeaderView ()
let tableView = UITableView (frame: CGRectZero, style: .Plain)
private var headerViewHeightConstraint = NSLayoutConstraint()
private var headerBeganCollapsed = false
private var collapsedHeaderViewHeight : CGFloat = UIApplication.sharedApplication().statusBarFrame.height
private var expandedHeaderViewHeight : CGFloat = 75
private var headerExpandDelay : CGFloat = 100
private var tableViewScrollOffsetBeginDraggingY : CGFloat = 0.0
/**
Designated Initializer. Initializes table view controller and header view.
:param: collapsedHeaderViewHeight Height of header view when collapsed.
:param: expandedHeaderViewHeight Height of header view when expanded.
:param: headerExpandDelay Delay for header view to begin expanding when user is scrolling up.
*/
init(collapsedHeaderViewHeight : CGFloat, expandedHeaderViewHeight : CGFloat, headerExpandDelay :CGFloat) {
self.collapsedHeaderViewHeight = collapsedHeaderViewHeight
self.expandedHeaderViewHeight = expandedHeaderViewHeight
self.headerExpandDelay = headerExpandDelay
super.init(nibName: nil, bundle: nil)
tableView.dataSource = self
tableView.delegate = self
}
/**
Initializes table view controller and header view with default values.
*/
init () {
super.init(nibName: nil, bundle: nil)
tableView.dataSource = self
tableView.delegate = self
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
headerView.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(headerView)
view.addSubview(tableView)
tableView.backgroundColor = UIColor.whiteColor()
let views = ["headerView" : headerView, "tableView" : tableView]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[headerView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[headerView][tableView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
headerViewHeightConstraint = NSLayoutConstraint(item: headerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: expandedHeaderViewHeight)
view.addConstraint(headerViewHeightConstraint)
}
func animateHeaderViewHeight () -> Void {
// Animate the header view to collapsed or expanded if it is dragged only partially
var headerViewHeightDestinationConstant : CGFloat = 0.0
if (headerViewHeightConstraint.constant < ((expandedHeaderViewHeight - collapsedHeaderViewHeight) / 2.0 + collapsedHeaderViewHeight)) {
headerViewHeightDestinationConstant = collapsedHeaderViewHeight
} else {
headerViewHeightDestinationConstant = expandedHeaderViewHeight
}
if (headerViewHeightConstraint.constant != expandedHeaderViewHeight && headerViewHeightConstraint.constant != collapsedHeaderViewHeight) {
let animationDuration = 0.25
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
self.headerViewHeightConstraint.constant = headerViewHeightDestinationConstant
let progress = (self.headerViewHeightConstraint.constant - self.collapsedHeaderViewHeight) / (self.expandedHeaderViewHeight - self.collapsedHeaderViewHeight)
self.headerView.expandToProgress(progress)
self.view.layoutIfNeeded()
})
}
}
}
extension APDynamicHeaderTableViewController : UITableViewDelegate {
}
extension APDynamicHeaderTableViewController : UIScrollViewDelegate {
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
// Clamp the beginning point to 0 and the max content offset to prevent unintentional resizing when dragging during rubber banding
tableViewScrollOffsetBeginDraggingY = min(max(scrollView.contentOffset.y, 0), scrollView.contentSize.height - scrollView.frame.size.height)
// Keep track of whether or not the header was collapsed to determine if we can add the delay of expansion
headerBeganCollapsed = (headerViewHeightConstraint.constant == collapsedHeaderViewHeight)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// Do nothing if the table view is not scrollable
if tableView.contentSize.height < CGRectGetHeight(tableView.bounds) {
return
}
var contentOffsetY = tableView.contentOffset.y - tableViewScrollOffsetBeginDraggingY
// Add a delay to expanding the header only if the user began scrolling below the allotted amount of space to actually expand the header with no delay (e.g. If it takes 30 pixels to scroll up the scrollview to expand the header then don't add the delay of the user started scrolling at 10 pixels)
if tableViewScrollOffsetBeginDraggingY > ((expandedHeaderViewHeight - collapsedHeaderViewHeight) + headerExpandDelay) && contentOffsetY < 0 && headerBeganCollapsed {
contentOffsetY = contentOffsetY + headerExpandDelay
}
// Calculate how much the header height will change so we can readjust the table view's content offset so it doesn't scroll while we change the height of the header
let changeInHeaderViewHeight = headerViewHeightConstraint.constant - min(max(headerViewHeightConstraint.constant - contentOffsetY, collapsedHeaderViewHeight), expandedHeaderViewHeight)
headerViewHeightConstraint.constant = min(max(headerViewHeightConstraint.constant - contentOffsetY, collapsedHeaderViewHeight), expandedHeaderViewHeight)
let progress = (headerViewHeightConstraint.constant - collapsedHeaderViewHeight) / (expandedHeaderViewHeight - collapsedHeaderViewHeight)
headerView.expandToProgress(progress)
// When the header view height is changing, freeze the content in the table view
if headerViewHeightConstraint.constant != collapsedHeaderViewHeight && headerViewHeightConstraint.constant != expandedHeaderViewHeight {
tableView.contentOffset = CGPointMake(0, tableView.contentOffset.y - changeInHeaderViewHeight)
}
}
// Animate the header view when the user ends dragging or flicks the scroll view
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
animateHeaderViewHeight()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
animateHeaderViewHeight()
}
}
extension APDynamicHeaderTableViewController : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var tableViewCell : UITableViewCell
if let dequeuedTableViewCell = tableView.dequeueReusableCellWithIdentifier("Identifier") as? UITableViewCell {
tableViewCell = dequeuedTableViewCell
} else {
tableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Identifier")
tableViewCell.selectionStyle = .None
}
tableViewCell.textLabel?.text = String(indexPath.row)
return tableViewCell
}
}
|
mit
|
65cdc15cb86f717d1a375a0985aa4a2b
| 48.980392 | 300 | 0.777037 | 5.419561 | false | false | false | false |
testpress/ios-app
|
ios-app/Utils/Reachability.swift
|
1
|
2337
|
//
// Reachability.swift
// ios-app
//
// Copyright © 2017 Testpress. 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 SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr:
in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return isReachable && !needsConnection
}
}
|
mit
|
0c69454e2001e9ffff234abc93363d65
| 43.075472 | 95 | 0.693493 | 4.5625 | false | false | false | false |
ztolley/VideoStationViewer
|
VideoStationViewer/SynologyMediaItem.swift
|
1
|
569
|
import Foundation
struct SynologyMediaItem: Equatable {
var id: Int!
var title: String!
var tagline: String!
var certificate: String!
var fileId: Int!
var summary: String!
var genre: [String]!
var sortTitle: String!
var showId: Int!
var actor = [String]()
var director = [String]()
var writer = [String]()
var episode: Int!
var season: Int!
var identifier: String {
return "\(id)"
}
}
func ==(lhs: SynologyMediaItem, rhs: SynologyMediaItem)-> Bool {
// Two `DataItem`s are considered equal if their identifiers match.
return lhs.id == rhs.id
}
|
gpl-3.0
|
8f784c799d16e997438b332d9cfdba31
| 18.655172 | 68 | 0.690685 | 3.161111 | false | false | false | false |
calebd/swift
|
test/Driver/linker.swift
|
1
|
11157
|
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-none-linux-androideabi -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7 %s < %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7-NEGATIVE %s < %t.android.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.cygwin.txt
// RUN: %FileCheck -check-prefix CYGWIN-x86_64 %s < %t.cygwin.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Fsystem car -F cdr -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | %FileCheck -check-prefix DEBUG %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s > %t.simple-macosx10.10.txt
// RUN: %FileCheck %s < %t.simple-macosx10.10.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple-macosx10.10.txt
// RUN: %empty-directory(%t)
// RUN: touch %t/a.o
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | %FileCheck -check-prefix COMPILE_AND_LINK %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-use-filelists -o linker 2>&1 | %FileCheck -check-prefix FILELIST %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | %FileCheck -check-prefix INFERRED_NAME %s
// There are more RUN lines further down in the file.
// CHECK: swift
// CHECK: -o [[OBJECTFILE:.*]]
// CHECK-NEXT: bin/ld{{"? }}
// CHECK-DAG: [[OBJECTFILE]]
// CHECK-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift/macosx]]
// CHECK-DAG: -rpath [[STDLIB_PATH]]
// CHECK-DAG: -lSystem
// CHECK-DAG: -arch x86_64
// CHECK: -o {{[^ ]+}}
// SIMPLE: bin/ld{{"? }}
// SIMPLE-NOT: -syslibroot
// SIMPLE-DAG: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -o linker
// IOS_SIMPLE: swift
// IOS_SIMPLE: -o [[OBJECTFILE:.*]]
// IOS_SIMPLE: bin/ld{{"? }}
// IOS_SIMPLE-DAG: [[OBJECTFILE]]
// IOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/iphonesimulator}}
// IOS_SIMPLE-DAG: -lSystem
// IOS_SIMPLE-DAG: -arch x86_64
// IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}}
// IOS_SIMPLE: -o linker
// tvOS_SIMPLE: swift
// tvOS_SIMPLE: -o [[OBJECTFILE:.*]]
// tvOS_SIMPLE: bin/ld{{"? }}
// tvOS_SIMPLE-DAG: [[OBJECTFILE]]
// tvOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/appletvsimulator}}
// tvOS_SIMPLE-DAG: -lSystem
// tvOS_SIMPLE-DAG: -arch x86_64
// tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}}
// tvOS_SIMPLE: -o linker
// watchOS_SIMPLE: swift
// watchOS_SIMPLE: -o [[OBJECTFILE:.*]]
// watchOS_SIMPLE: bin/ld{{"? }}
// watchOS_SIMPLE-DAG: [[OBJECTFILE]]
// watchOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/watchsimulator}}
// watchOS_SIMPLE-DAG: -lSystem
// watchOS_SIMPLE-DAG: -arch i386
// watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}}
// watchOS_SIMPLE: -o linker
// LINUX-x86_64: swift
// LINUX-x86_64: -o [[OBJECTFILE:.*]]
// LINUX-x86_64: clang++{{"? }}
// LINUX-x86_64-DAG: [[OBJECTFILE]]
// LINUX-x86_64-DAG: -lswiftCore
// LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-x86_64-DAG: -F foo -iframework car -F cdr
// LINUX-x86_64-DAG: -framework bar
// LINUX-x86_64-DAG: -L baz
// LINUX-x86_64-DAG: -lboo
// LINUX-x86_64-DAG: -Xlinker -undefined
// LINUX-x86_64: -o linker
// LINUX-armv6: swift
// LINUX-armv6: -o [[OBJECTFILE:.*]]
// LINUX-armv6: clang++{{"? }}
// LINUX-armv6-DAG: [[OBJECTFILE]]
// LINUX-armv6-DAG: -lswiftCore
// LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-armv6-DAG: -target armv6-unknown-linux-gnueabihf
// LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv6-DAG: -F foo -iframework car -F cdr
// LINUX-armv6-DAG: -framework bar
// LINUX-armv6-DAG: -L baz
// LINUX-armv6-DAG: -lboo
// LINUX-armv6-DAG: -Xlinker -undefined
// LINUX-armv6: -o linker
// LINUX-armv7: swift
// LINUX-armv7: -o [[OBJECTFILE:.*]]
// LINUX-armv7: clang++{{"? }}
// LINUX-armv7-DAG: [[OBJECTFILE]]
// LINUX-armv7-DAG: -lswiftCore
// LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-armv7-DAG: -target armv7-unknown-linux-gnueabihf
// LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv7-DAG: -F foo -iframework car -F cdr
// LINUX-armv7-DAG: -framework bar
// LINUX-armv7-DAG: -L baz
// LINUX-armv7-DAG: -lboo
// LINUX-armv7-DAG: -Xlinker -undefined
// LINUX-armv7: -o linker
// LINUX-thumbv7: swift
// LINUX-thumbv7: -o [[OBJECTFILE:.*]]
// LINUX-thumbv7: clang++{{"? }}
// LINUX-thumbv7-DAG: [[OBJECTFILE]]
// LINUX-thumbv7-DAG: -lswiftCore
// LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-thumbv7-DAG: -target thumbv7-unknown-linux-gnueabihf
// LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-thumbv7-DAG: -F foo -iframework car -F cdr
// LINUX-thumbv7-DAG: -framework bar
// LINUX-thumbv7-DAG: -L baz
// LINUX-thumbv7-DAG: -lboo
// LINUX-thumbv7-DAG: -Xlinker -undefined
// LINUX-thumbv7: -o linker
// ANDROID-armv7: swift
// ANDROID-armv7: -o [[OBJECTFILE:.*]]
// ANDROID-armv7: clang++{{"? }}
// ANDROID-armv7-DAG: [[OBJECTFILE]]
// ANDROID-armv7-DAG: -lswiftCore
// ANDROID-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// ANDROID-armv7-DAG: -target armv7-none-linux-androideabi
// ANDROID-armv7-DAG: -F foo -iframework car -F cdr
// ANDROID-armv7-DAG: -framework bar
// ANDROID-armv7-DAG: -L baz
// ANDROID-armv7-DAG: -lboo
// ANDROID-armv7-DAG: -Xlinker -undefined
// ANDROID-armv7: -o linker
// ANDROID-armv7-NEGATIVE-NOT: -Xlinker -rpath
// CYGWIN-x86_64: swift
// CYGWIN-x86_64: -o [[OBJECTFILE:.*]]
// CYGWIN-x86_64: clang++{{"? }}
// CYGWIN-x86_64-DAG: [[OBJECTFILE]]
// CYGWIN-x86_64-DAG: -lswiftCore
// CYGWIN-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// CYGWIN-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// CYGWIN-x86_64-DAG: -F foo -iframework car -F cdr
// CYGWIN-x86_64-DAG: -framework bar
// CYGWIN-x86_64-DAG: -L baz
// CYGWIN-x86_64-DAG: -lboo
// CYGWIN-x86_64-DAG: -Xlinker -undefined
// CYGWIN-x86_64: -o linker
// COMPLEX: bin/ld{{"? }}
// COMPLEX-DAG: -dylib
// COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -lfoo
// COMPLEX-DAG: -framework bar
// COMPLEX-DAG: -L baz
// COMPLEX-DAG: -F garply -F car -F cdr
// COMPLEX-DAG: -undefined dynamic_lookup
// COMPLEX-DAG: -macosx_version_min 10.9.1
// COMPLEX: -o sdk.out
// DEBUG: bin/swift
// DEBUG-NEXT: bin/swift
// DEBUG-NEXT: bin/ld{{"? }}
// DEBUG: -add_ast_path {{.*}}/{{[^/]+}}.swiftmodule
// DEBUG: -o linker
// DEBUG-NEXT: {{^|bin/}}dsymutil
// DEBUG: linker
// DEBUG: -o linker.dSYM
// COMPILE_AND_LINK: bin/swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK: linker.swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK-NEXT: bin/ld{{"? }}
// COMPILE_AND_LINK-DAG: /a.o
// COMPILE_AND_LINK-DAG: .o
// COMPILE_AND_LINK: -o linker
// FILELIST: bin/ld{{"? }}
// FILELIST-NOT: .o
// FILELIST: -filelist {{"?[^-]}}
// FILELIST-NOT: .o
// FILELIST: /a.o
// FILELIST-NOT: .o
// FILELIST: -o linker
// INFERRED_NAME: bin/swift
// INFERRED_NAME: -module-name LINKER
// INFERRED_NAME: bin/ld{{"? }}
// INFERRED_NAME: -o libLINKER.{{dylib|so}}
// Test ld detection. We use hard links to make sure
// the Swift driver really thinks it's been moved.
// RUN: rm -rf %t
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/bin)
// RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc)
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE-LINKER %s
// RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/swift
// RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/ld
// RELATIVE-LINKER: -o {{[^ ]+}}
// Also test arclite detection. This uses xcrun to find arclite when it's not
// next to Swift.
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/bin)
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc)
// RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=XCRUN_ARCLITE %s
// XCRUN_ARCLITE: bin/ld{{"? }}
// XCRUN_ARCLITE: /ANOTHER-DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a
// XCRUN_ARCLITE: -o {{[^ ]+}}
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/lib/arc)
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE_ARCLITE %s
// RELATIVE_ARCLITE: bin/ld{{"? }}
// RELATIVE_ARCLITE: /DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a
// RELATIVE_ARCLITE: -o {{[^ ]+}}
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
|
apache-2.0
|
4215dcad0fbe688cadd5dced32da2b4c
| 37.874564 | 262 | 0.671686 | 2.842548 | false | false | true | false |
BradLarson/GPUImage2
|
framework/Source/ShaderUniformSettings.swift
|
1
|
3505
|
#if canImport(OpenGL)
import OpenGL.GL3
#endif
#if canImport(OpenGLES)
import OpenGLES
#endif
#if canImport(COpenGLES)
import COpenGLES.gles2
#endif
#if canImport(COpenGL)
import COpenGL
#endif
public struct ShaderUniformSettings {
private var uniformValues = [String:Any]()
public init() {
}
public subscript(index:String) -> Float? {
get { return uniformValues[index] as? Float}
set(newValue) { uniformValues[index] = newValue }
}
public subscript(index:String) -> Int? {
get { return uniformValues[index] as? Int }
set(newValue) { uniformValues[index] = newValue }
}
public subscript(index:String) -> Color? {
get { return uniformValues[index] as? Color }
set(newValue) { uniformValues[index] = newValue }
}
public subscript(index:String) -> Position? {
get { return uniformValues[index] as? Position }
set(newValue) { uniformValues[index] = newValue }
}
public subscript(index:String) -> Size? {
get { return uniformValues[index] as? Size}
set(newValue) { uniformValues[index] = newValue }
}
public subscript(index:String) -> Matrix4x4? {
get { return uniformValues[index] as? Matrix4x4 }
set(newValue) { uniformValues[index] = newValue }
}
public subscript(index:String) -> Matrix3x3? {
get { return uniformValues[index] as? Matrix3x3}
set(newValue) { uniformValues[index] = newValue }
}
public func restoreShaderSettings(_ shader:ShaderProgram) {
for (uniform, value) in uniformValues {
switch value {
case let value as Float: shader.setValue(GLfloat(value), forUniform:uniform)
case let value as Int: shader.setValue(GLint(value), forUniform:uniform)
case let value as Color: shader.setValue(value, forUniform:uniform)
case let value as Position: shader.setValue(value.toGLArray(), forUniform:uniform)
case let value as Size: shader.setValue(value.toGLArray(), forUniform:uniform)
case let value as Matrix4x4: shader.setMatrix(value.toRowMajorGLArray(), forUniform:uniform)
case let value as Matrix3x3: shader.setMatrix(value.toRowMajorGLArray(), forUniform:uniform)
default: fatalError("Somehow tried to restore a shader uniform value of an unsupported type: \(value)")
}
}
}
}
extension Color {
func toGLArray() -> [GLfloat] {
return [GLfloat(redComponent), GLfloat(greenComponent), GLfloat(blueComponent)]
}
func toGLArrayWithAlpha() -> [GLfloat] {
return [GLfloat(redComponent), GLfloat(greenComponent), GLfloat(blueComponent), GLfloat(alphaComponent)]
}
}
extension Position {
func toGLArray() -> [GLfloat] {
if let z = self.z {
return [GLfloat(x), GLfloat(y), GLfloat(z)]
} else {
return [GLfloat(x), GLfloat(y)]
}
}
}
extension Size {
func toGLArray() -> [GLfloat] {
return [GLfloat(width), GLfloat(height)]
}
}
extension Matrix4x4 {
func toRowMajorGLArray() -> [GLfloat] {
return [m11, m12, m13, m14,
m21, m22, m23, m24,
m31, m32, m33, m34,
m41, m42, m43, m44]
}
}
public extension Matrix3x3 {
func toRowMajorGLArray() -> [GLfloat] {
return [m11, m12, m13,
m21, m22, m23,
m31, m32, m33]
}
}
|
bsd-3-clause
|
e3c8f6a3d8b5e19ad3e9424fe4b0f0b7
| 29.478261 | 119 | 0.616548 | 3.903118 | false | false | false | false |
h-n-y/BigNerdRanch-SwiftProgramming
|
chapter-19/GoldChallenge.playground/Contents.swift
|
1
|
5257
|
/*
Chapter 19 Gold Challenge
Note:
The return type for the function itemForRow(_:column:) in
TabularDataSource protocol has been changed from Int to String
*/
import Cocoa
protocol TabularDataSource {
var numberOfRows: Int { get }
var numberOfColumns: Int { get }
func labelForRow(row: Int) -> String
func labelForColumn(column: Int) -> String
func itemForRow(row: Int, column: Int) -> String
}
func padding(amount: Int) -> String {
var paddingString = ""
for _ in 0..<amount {
paddingString += " "
}
return paddingString
}
func printTable(dataSource: protocol<TabularDataSource, CustomStringConvertible>) {
print("Table: \(dataSource.description)")
// Create arrays of the row and column labels
let rowLabels = (0..<dataSource.numberOfRows).map { dataSource.labelForRow($0) }
let columnLabels = (0..<dataSource.numberOfColumns).map({
(index: Int) -> String in
dataSource.labelForColumn(index)
})
// Create an array of the width of each row label
let rowLabelWidths = rowLabels.map { $0.characters.count }
// Determine length of longest row label
guard let maxRowLabelWidth = rowLabelWidths.maxElement() else {
return
}
// Determine the width of each column
// - the width of the column is controlled by the item (or label) with the
// greatest width in that column
var columnWidths = [Int]()
// iterate over each column
for col in 0..<dataSource.numberOfColumns {
// set initial max width to be the width of the column header
let columnHeader = " \(columnLabels[col]) |"
var maxColumnWidth = columnHeader.characters.count
// search for row items with widths creater than column header
for row in 0..<dataSource.numberOfRows {
let item = dataSource.itemForRow(row, column: col)
let itemWidth = " \(item) |".characters.count
if itemWidth > maxColumnWidth {
maxColumnWidth = itemWidth
}
}
columnWidths.append(maxColumnWidth)
}
// Create first row containing column headers
var firstRow: String = padding(maxRowLabelWidth) + " |"
for i in 0..<dataSource.numberOfColumns {
let columnHeader = " " + dataSource.labelForColumn(i) + " |"
let paddingAmount = columnWidths[i] - columnHeader.characters.count
firstRow += padding(paddingAmount) + columnHeader
}
print(firstRow)
// Print remaining rows
//
for i in 0..<dataSource.numberOfRows {
// Pad the row label out so they are all the same length
let paddingAmount = maxRowLabelWidth - rowLabelWidths[i]
var out = rowLabels[i] + padding(paddingAmount) + " |"
// Append each item in this row to our string
for j in 0..<dataSource.numberOfColumns {
let item = dataSource.itemForRow(i, column: j)
let itemString = " \(item) |"
let paddingAmount = columnWidths[j] - itemString.characters.count
out += padding(paddingAmount) + itemString
}
// Done - print it!
print(out)
}
}
/*
GOLD CHALLENGE
*/
struct AmazonBook {
var title: String
var author: String
var rating: Double {
// restrict rating to range [0, 5]
didSet {
if rating > 5 {
rating = 5.0
} else if rating < 0 {
rating = 0
}
}
}
}
struct BookCollection: TabularDataSource, CustomStringConvertible {
var books = [AmazonBook]()
// PROTOCOL: Custom String Convertible
var description: String {
return "Book Collection"
}
// PROTOCOL: Tabular Data Source
var numberOfRows: Int {
return books.count
}
var numberOfColumns: Int {
return 3
}
func labelForRow(row: Int) -> String {
return ""
}
func labelForColumn(column: Int) -> String {
switch column {
case 0: return "Title"
case 1: return "Author"
case 2: return "Rating"
default: fatalError("Invalid column!")
}
}
func itemForRow(row: Int, column: Int) -> String {
let book = books[row]
switch column {
case 0: return book.title
case 1: return book.author
case 2: return "\(book.rating)"
default: fatalError("Invalid column!")
}
}
}
var myBookCollection = BookCollection()
myBookCollection.books.append(AmazonBook(title: "My Name Is Lucy Barton", author: "Elizabeth Strout", rating: 3.5))
myBookCollection.books.append(AmazonBook(title: "The Girl on the Train", author: "Paula Hawkins", rating: 4.5))
myBookCollection.books.append(AmazonBook(title: "All the Light We Cannot See", author: "Anthony Doerr", rating: 4.6))
myBookCollection.books.append(AmazonBook(title: "Go Set a Watchman", author: "Harper Lee", rating: 4.0))
printTable(myBookCollection)
|
mit
|
4590be7af7a30fcdc570d78c39ee1b8a
| 25.958974 | 117 | 0.593875 | 4.462649 | false | false | false | false |
keyeMyria/edx-app-ios
|
Source/NetworkManager.swift
|
2
|
11726
|
//
// CourseOutline.swift
// edX
//
// Created by Jake Lim on 5/09/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
case PATCH = "PATCH"
}
public enum RequestBody {
case JSONBody(JSON)
case DataBody(data : NSData, contentType : String)
case EmptyBody
}
public enum ResponseDeserializer<Out> {
case JSONResponse((NSHTTPURLResponse, JSON) -> Result<Out>)
case DataResponse((NSHTTPURLResponse, NSData) -> Result<Out>)
case NoContent(NSHTTPURLResponse -> Result<Out>)
}
public struct NetworkRequest<Out> {
let method : HTTPMethod
let path : String // Absolute URL or URL relative to the API base
let requiresAuth : Bool
let body : RequestBody
let query: [String:JSON]
let deserializer : ResponseDeserializer<Out>
public init(method : HTTPMethod,
path : String,
requiresAuth : Bool = false,
body : RequestBody = .EmptyBody,
query : [String:JSON] = [:],
deserializer : ResponseDeserializer<Out>) {
self.method = method
self.path = path
self.requiresAuth = requiresAuth
self.body = body
self.query = query
self.deserializer = deserializer
}
//Apparently swift doesn't allow a computed property in a struct
func pageSize() -> Int? {
if let pageSize = query["page_size"] {
return pageSize.intValue
}
else {
return nil
}
}
}
extension NetworkRequest: DebugPrintable {
public var debugDescription: String { return "\(_stdlib_getDemangledTypeName(self.dynamicType)) {\(method):\(path)}" }
}
public struct NetworkResult<Out> {
public let request: NSURLRequest?
public let response: NSHTTPURLResponse?
public let data: Out?
public let baseData : NSData?
public let error: NSError?
public init(request : NSURLRequest?, response : NSHTTPURLResponse?, data : Out?, baseData : NSData?, error : NSError?) {
self.request = request
self.response = response
self.data = data
self.error = error
self.baseData = baseData
}
}
public class NetworkTask : Removable {
let request : Request
private init(request : Request) {
self.request = request
}
public func remove() {
request.cancel()
}
}
@objc public protocol AuthorizationHeaderProvider {
var authorizationHeaders : [String:String] { get }
}
public class NetworkManager : NSObject {
public typealias JSONInterceptor = (response : NSHTTPURLResponse, json : JSON) -> Result<JSON>
private let authorizationHeaderProvider: AuthorizationHeaderProvider?
private let baseURL : NSURL
private let cache : ResponseCache
private var jsonInterceptors : [JSONInterceptor] = []
public init(authorizationHeaderProvider: AuthorizationHeaderProvider? = nil, baseURL : NSURL, cache : ResponseCache) {
self.authorizationHeaderProvider = authorizationHeaderProvider
self.baseURL = baseURL
self.cache = cache
}
/// Allows you to add a processing pass to any JSON response.
/// Typically used to check for errors that can be sent by any request
public func addJSONInterceptor(interceptor : (response : NSHTTPURLResponse, json : JSON) -> Result<JSON>) {
jsonInterceptors.append(interceptor)
}
public func URLRequestWithRequest<Out>(request : NetworkRequest<Out>) -> Result<NSURLRequest> {
return NSURL(string: request.path, relativeToURL: baseURL).toResult().flatMap { url -> Result<NSURLRequest> in
let URLRequest = NSURLRequest(URL: url)
if request.query.count == 0 {
return Success(URLRequest)
}
var queryParams : [String:String] = [:]
for (key, value) in request.query {
value.rawString(options : NSJSONWritingOptions()).map {stringValue -> Void in
queryParams[key] = stringValue
}
}
// Alamofire has a kind of contorted API where you can encode parameters over URLs
// or through the POST body, but you can't do both at the same time.
//
// So first we encode the get parameters
let (paramRequest, error) = ParameterEncoding.URL.encode(URLRequest, parameters: queryParams)
if let error = error {
return Failure(error)
}
else {
return Success(paramRequest)
}
}
.flatMap { URLRequest in
let mutableURLRequest = URLRequest.mutableCopy() as! NSMutableURLRequest
if request.requiresAuth {
for (key, value) in self.authorizationHeaderProvider?.authorizationHeaders ?? [:] {
mutableURLRequest.setValue(value, forHTTPHeaderField: key)
}
}
mutableURLRequest.HTTPMethod = request.method.rawValue
// Now we encode the body
switch request.body {
case .EmptyBody:
return Success(mutableURLRequest)
case let .DataBody(data: data, contentType: contentType):
mutableURLRequest.HTTPBody = data
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
return Success(mutableURLRequest)
case let .JSONBody(json):
let (bodyRequest, error) = ParameterEncoding.JSON.encode(mutableURLRequest, parameters: json.dictionaryObject ?? [:])
if let error = error {
return Failure(error)
}
else {
return Success(bodyRequest)
}
}
}
}
private static func deserialize<Out>(deserializer : ResponseDeserializer<Out>, interceptors : [JSONInterceptor], response : NSHTTPURLResponse?, data : NSData?) -> Result<Out> {
if let response = response {
switch deserializer {
case let .JSONResponse(f):
if let data = data,
raw : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: nil)
{
let json = JSON(raw)
let result = reduce(interceptors, Success(json)) {(current : Result<JSON>, interceptor : (response : NSHTTPURLResponse, json : JSON) -> Result<JSON>) -> Result<JSON> in
return current.flatMap {interceptor(response : response, json: $0)}
}
return result.flatMap {
return f(response, $0)
}
}
else {
return Failure(NSError.oex_unknownError())
}
case let .DataResponse(f):
return data.toResult().flatMap { f(response, $0) }
case let .NoContent(f):
return f(response)
}
}
else {
return Failure()
}
}
public func taskForRequest<Out>(request : NetworkRequest<Out>, handler: NetworkResult<Out> -> Void) -> Removable {
let URLRequest = URLRequestWithRequest(request)
let interceptors = jsonInterceptors
let task = URLRequest.map {URLRequest -> NetworkTask in
let task = Manager.sharedInstance.request(URLRequest)
let serializer = { (URLRequest : NSURLRequest, response : NSHTTPURLResponse?, data : NSData?) -> (AnyObject?, NSError?) in
let result = NetworkManager.deserialize(request.deserializer, interceptors: interceptors, response: response, data: data)
return (Box((value : result.value, original : data)), result.error)
}
task.response(serializer: serializer) { (request, response, object, error) in
let parsed = (object as? Box<(value : Out?, original : NSData?)>)?.value
let result = NetworkResult<Out>(request: request, response: response, data: parsed?.value, baseData: parsed?.original, error: error)
handler(result)
}
task.resume()
return NetworkTask(request: task)
}
switch task {
case let .Success(t): return t.value
case let .Failure(error):
dispatch_async(dispatch_get_main_queue()) {
handler(NetworkResult(request: nil, response: nil, data: nil, baseData : nil, error: error))
}
return BlockRemovable {}
}
}
private func combineWithPersistentCacheFetch<Out>(stream : Stream<Out>, request : NetworkRequest<Out>) -> Stream<Out> {
if let URLRequest = URLRequestWithRequest(request).value {
let cacheStream = Sink<Out>()
let interceptors = jsonInterceptors
cache.fetchCacheEntryWithRequest(URLRequest, completion: {(entry : ResponseCacheEntry?) -> Void in
if let entry = entry {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {[weak cacheStream] in
let result = NetworkManager.deserialize(request.deserializer, interceptors: interceptors, response: entry.response, data: entry.data)
dispatch_async(dispatch_get_main_queue()) {[weak cacheStream] in
cacheStream?.close()
cacheStream?.send(result)
}
})
}
else {
cacheStream.close()
}
})
return stream.cachedByStream(cacheStream)
}
else {
return stream
}
}
public func streamForRequest<Out>(request : NetworkRequest<Out>, persistResponse : Bool = false, autoCancel : Bool = true) -> Stream<Out> {
let stream = Sink<NetworkResult<Out>>()
let task = self.taskForRequest(request) {[weak stream, weak self] result in
if let response = result.response, request = result.request where persistResponse {
self?.cache.setCacheResponse(response, withData: result.baseData, forRequest: request, completion: nil)
}
stream?.close()
stream?.send(result)
}
var result : Stream<Out> = stream.flatMap {[weak self] (result : NetworkResult<Out>) -> Result<Out> in
return result.data.toResult(result.error)
}
if persistResponse {
result = combineWithPersistentCacheFetch(result, request: request)
}
if autoCancel {
result = result.autoCancel(task)
}
return result
}
}
extension NetworkManager {
func addStandardInterceptors() {
addJSONInterceptor { (response, json) -> Result<JSON> in
if let statusCode = OEXHTTPStatusCode(rawValue: response.statusCode) where statusCode.is4xx {
if json["has_access"].bool == false {
let access = OEXCoursewareAccess(dictionary : json.dictionaryObject)
return Failure(OEXCoursewareAccessError(coursewareAccess: access, displayInfo: nil))
}
return Success(json)
}
else {
return Success(json)
}
}
}
}
|
apache-2.0
|
8d9076d5091e56860454860a184ef627
| 37.445902 | 188 | 0.583234 | 5.204616 | false | false | false | false |
achimk/Cars
|
CarsApp/Features/Cars/Add/Operations/CarSaveResultOperation.swift
|
1
|
2455
|
//
// CarSaveResultOperation.swift
// CarsApp
//
// Created by Joachim Kret on 01/08/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
import RxSwift
struct CarSaveResultOperation: ObservableConvertibleType {
private let service: CarAddServiceType
private let builder: CarStepCreateBuilderType
private let inputs: Array<CarInputViewModelType>
private let probe: ObservableProbe
init(service: CarAddServiceType,
builder: CarStepCreateBuilderType,
inputs: Array<CarInputViewModelType>,
probe: ObservableProbe) {
self.service = service
self.builder = builder
self.inputs = inputs
self.probe = probe
}
func asObservable() -> Observable<CarSaveResult> {
let operation = self
let probe = self.probe
return createModelObserverable()
.flatMapLatest { operation.createServiceObservable(with: $0, probe: probe) }
.map { CarSaveResult.success() }
.catchError { operation.createResult(with: $0) }
}
private func createModelObserverable() -> Observable<CarCreateModel> {
let builder = self.builder
let inputs = self.inputs
return Observable.create { (observer: AnyObserver<CarCreateModel>) -> Disposable in
builder.prepareForUse()
inputs.forEach { $0.inputs.accept(builder) }
do {
let result = try builder.build()
observer.onNext(result)
observer.onCompleted()
} catch {
observer.onError(error)
}
return Disposables.create()
}
}
private func createServiceObservable(with model: CarCreateModel, probe: ObservableProbe) -> Observable<Void> {
return service
.createCar(with: model)
.take(1)
.trackActivity(probe)
}
private func createResult(with error: Error) -> Observable<CarSaveResult> {
let result: CarSaveResult
switch error {
case let error as ValidationErrors:
result = CarSaveResult.failure(CarSaveError.invalidForm(error))
case let error as CarsServiceError:
result = CarSaveResult.failure(CarSaveError.serviceError(error))
default:
result = CarSaveResult.failure(CarSaveError.unknown(error))
}
return Observable.just(result)
}
}
|
mit
|
145a6628b58a8c9d35801e4d3c60e819
| 28.926829 | 114 | 0.632437 | 4.869048 | false | false | false | false |
tutsplus/CoreDataSwift-BatchDeletes
|
Done/AppDelegate.swift
|
4
|
4199
|
//
// AppDelegate.swift
// Done
//
// Created by Bart Jacobs on 19/10/15.
// Copyright © 2015 Envato Tuts+. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Fetch Main Storyboard
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
// Instantiate Root Navigation Controller
let rootNavigationController = mainStoryboard.instantiateViewControllerWithIdentifier("StoryboardIDRootNavigationController") as! UINavigationController
// Configure View Controller
let viewController = rootNavigationController.topViewController as? ViewController
if let viewController = viewController {
viewController.managedObjectContext = self.managedObjectContext
}
// Configure Window
window?.rootViewController = rootNavigationController
return true
}
func applicationWillResignActive(application: UIApplication) {}
func applicationDidEnterBackground(application: UIApplication) {
saveManagedObjectContext()
}
func applicationWillEnterForeground(application: UIApplication) {}
func applicationDidBecomeActive(application: UIApplication) {}
func applicationWillTerminate(application: UIApplication) {
saveManagedObjectContext()
}
// MARK: -
// MARK: Core Data Stack
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource("Done", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let persistentStoreCoordinator = self.persistentStoreCoordinator
// Initialize Managed Object Context
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
// Configure Managed Object Context
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// Initialize Persistent Store Coordinator
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
// URL Documents Directory
let URLs = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let applicationDocumentsDirectory = URLs[(URLs.count - 1)]
// URL Persistent Store
let URLPersistentStore = applicationDocumentsDirectory.URLByAppendingPathComponent("Done.sqlite")
do {
// Add Persistent Store to Persistent Store Coordinator
try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: URLPersistentStore, options: nil)
} catch {
// Populate Error
var userInfo = [String: AnyObject]()
userInfo[NSLocalizedDescriptionKey] = "There was an error creating or loading the application's saved data."
userInfo[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data."
userInfo[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "com.tutsplus.Done", code: 1001, userInfo: userInfo)
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return persistentStoreCoordinator
}()
// MARK: -
// MARK: Helper Methods
private func saveManagedObjectContext() {
do {
try self.managedObjectContext.save()
} catch {
let saveError = error as NSError
print("\(saveError), \(saveError.userInfo)")
}
}
}
|
bsd-2-clause
|
0bab12c9c0568d45a1d60be63cf847c3
| 35.824561 | 160 | 0.678418 | 6.848287 | false | false | false | false |
kstaring/swift
|
stdlib/public/core/StringHashable.swift
|
4
|
3610
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_NSStringHashValue")
func _stdlib_NSStringHashValue(_ str: AnyObject, _ isASCII: Bool) -> Int
@_silgen_name("swift_stdlib_NSStringHashValuePointer")
func _stdlib_NSStringHashValuePointer(_ str: OpaquePointer, _ isASCII: Bool) -> Int
#endif
extension _Unicode {
internal static func hashASCII(
_ string: UnsafeBufferPointer<UInt8>
) -> Int {
let collationTable = _swift_stdlib_unicode_getASCIICollationTable()
var hasher = _SipHash13Context(key: _Hashing.secretKey)
for c in string {
_precondition(c <= 127)
let element = collationTable[Int(c)]
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
internal static func hashUTF16(
_ string: UnsafeBufferPointer<UInt16>
) -> Int {
let collationIterator = _swift_stdlib_unicodeCollationIterator_create(
string.baseAddress!,
UInt32(string.count))
defer { _swift_stdlib_unicodeCollationIterator_delete(collationIterator) }
var hasher = _SipHash13Context(key: _Hashing.secretKey)
while true {
var hitEnd = false
let element =
_swift_stdlib_unicodeCollationIterator_next(collationIterator, &hitEnd)
if hitEnd {
break
}
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
}
extension String : Hashable {
/// The string's hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
#if _runtime(_ObjC)
// Mix random bits into NSString's hash so that clients don't rely on
// Swift.String.hashValue and NSString.hash being the same.
#if arch(i386) || arch(arm)
let hashOffset = Int(bitPattern: 0x88dd_cc21)
#else
let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21)
#endif
// If we have a contiguous string then we can use the stack optimization.
let core = self._core
let isASCII = core.isASCII
if core.hasContiguousStorage {
let stackAllocated = _NSContiguousString(core)
return hashOffset ^ stackAllocated._unsafeWithNotEscapedSelfPointer {
return _stdlib_NSStringHashValuePointer($0, isASCII)
}
} else {
let cocoaString = unsafeBitCast(
self._bridgeToObjectiveCImpl(), to: _NSStringCore.self)
return hashOffset ^ _stdlib_NSStringHashValue(cocoaString, isASCII)
}
#else
if let asciiBuffer = self._core.asciiBuffer {
return _Unicode.hashASCII(UnsafeBufferPointer(
start: asciiBuffer.baseAddress!,
count: asciiBuffer.count))
} else {
return _Unicode.hashUTF16(
UnsafeBufferPointer(start: _core.startUTF16, count: _core.count))
}
#endif
}
}
|
apache-2.0
|
33e14e5823ba462a44f493ec26cfd597
| 33.056604 | 83 | 0.660665 | 4.386391 | false | false | false | false |
ReactiveKit/Bond
|
Playground-macOS.playground/Pages/NSOutlineView Bindings Simpler.xcplaygroundpage/Contents.swift
|
1
|
1253
|
//: [Previous](@previous)
///: Before running the playground, make sure to build "Bond-macOS" and "PlaygroundSupport"
///: targets with Mac as a destination.
import Foundation
import PlaygroundSupport
import Cocoa
import Bond
import ReactiveKit
let outlineView = NSOutlineView()
outlineView.frame.size = CGSize(width: 300, height: 300)
outlineView.rowHeight = 30
let scrollView = NSScrollView()
scrollView.frame.size = CGSize(width: 300, height: 300)
scrollView.documentView = outlineView
// Note: Open the assistant editor to see the table view
PlaygroundPage.current.liveView = scrollView
PlaygroundPage.current.needsIndefiniteExecution = true
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "name"))
column.width = 200
column.headerCell.title = "View"
outlineView.addTableColumn(column)
outlineView.outlineTableColumn = column
// Let's make NSView a tree...
extension NSView: TreeProtocol {
public var children: [NSView] {
return subviews
}
}
// ...and use the scroll view (now a tree) as our data source
let changeset = TreeChangeset(collection: scrollView, patch: [])
SafeSignal
.just(changeset)
.bind(to: outlineView) {
$0.description as NSString
}
//: [Next](@next)
|
mit
|
03d81072b45282371dcb71b41cba4a22
| 24.571429 | 91 | 0.747805 | 4.247458 | false | false | false | false |
KrisYu/Octobook
|
Pods/FolioReaderKit/Source/Models/Highlight+Helper.swift
|
2
|
10277
|
//
// Highlight+Helper.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 06/07/16.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import Foundation
import RealmSwift
/**
HighlightStyle type, default is .Yellow.
*/
public enum HighlightStyle: Int {
case yellow
case green
case blue
case pink
case underline
public init () { self = .yellow }
/**
Return HighlightStyle for CSS class.
*/
public static func styleForClass(_ className: String) -> HighlightStyle {
switch className {
case "highlight-yellow":
return .yellow
case "highlight-green":
return .green
case "highlight-blue":
return .blue
case "highlight-pink":
return .pink
case "highlight-underline":
return .underline
default:
return .yellow
}
}
/**
Return CSS class for HighlightStyle.
*/
public static func classForStyle(_ style: Int) -> String {
switch style {
case HighlightStyle.yellow.rawValue:
return "highlight-yellow"
case HighlightStyle.green.rawValue:
return "highlight-green"
case HighlightStyle.blue.rawValue:
return "highlight-blue"
case HighlightStyle.pink.rawValue:
return "highlight-pink"
case HighlightStyle.underline.rawValue:
return "highlight-underline"
default:
return "highlight-yellow"
}
}
/**
Return CSS class for HighlightStyle.
*/
public static func colorForStyle(_ style: Int, nightMode: Bool = false) -> UIColor {
switch style {
case HighlightStyle.yellow.rawValue:
return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.green.rawValue:
return UIColor(red: 192/255, green: 237/255, blue: 114/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.blue.rawValue:
return UIColor(red: 173/255, green: 216/255, blue: 255/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.pink.rawValue:
return UIColor(red: 255/255, green: 176/255, blue: 202/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.underline.rawValue:
return UIColor(red: 240/255, green: 40/255, blue: 20/255, alpha: nightMode ? 0.6 : 1)
default:
return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1)
}
}
}
/// Completion block
public typealias Completion = (_ error: NSError?) -> ()
extension Highlight {
/**
Save a Highlight with completion block
- parameter completion: Completion block
*/
public func persist(_ completion: Completion? = nil) {
do {
let realm = try! Realm()
realm.beginWrite()
realm.add(self, update: true)
try realm.commitWrite()
completion?(nil)
} catch let error as NSError {
print("Error on persist highlight: \(error)")
completion?(error)
}
}
/**
Remove a Highlight
*/
public func remove() {
do {
let realm = try! Realm()
realm.beginWrite()
realm.delete(self)
try realm.commitWrite()
} catch let error as NSError {
print("Error on remove highlight: \(error)")
}
}
/**
Remove a Highlight by ID
- parameter highlightId: The ID to be removed
*/
public static func removeById(_ highlightId: String) {
var highlight: Highlight?
let predicate = NSPredicate(format:"highlightId = %@", highlightId)
let realm = try! Realm()
highlight = realm.objects(Highlight.self).filter(predicate).toArray(Highlight.self).first
highlight?.remove()
}
/**
Update a Highlight by ID
- parameter highlightId: The ID to be removed
- parameter type: The `HighlightStyle`
*/
public static func updateById(_ highlightId: String, type: HighlightStyle) {
var highlight: Highlight?
let predicate = NSPredicate(format:"highlightId = %@", highlightId)
do {
let realm = try! Realm()
highlight = realm.objects(Highlight.self).filter(predicate).toArray(Highlight.self).first
realm.beginWrite()
highlight?.type = type.hashValue
try realm.commitWrite()
} catch let error as NSError {
print("Error on updateById : \(error)")
}
}
/**
Return a list of Highlights with a given ID
- parameter bookId: Book ID
- parameter page: Page number
- returns: Return a list of Highlights
*/
public static func allByBookId(_ bookId: String, andPage page: NSNumber? = nil) -> [Highlight] {
var highlights: [Highlight]?
let predicate = (page != nil) ? NSPredicate(format: "bookId = %@ && page = %@", bookId, page!) : NSPredicate(format: "bookId = %@", bookId)
let realm = try! Realm()
highlights = realm.objects(Highlight.self).filter(predicate).toArray(Highlight.self)
return highlights!
}
/**
Return all Highlights
- returns: Return all Highlights
*/
public static func all() -> [Highlight] {
var highlights: [Highlight]?
let realm = try! Realm()
highlights = realm.objects(Highlight.self).toArray(Highlight.self)
return highlights!
}
// MARK: HTML Methods
/**
Match a highlight on string.
*/
public static func matchHighlight(_ text: String!, andId id: String, startOffset: String, endOffset: String) -> Highlight? {
let pattern = "<highlight id=\"\(id)\" onclick=\".*?\" class=\"(.*?)\">((.|\\s)*?)</highlight>"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
let str = (text as NSString)
let mapped = matches.map { (match) -> Highlight in
var contentPre = str.substring(with: NSRange(location: match.range.location-kHighlightRange, length: kHighlightRange))
var contentPost = str.substring(with: NSRange(location: match.range.location + match.range.length, length: kHighlightRange))
// Normalize string before save
if contentPre.range(of: ">") != nil {
let regex = try! NSRegularExpression(pattern: "((?=[^>]*$)(.|\\s)*$)", options: [])
let searchString = regex.firstMatch(in: contentPre, options: .reportProgress, range: NSRange(location: 0, length: contentPre.characters.count))
if searchString!.range.location != NSNotFound {
contentPre = (contentPre as NSString).substring(with: searchString!.range)
}
}
if contentPost.range(of: "<") != nil {
let regex = try! NSRegularExpression(pattern: "^((.|\\s)*?)(?=<)", options: [])
let searchString = regex.firstMatch(in: contentPost, options: .reportProgress, range: NSRange(location: 0, length: contentPost.characters.count))
if searchString!.range.location != NSNotFound {
contentPost = (contentPost as NSString).substring(with: searchString!.range)
}
}
let highlight = Highlight()
highlight.highlightId = id
highlight.type = HighlightStyle.styleForClass(str.substring(with: match.rangeAt(1))).rawValue
highlight.date = Foundation.Date()
highlight.content = Highlight.removeSentenceSpam(str.substring(with: match.rangeAt(2)))
highlight.contentPre = Highlight.removeSentenceSpam(contentPre)
highlight.contentPost = Highlight.removeSentenceSpam(contentPost)
highlight.page = currentPageNumber
highlight.bookId = (kBookId as NSString).deletingPathExtension
highlight.startOffset = Int(startOffset) ?? -1
highlight.endOffset = Int(endOffset) ?? -1
return highlight
}
return mapped.first
}
/**
Remove a Highlight from HTML by ID
- parameter highlightId: The ID to be removed
- returns: The removed id
*/
@discardableResult public static func removeFromHTMLById(_ highlightId: String) -> String? {
guard let currentPage = FolioReader.shared.readerCenter?.currentPage else { return nil }
if let removedId = currentPage.webView.js("removeHighlightById('\(highlightId)')") {
return removedId
} else {
print("Error removing Higlight from page")
return nil
}
}
/**
Remove span tag before store the highlight, this span is added on JavaScript.
<span class=\"sentence\"></span>
- parameter text: Text to analise
- returns: Striped text
*/
public static func removeSentenceSpam(_ text: String) -> String {
// Remove from text
func removeFrom(_ text: String, withPattern pattern: String) -> String {
var locator = text
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: locator, options: [], range: NSRange(location: 0, length: locator.utf16.count))
let str = (locator as NSString)
var newLocator = ""
for match in matches {
newLocator += str.substring(with: match.rangeAt(1))
}
if matches.count > 0 && !newLocator.isEmpty {
locator = newLocator
}
return locator
}
let pattern = "<span class=\"sentence\">((.|\\s)*?)</span>"
let cleanText = removeFrom(text, withPattern: pattern)
return cleanText
}
}
|
mit
|
91e478c82e35b40a0d47b6215533163a
| 34.684028 | 161 | 0.578671 | 4.829417 | false | false | false | false |
MillmanY/MMTabBarAnimation
|
MMTabBarAnimation/Classes/UIViewExtension.swift
|
1
|
2550
|
//
// UIViewExtension.swift
// TabBarDemo
//
// Created by Millman YANG on 2016/12/17.
// Copyright © 2016年 Millman YANG. All rights reserved.
//
import UIKit
public enum RotationType {
case left
case right
case circle
}
public struct TabBarAnimate {
internal let view: UIView
var duration:TimeInterval = 0.3
public func scaleBounce(rate:Float) {
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.duration = duration
animation.values = [1.0,rate,1.1,0.8,1.0]
self.view.layer.add(animation, forKey: "Scale")
}
public func rotation(type:RotationType) {
switch type {
case .left,.right:
let option:UIViewAnimationOptions = (type == .left) ? .transitionFlipFromLeft : .transitionFlipFromRight
UIView.transition(with: self.view, duration: duration, options: option, animations: nil, completion: nil)
case .circle:
self.rotaitonZ()
}
}
fileprivate func rotaitonZ() {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = 0.0
animation.toValue = CGFloat(M_PI * 2.0)
animation.duration = duration
animation.isRemovedOnCompletion = false
self.view.layer.add(animation, forKey: "Rotation")
}
public func shake() {
let animation = CAKeyframeAnimation.init(keyPath: "position.x")
let x = self.view.center.x
animation.values = [(x-3),(x+3),(x-2),(x+2),(x-1),(x+1),(x)]
animation.duration = duration
self.view.layer.add(animation, forKey: "Shake")
}
public func jumpY() {
let animation = CAKeyframeAnimation.init(keyPath: "position.y")
let y = self.view.center.y
animation.values = [(y-5),(y),(y-3),(y),(y-1),(y)]
animation.duration = duration
self.view.layer.add(animation, forKey: "JumpY")
}
internal init(view: UIView) {
self.view = view
}
}
private var animateKey = "TabBarAnimateKey"
extension UIView {
public var animate: TabBarAnimate {
set {
objc_setAssociatedObject(self, &animateKey, newValue, .OBJC_ASSOCIATION_RETAIN)
} get {
if let animate = objc_getAssociatedObject(self, &animateKey) as? TabBarAnimate {
return animate
} else {
self.animate = TabBarAnimate(view: self)
return self.animate
}
}
}
}
|
mit
|
6f0f8def5d2d618d5d0da3cf8b977053
| 29.686747 | 117 | 0.602277 | 4.154976 | false | false | false | false |
sdq/rrule.swift
|
rrule.swift
|
1
|
30890
|
//
// RRuleSwift.swift
// RecurrenceTest
//
// Created by sdq on 7/18/16.
// Copyright © 2016 sdq. All rights reserved.
//
import Foundation
import EventKit
// 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
}
}
// swiftlint:disable file_length
// swiftlint:disable variable_name
// swiftlint:disable type_name
// swiftlint:disable type_body_length
// swiftlint:disable comma
// swiftlint:disable todo
public enum RruleFrequency {
case yearly
case monthly
case weekly
case daily
case hourly //Todo
case minutely //Todo
case secondly //Todo
}
private struct DateMask {
var year: Int = 0
var month: Int = 0
var leapYear: Bool = false
var nextYearLength: Int = 0
var lastdayOfMonth: [Int] = []
var weekdayOf1stYearday: Int = 0
var yeardayToWeekday: [Int] = []
var yeardayToMonth: [Int] = []
var yeardayToMonthday: [Int] = []
var yeardayToMonthdayNegtive: [Int] = []
var yearLength: Int = 0
var yeardayIsNthWeekday: [Int:Bool] = [:]
var yeardayIsInWeekno: [Int:Bool] = [:]
}
class rrule {
var frequency: RruleFrequency
var interval = 1
var wkst: Int = 1
var dtstart = Date()
var until: Date?
var count: Int?
var bysetpos = [Int]()
var byyearday = [Int]()
var bymonth = [Int]()
var byweekno = [Int]()
var bymonthday = [Int]()
var bymonthdayNegative = [Int]()
var byweekday = [Int]()
var byweekdaynth = [Int]()
var byhour = [Int]()
var byminute = [Int]()
var bysecond = [Int]()
var exclusionDates = [Date]()
var inclusionDates = [Date]()
fileprivate let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
fileprivate var dateComponent = DateComponents()
fileprivate var year: Int = 0
fileprivate var month: Int = 0
fileprivate var day: Int = 0
fileprivate var hour: Int = 0
fileprivate var minute: Int = 0
fileprivate var second: Int = 0
fileprivate var dayset: [Int]?
fileprivate var total: Int?
fileprivate var masks = DateMask()
init(frequency: RruleFrequency, dtstart: Date? = nil, until: Date? = nil, count: Int? = nil, interval: Int = 1, wkst: Int = 1, bysetpos: [Int] = [], bymonth: [Int] = [], bymonthday: [Int] = [], byyearday: [Int] = [], byweekno: [Int] = [], byweekday: [Int] = [], byhour: [Int] = [], byminute: [Int] = [], bysecond: [Int] = [], exclusionDates: [Date] = [], inclusionDates: [Date] = []) {
self.frequency = frequency
if let dtstart = dtstart {
self.dtstart = dtstart
}
if let until = until {
self.until = until
}
if let count = count {
self.count = count
}
self.interval = interval
self.wkst = wkst
self.bysetpos = bysetpos
self.bymonth = bymonth
self.byyearday = byyearday
self.byweekno = byweekno
self.byweekday = byweekday
self.byhour = byhour
self.byminute = byminute
self.bysecond = bysecond
self.inclusionDates = inclusionDates
self.exclusionDates = exclusionDates
for monthday in bymonthday {
if monthday < -31 || monthday > 31 {
continue
}
if monthday < 0 {
self.bymonthdayNegative.append(monthday)
} else {
self.bymonthday.append(monthday)
}
}
// Complete the recurrence rule
if self.byweekno.count == 0 && self.byyearday.count == 0 && self.bymonthday.count == 0 && self.byweekday.count == 0 {
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: dtstart!)
switch frequency {
case .yearly:
if bymonth.count == 0 {
if let month = components.month {
self.bymonth = [month]
}
}
if let day = components.day {
self.bymonthday = [day]
}
case .monthly:
if let day = components.day {
self.bymonthday = [day]
}
case .weekly:
if let weekday = components.weekday {
self.byweekday = [weekday]
}
default:
break
}
}
}
func getOccurrences() -> [Date] {
return getOccurrencesBetween()
}
// swiftlint:disable function_body_length
func getOccurrencesBetween(beginDate: Date? = nil, endDate: Date? = nil) -> [Date] {
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dtstart)
year = components.year!
month = components.month!
day = components.day!
hour = components.hour!
minute = components.minute!
second = components.second!
var beginDateYear = 0
var beginDateYearday = 0
if let beginDate = beginDate {
let (beginYear, beginMonth, beginDay) = getYearMonthDay(beginDate)
beginDateYear = beginYear
beginDateYearday = getYearday(year: beginYear, month: beginMonth, day: beginDay)
}
var endDateYear = 0
var endDateYearday = 0
if let endDate = endDate {
let (endYear, endMonth, endDay) = getYearMonthDay(endDate)
endDateYear = endYear
endDateYearday = getYearday(year: endYear, month: endMonth, day: endDay)
}
var endFlag = false
guard let max = MaxRepeatCycle[frequency] else {
return []
}
var occurrences = [Date]()
for _ in 0..<max {
// 1. get dayset in the next interval
if masks.year == 0 || masks.month == 0 || masks.year != year || masks.month != month {
//only if year change
if masks.year != year {
masks.leapYear = isLeapYear(year)
if isLeapYear(year) {
masks.yearLength = 366
masks.yeardayToMonth = M366MASK
masks.yeardayToMonthday = MDAY366MASK
masks.yeardayToMonthdayNegtive = NMDAY366MASK
masks.lastdayOfMonth = M366RANGE
} else {
masks.yearLength = 365
masks.yeardayToMonth = M365MASK
masks.yeardayToMonthday = MDAY365MASK
masks.yeardayToMonthdayNegtive = NMDAY365MASK
masks.lastdayOfMonth = M365RANGE
}
if isLeapYear(year+1) {
masks.nextYearLength = 366
} else {
masks.nextYearLength = 365
}
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = 1
dateComponents.day = 1
let date = Calendar.current.date(from: dateComponents)!
let weekdayOf1stYearday = Calendar.current.component(.weekday, from: date)
let yeardayToWeekday = Array(WDAYMASK.suffix(from: weekdayOf1stYearday-1))
masks.weekdayOf1stYearday = weekdayOf1stYearday
masks.yeardayToWeekday = yeardayToWeekday
if byweekno.count > 0 {
buildWeeknoMask(year, month: month, day: day)
}
}
// everytime month or year changes
if byweekdaynth.count != 0 {
//TODO: deal with weekdaynth mask
}
masks.year = year
masks.month = month
}
let dayset = getDaySet(year, month: month, day: day, masks: masks)
// 2. filter the dayset by mask
var filterDayset = [Int]()
for yeardayFromZero in dayset {
if bymonth.count != 0 && !bymonth.contains(masks.yeardayToMonth[yeardayFromZero]) {
continue
}
if byweekno.count != 0 && masks.yeardayIsInWeekno[yeardayFromZero] == nil {
continue
}
if byyearday.count != 0 {
if yeardayFromZero < masks.yearLength {
if !byyearday.contains(yeardayFromZero + 1) && !byyearday.contains(yeardayFromZero - masks.yearLength) {
continue
}
} else {
if !byyearday.contains(yeardayFromZero + 1 - masks.yearLength) && !byyearday.contains(yeardayFromZero - masks.yearLength - masks.nextYearLength) {
continue
}
}
}
if (bymonthday.count != 0 || bymonthdayNegative.count != 0) && !bymonthday.contains(masks.yeardayToMonthday[yeardayFromZero]) && !bymonthdayNegative.contains(masks.yeardayToMonthdayNegtive[yeardayFromZero]) {
continue
}
if byweekday.count != 0 && !byweekday.contains(masks.yeardayToWeekday[yeardayFromZero]) {
continue
}
if byweekdaynth.count != 0 && masks.yeardayIsNthWeekday[yeardayFromZero] == nil {
continue
}
let yearday = yeardayFromZero + 1
filterDayset.append(yearday)
}
// setup BYSETPOS
if bysetpos.count > 0 {
for i in 0..<bysetpos.count {
if bysetpos[i] < 0 {
bysetpos[i] = filterDayset.count + 1 + bysetpos[i]
}
}
}
// 3. filter the dayset by conditions
for index in 0..<filterDayset.count {
//yearday to month and day
let yearday = filterDayset[index]
if bysetpos.count > 0 && !bysetpos.contains(index+1) {
continue
}
if let _ = beginDate {
if beginDateYear > year || (beginDateYear == year && beginDateYearday > yearday) {
continue
}
// if beginDate.timeIntervalSinceDate(occurrence) > 0 {
// continue
// }
}
if let _ = endDate {
if endDateYear < year || (endDateYear == year && endDateYearday < yearday) {
continue
}
// if endDate.timeIntervalSinceDate(occurrence) < 0 {
// continue
// }
}
let occurrence = getDate(year: year, month: 1, day: yearday, hour: hour, minute: minute, second: second)
if (self.count != nil && occurrences.count >= self.count!) || (self.until != nil && occurrence > self.until!) {
endFlag = true
break
}
occurrences.append(occurrence)
}
if endFlag {
break
}
// 4. prepare for the next interval
var daysIncrement = 0
switch frequency {
case .yearly:
year = year + interval
case .monthly:
month = month + interval
if month > 12 {
year = year + month / 12
month = month % 12
if month == 0 {
month = 12
year = year - 1
}
}
case .weekly:
if dayset.count < 7 {
daysIncrement = 7 * (interval - 1) + dayset.count
} else {
daysIncrement = 7 * interval
}
case .daily:
daysIncrement = interval
default:
break
}
if daysIncrement > 0 {
let yearday = getYearday(year: year, month: month, day: day)
let newYearday = yearday + daysIncrement
if newYearday > masks.yearLength {
let newDate = getDate(year: year, month: month, day: (day + daysIncrement), hour: hour, minute: minute, second: second)
(year, month, day) = getYearMonthDay(newDate)
} else {
if masks.leapYear {
month = M366MASK[newYearday - 1]
day = newYearday - M366RANGE[month - 1]
} else {
month = M365MASK[newYearday - 1]
day = newYearday - M365RANGE[month - 1]
}
}
}
}
//include dates
for rdate in inclusionDates {
if let beginDate = beginDate {
if beginDate.timeIntervalSince(rdate) > 0 {
continue
}
}
if let endDate = endDate {
if endDate.timeIntervalSince(rdate) < 0 {
continue
}
}
occurrences.append(rdate)
}
//exclude dates
for exdate in exclusionDates {
for occurrence in occurrences {
if occurrence.timeIntervalSince(exdate) == 0 {
let index = occurrences.index(of: occurrence)!
occurrences.remove(at: index)
}
}
}
return occurrences
}
fileprivate func getDaySet(_ year: Int, month: Int, day: Int, masks: DateMask) -> [Int] {
//let date = getDate(year: year, month: month, day: day, hour: hour, minute: minute, second: second)
switch frequency {
case .yearly:
let yearLen = masks.yearLength
var returnArray = [Int]()
for i in 0..<yearLen {
returnArray.append(i)
}
return returnArray
case .monthly:
let start = masks.lastdayOfMonth[month - 1]
let end = masks.lastdayOfMonth[month]
var returnArray = [Int]()
for i in start..<end {
returnArray.append(i)
}
return returnArray
case .weekly:
var returnArray = [Int]()
var i = getYearday(year: year, month: month, day: day) - 1 //from zero
for _ in 0..<7 {
returnArray.append(i)
i = i + 1
if masks.yeardayToWeekday[i] == wkst {
break
}
}
return returnArray
case .daily:
fallthrough
case .hourly:
fallthrough
case .minutely:
fallthrough
case .secondly:
let i = getYearday(year: year, month: month, day: day) - 1
return [i]
}
}
fileprivate func buildWeeknoMask(_ year: Int, month: Int, day: Int) {
masks.yeardayIsInWeekno = [Int:Bool]()
let firstWkst = (7 - masks.weekdayOf1stYearday + wkst) % 7
var firstWkstOffset: Int
var days: Int
if firstWkst >= 4 {
firstWkstOffset = 0
days = masks.yearLength + masks.weekdayOf1stYearday - wkst
} else {
firstWkstOffset = firstWkst
days = masks.yearLength - firstWkst
}
let weeks = days / 7 + (days % 7) / 4
for weekno in byweekno {
var n = weekno
if n < 0 {
n = n + weeks + 1
}
if n <= 0 || n > weeks {
continue
}
var i = 0
if n > 1 {
i = firstWkstOffset + (n - 1) * 7
if firstWkstOffset != firstWkst {
i = i - (7 - firstWkst)
}
} else {
i = firstWkstOffset
}
for _ in 0..<7 {
masks.yeardayIsInWeekno[i] = true
i = i + 1
if masks.yeardayToWeekday[i] == wkst {
break
}
}
}
if byweekno.contains(1) {
// TODO: Check -numweeks for next year.
var i = firstWkstOffset + weeks * 7
if firstWkstOffset != firstWkst {
i = i - (7 - firstWkst)
}
if i < masks.yearLength {
for _ in 0..<7 {
masks.yeardayIsInWeekno[i] = true
i = i + 1
if masks.yeardayToWeekday[i] == wkst {
break
}
}
}
}
var weeksLastYear = -1
if !byweekno.contains(-1) {
var dateComponents = DateComponents()
dateComponents.year = year-1
dateComponents.month = 1
dateComponents.day = 1
let date = Calendar.current.date(from: dateComponents)!
let weekdayOf1stYearday = Calendar.current.component(.weekday, from: date)
var firstWkstOffsetLastYear = (7 - weekdayOf1stYearday + wkst) % 7
let lastYearLen = isLeapYear(year-1) ? 366 : 365
if firstWkstOffsetLastYear >= 4 {
firstWkstOffsetLastYear = 0
weeksLastYear = 52 + ((lastYearLen + (weekdayOf1stYearday - wkst) % 7) % 7) / 4
} else {
weeksLastYear = 52 + ((masks.yearLength - firstWkstOffset) % 7) / 4
}
}
if byweekno.contains(weeksLastYear) {
for i in 0..<firstWkstOffset {
masks.yeardayIsInWeekno[i] = true
}
}
}
fileprivate let M366MASK = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
1,1,1,1,1,1,1] //7 days longer
fileprivate let M365MASK = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
1,1,1,1,1,1,1]
fileprivate let MDAY366MASK = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7]
fileprivate let MDAY365MASK = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1,2,3,4,5,6,7]
fileprivate let NMDAY366MASK = [-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25]
fileprivate let NMDAY365MASK = [-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
-31,-30,-29,-28,-27,-26,-25]
fileprivate let WDAYMASK = [1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7] //55 weeks
fileprivate let M366RANGE = [0,31,60,91,121,152,182,213,244,274,305,335,366]
fileprivate let M365RANGE = [0,31,59,90,120,151,181,212,243,273,304,334,365]
fileprivate let MaxRepeatCycle: [RruleFrequency:Int] = [.yearly:10,
.monthly:120,
.weekly:520,
.daily:3650,
.hourly:24,
.minutely:1440,
.secondly:86400]
fileprivate func isLeapYear(_ year: Int) -> Bool {
if year % 4 == 0 {
return true
}
if year % 100 == 0 {
return false
}
if year % 400 == 0 {
return true
}
return false
}
fileprivate func getDate(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int) -> Date {
dateComponent.year = year
dateComponent.month = month
dateComponent.day = day
dateComponent.hour = hour
dateComponent.minute = minute
dateComponent.second = second
return (calendar.date(from: dateComponent))!
}
fileprivate func getYearday(year:Int, month: Int, day: Int) -> Int {
if isLeapYear(year) {
return M366RANGE[month - 1] + day
} else {
return M365RANGE[month - 1] + day
}
}
fileprivate func getYearMonthDay(_ date: Date) -> (Int, Int, Int) {
let dateComponent = (calendar as NSCalendar?)?.components([.year, .month, .day], from: date)
return ((dateComponent?.year)!, (dateComponent?.month)!, (dateComponent?.day)!)
}
fileprivate func getWeekday(_ date: Date) -> Int {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let dateComponent = (calendar as NSCalendar?)?.components(.weekday, from: date)
return (dateComponent?.weekday)!
}
}
|
mit
|
9a44894354b0e0e77776e7f741365420
| 44.4919 | 389 | 0.463919 | 3.055896 | false | false | false | false |
robtimp/xswift
|
exercises/minesweeper/Sources/Minesweeper/MinesweeperExample.swift
|
2
|
3652
|
import Foundation
#if os(Linux)
#if swift(>=3.1)
typealias Regex = NSRegularExpression
#else
typealias Regex = RegularExpression
#endif
#else
typealias Regex = NSRegularExpression
#endif
struct Board {
private let validCharacters: [Character] = ["+", "-", "|", "*", " "]
private let rows: [String]
enum BoardError: Error {
case differentLength
case faultyBorder
case invalidCharacter
}
init(_ rows: [String]) throws {
self.rows = rows
try validateInput()
}
func transform() -> [String] {
var result = [String]()
let rowsEnumarated = rows.enumerated()
for (i, row) in rowsEnumarated {
var newRow = ""
let rowCharsEnumarated = row.enumerated()
for (j, character) in rowCharsEnumarated {
if character != " " {
newRow += String(character)
} else {
let mineCount = mineCountForRow(row, i: i, j: j)
if mineCount > 0 {
newRow += String(mineCount)
} else {
newRow += " "
}
}
}
result.append(newRow)
}
return result
}
private func mineCountForRow(_ row: String, i: Int, j: Int) -> Int {
// Must be split up to avoid error: "Expression was too complex to be solved in reasonable time."
var surroundings = [row[j - 1], row[j + 1], rows[i - 1][j - 1]]
surroundings += [rows[i - 1][j], rows[i - 1][j + 1]]
surroundings += [rows[i + 1][j - 1]]
surroundings += [rows[i + 1][j], rows[i + 1][j + 1]]
return surroundings.filter { isMine($0) }.count
}
private func isMine(_ character: Character) -> Bool {
return character == "*"
}
private func validateInput() throws {
try validateSize()
try validateData()
try validateBorders()
}
private func validateSize() throws {
guard let count = rows.first?.count else {
throw BoardError.differentLength
}
try rows.forEach {
guard $0.count == count else {
throw BoardError.differentLength
}
}
}
private func validateData() throws {
try rows.forEach {
try $0.forEach {
guard validCharacters.contains($0) else {
throw BoardError.invalidCharacter
}
}
}
}
private func validateBorders() throws {
let firstAndLast = [rows[0], rows[rows.count - 1]]
try firstAndLast.forEach {
guard $0.matchesRegex("^\\+[-]+\\+$") else {
throw BoardError.faultyBorder
}
}
let middleRows = rows[1 ..< rows.count - 2]
try middleRows.forEach {
guard $0.matchesRegex("^\\|.+\\|$") else {
throw BoardError.faultyBorder
}
}
}
}
private extension String {
func matchesRegex(_ pattern: String) -> Bool {
let options = Regex.Options.dotMatchesLineSeparators
let regex = try? Regex(pattern: pattern, options: options)
var matches = 0
if let regex = regex {
matches = regex.numberOfMatches(in: self,
options: [],
range: NSRange(0..<self.utf16.count) )
}
return matches > 0
}
subscript(idx: Int) -> Character {
return self[index(startIndex, offsetBy: idx)]
}
}
|
mit
|
3e822199e595afe087ee0f731d09f03a
| 27.092308 | 105 | 0.508215 | 4.536646 | false | false | false | false |
klundberg/swift-corelibs-foundation
|
Foundation/PersonNameComponents.swift
|
1
|
3366
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
public struct PersonNameComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing {
public typealias ReferenceType = NSPersonNameComponents
internal var _handle: _MutableHandle<NSPersonNameComponents>
public init() {
_handle = _MutableHandle(adoptingReference: NSPersonNameComponents())
}
private init(reference: NSPersonNameComponents) {
_handle = _MutableHandle(reference: reference)
}
/* The below examples all assume the full name Dr. Johnathan Maple Appleseed Esq., nickname "Johnny" */
/* Pre-nominal letters denoting title, salutation, or honorific, e.g. Dr., Mr. */
public var namePrefix: String? {
get { return _handle.map { $0.namePrefix } }
set { _applyMutation { $0.namePrefix = newValue } }
}
/* Name bestowed upon an individual by one's parents, e.g. Johnathan */
public var givenName: String? {
get { return _handle.map { $0.givenName } }
set { _applyMutation { $0.givenName = newValue } }
}
/* Secondary given name chosen to differentiate those with the same first name, e.g. Maple */
public var middleName: String? {
get { return _handle.map { $0.middleName } }
set { _applyMutation { $0.middleName = newValue } }
}
/* Name passed from one generation to another to indicate lineage, e.g. Appleseed */
public var familyName: String? {
get { return _handle.map { $0.familyName } }
set { _applyMutation { $0.familyName = newValue } }
}
/* Post-nominal letters denoting degree, accreditation, or other honor, e.g. Esq., Jr., Ph.D. */
public var nameSuffix: String? {
get { return _handle.map { $0.nameSuffix } }
set { _applyMutation { $0.nameSuffix = newValue } }
}
/* Name substituted for the purposes of familiarity, e.g. "Johnny"*/
public var nickname: String? {
get { return _handle.map { $0.nickname } }
set { _applyMutation { $0.nickname = newValue } }
}
/* Each element of the phoneticRepresentation should correspond to an element of the original PersonNameComponents instance.
The phoneticRepresentation of the phoneticRepresentation object itself will be ignored. nil by default, must be instantiated.
*/
public var phoneticRepresentation: PersonNameComponents? {
get { return _handle.map { $0.phoneticRepresentation } }
set { _applyMutation { $0.phoneticRepresentation = newValue } }
}
public var hashValue : Int {
return _handle.map { $0.hash }
}
public var description: String { return _handle.map { $0.description } }
public var debugDescription: String { return _handle.map { $0.debugDescription } }
}
public func ==(lhs : PersonNameComponents, rhs: PersonNameComponents) -> Bool {
// Don't copy references here; no one should be storing anything
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
|
apache-2.0
|
22bf8663a241d535568fcdb392e655fb
| 41.607595 | 130 | 0.66637 | 4.440633 | false | false | false | false |
klundberg/swift-corelibs-foundation
|
Foundation/NSNotification.swift
|
1
|
7958
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
extension NSNotification {
public struct Name : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
}
}
public func ==(lhs: NSNotification.Name, rhs: NSNotification.Name) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public func <(lhs: NSNotification.Name, rhs: NSNotification.Name) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public class NSNotification: NSObject, NSCopying, NSCoding {
private(set) public var name: Name
private(set) public var object: AnyObject?
private(set) public var userInfo: [String : Any]?
public convenience override init() {
/* do not invoke; not a valid initializer for this class */
fatalError()
}
public init(name: Name, object: AnyObject?, userInfo: [String : Any]?) {
self.name = name
self.object = object
self.userInfo = userInfo
}
public convenience required init?(coder aDecoder: NSCoder) {
if aDecoder.allowsKeyedCoding {
guard let name = aDecoder.decodeObjectOfClass(NSString.self, forKey:"NS.name") else {
return nil
}
let object = aDecoder.decodeObject(forKey: "NS.object")
// let userInfo = aDecoder.decodeObjectOfClass(NSDictionary.self, forKey: "NS.userinfo")
self.init(name: Name(rawValue: name.bridge()), object: object, userInfo: nil)
} else {
guard let name = aDecoder.decodeObject() as? NSString else {
return nil
}
let object = aDecoder.decodeObject()
// let userInfo = aDecoder.decodeObject() as? NSDictionary
self.init(name: Name(rawValue: name.bridge()), object: object, userInfo: nil)
}
}
public func encode(with aCoder: NSCoder) {
if aCoder.allowsKeyedCoding {
aCoder.encode(self.name.rawValue.bridge(), forKey:"NS.name")
aCoder.encode(self.object, forKey:"NS.object")
// aCoder.encodeObject(self.userInfo?.bridge(), forKey:"NS.userinfo")
} else {
aCoder.encode(self.name.rawValue.bridge())
aCoder.encode(self.object)
// aCoder.encodeObject(self.userInfo?.bridge())
}
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
return self
}
public override var description: String {
var str = "\(self.dynamicType) \(unsafeAddress(of: self)) {"
str += "name = \(self.name.rawValue)"
if let object = self.object {
str += "; object = \(object)"
}
if let userInfo = self.userInfo {
str += "; userInfo = \(userInfo)"
}
str += "}"
return str
}
}
extension NSNotification {
public convenience init(name aName: Name, object anObject: AnyObject?) {
self.init(name: aName, object: anObject, userInfo: nil)
}
}
private class NSNotificationReceiver : NSObject {
private weak var object: NSObject?
private var name: Notification.Name?
private var block: ((Notification) -> Void)?
private var sender: AnyObject?
}
extension Sequence where Iterator.Element : NSNotificationReceiver {
/// Returns collection of `NSNotificationReceiver`.
///
/// Will return:
/// - elements that property `object` is not equal to `observerToFilter`
/// - elements that property `name` is not equal to parameter `name` if specified.
/// - elements that property `sender` is not equal to parameter `object` if specified.
///
private func filterOutObserver(_ observerToFilter: AnyObject, name:Notification.Name? = nil, object: AnyObject? = nil) -> [Iterator.Element] {
return self.filter { observer in
let differentObserver = observer.object !== observerToFilter
let nameSpecified = name != nil
let differentName = observer.name != name
let objectSpecified = object != nil
let differentSender = observer.sender !== object
return differentObserver || (nameSpecified && differentName) || (objectSpecified && differentSender)
}
}
/// Returns collection of `NSNotificationReceiver`.
///
/// Will return:
/// - elements that property `sender` is `nil` or equals specified parameter `sender`.
/// - elements that property `name` is `nil` or equals specified parameter `name`.
///
private func observersMatchingName(_ name:Notification.Name? = nil, sender: AnyObject? = nil) -> [Iterator.Element] {
return self.filter { observer in
let emptyName = observer.name == nil
let sameName = observer.name == name
let emptySender = observer.sender == nil
let sameSender = observer.sender === sender
return (emptySender || sameSender) && (emptyName || sameName)
}
}
}
private let _defaultCenter: NotificationCenter = NotificationCenter()
public class NotificationCenter: NSObject {
private var _observers: [NSNotificationReceiver]
private let _observersLock = Lock()
public required override init() {
_observers = [NSNotificationReceiver]()
}
public class func defaultCenter() -> NotificationCenter {
return _defaultCenter
}
public func postNotification(_ notification: Notification) {
let sendTo = _observersLock.synchronized({
return _observers.observersMatchingName(notification.name, sender: notification.object)
})
for observer in sendTo {
guard let block = observer.block else {
continue
}
block(notification)
}
}
public func postNotificationName(_ aName: Notification.Name, object anObject: AnyObject?) {
let notification = Notification(name: aName, object: anObject)
postNotification(notification)
}
public func postNotificationName(_ aName: Notification.Name, object anObject: AnyObject?, userInfo aUserInfo: [String : Any]?) {
let notification = Notification(name: aName, object: anObject, userInfo: aUserInfo)
postNotification(notification)
}
public func removeObserver(_ observer: AnyObject) {
removeObserver(observer, name: nil, object: nil)
}
public func removeObserver(_ observer: AnyObject, name: Notification.Name?, object: AnyObject?) {
guard let observer = observer as? NSObject else {
return
}
_observersLock.synchronized({
self._observers = _observers.filterOutObserver(observer, name: name, object: object)
})
}
public func addObserverForName(_ name: Notification.Name?, object obj: AnyObject?, queue: OperationQueue?, usingBlock block: (Notification) -> Void) -> NSObjectProtocol {
if queue != nil {
NSUnimplemented()
}
let object = NSObject()
let newObserver = NSNotificationReceiver()
newObserver.object = object
newObserver.name = name
newObserver.block = block
newObserver.sender = obj
_observersLock.synchronized({
_observers.append(newObserver)
})
return object
}
}
|
apache-2.0
|
4238712b65ccf38600285030fa8d04cd
| 33.450216 | 174 | 0.624026 | 4.882209 | false | false | false | false |
malaonline/iOS
|
mala-ios/View/TeacherDetail/TeacherDetailsHeaderView.swift
|
1
|
11958
|
//
// TeacherDetailsHeaderView.swift
// mala-ios
//
// Created by Elors on 1/7/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
import SnapKit
import Kingfisher
import KYCircularProgress
class TeacherDetailsHeaderView: UIView {
// MARK: - Property
var model: TeacherDetailModel = TeacherDetailModel() {
didSet {
/// 教师头像URL
avatarView.setImage(withURL: model.avatar)
/// 教师姓名
nameLabel.text = model.name
nameLabel.sizeToFit()
/// 教师性别
if model.gender == "f" {
genderIcon.image = UIImage(asset: .genderFemale)
}else if model.gender == "m" {
genderIcon.image = UIImage(asset: .genderMale)
}else {
genderIcon.image = UIImage(asset: .none)
}
/// 教授学科
subjectLabel.text = model.subject
/// 价格
priceLabel.text = String(MinPrice: model.min_price.money, MaxPrice: model.max_price.money)
/// 教龄
teachingAgeLabel.text = model.teachingAgeString
teachingAgeProgressBar.progress = Double(model.teaching_age)/20
/// 级别
levelLabel.text = String(format: "T%d", model.level)
levelProgressBar.progress = Double(model.level)/10
}
}
// MARK: - Components
/// 内部控件容器(注意本类继承于 UIView 而非 UITableViewCell)
private lazy var contentView: UIView = {
let view = UIView(UIColor.white)
return view
}()
/// 头像显示控件
private lazy var avatarView: UIImageView = {
let imageView = UIImageView(imageName: "avatar_placeholder")
imageView.layer.cornerRadius = (MalaLayout_AvatarSize-5)*0.5
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.enableOneTapToLaunchPhotoBrowser()
return imageView
}()
/// 头像背景
private lazy var avatarBackground: UIView = {
let view = UIView(UIColor.white)
view.layer.cornerRadius = MalaLayout_AvatarSize*0.5
view.layer.masksToBounds = true
return view
}()
/// 会员图标显示控件
private lazy var vipIconView: UIImageView = {
let imageView = UIImageView(imageName: "vip_icon")
imageView.layer.cornerRadius = MalaLayout_VipIconSize*0.5
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = 1.0
imageView.layer.borderColor = UIColor.white.cgColor
return imageView
}()
/// 老师姓名label
private lazy var nameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
/// 老师性别Icon
private lazy var genderIcon: UIImageView = {
let imageView = UIImageView(imageName: "gender_female")
return imageView
}()
/// 科目label
private lazy var subjectLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor(named: .HeaderTitle)
label.font = UIFont.systemFont(ofSize: 12)
return label
}()
/// 价格label
private lazy var priceLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor(named: .HeaderTitle)
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .left
return label
}()
/// 分割线
private lazy var separatorLine: UIView = {
let view = UIView(UIColor(named: .SeparatorLine))
return view
}()
/// 教龄进度条
private lazy var teachingAgeProgressBar: KYCircularProgress = {
let progress = KYCircularProgress(frame: CGRect(x: 0, y: 0, width: 50, height: 50), showGuide: true)
progress.lineWidth = 2.5
progress.guideLineWidth = 2.5
progress.colors = [UIColor(named: .TeachingAgeRed)]
progress.guideColor = UIColor(named: .ProgressGray)
progress.startAngle = -Double.pi / 2
progress.endAngle = -Double.pi / 2
progress.progress = 0.35
return progress
}()
/// 教龄图标
private lazy var teachingAgeIcon: UIImageView = {
let imageView = UIImageView(imageName: "teachingAge_icon")
return imageView
}()
/// 教龄文字标签
private lazy var teachingAgeString: UILabel = {
let label = UILabel(
text: "教龄",
fontSize: 14,
textColor: UIColor(named: .HeaderTitle)
)
return label
}()
/// 教龄标签
private lazy var teachingAgeLabel: UILabel = {
let label = UILabel(
text: "0年",
fontSize: 14,
textColor: UIColor(named: .HeaderTitle)
)
return label
}()
/// 级别进度条
private lazy var levelProgressBar: KYCircularProgress = {
let progress = KYCircularProgress(frame: CGRect(x: 0, y: 0, width: 50, height: 50), showGuide: true)
progress.lineWidth = 2.5
progress.guideLineWidth = 2.5
progress.colors = [UIColor(named: .LevelYellow)]
progress.guideColor = UIColor(named: .ProgressGray)
progress.startAngle = -Double.pi / 2
progress.endAngle = -Double.pi / 2
progress.progress = 0.35
return progress
}()
/// 级别图标
private lazy var levelIcon: UIImageView = {
let imageView = UIImageView(imageName: "level_icon")
return imageView
}()
/// 级别文字标签
private lazy var levelString: UILabel = {
let label = UILabel(
text: "级别",
fontSize: 14,
textColor: UIColor(named: .HeaderTitle)
)
return label
}()
/// 级别标签
private lazy var levelLabel: UILabel = {
let label = UILabel(
text: "T1",
fontSize: 14,
textColor: UIColor(named: .HeaderTitle)
)
return label
}()
// MARK: - Instance Method
override init(frame: CGRect) {
super.init(frame: frame)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// Style
self.backgroundColor = UIColor.clear
// SubViews
addSubview(contentView)
contentView.addSubview(avatarBackground)
contentView.addSubview(avatarView)
contentView.addSubview(vipIconView)
contentView.addSubview(nameLabel)
contentView.addSubview(genderIcon)
contentView.addSubview(subjectLabel)
contentView.addSubview(priceLabel)
contentView.addSubview(separatorLine)
contentView.addSubview(teachingAgeProgressBar)
contentView.addSubview(teachingAgeIcon)
contentView.addSubview(teachingAgeString)
contentView.addSubview(teachingAgeLabel)
contentView.addSubview(levelProgressBar)
contentView.addSubview(levelIcon)
contentView.addSubview(levelString)
contentView.addSubview(levelLabel)
// Autolayout
contentView.snp.makeConstraints({ (maker) -> Void in
maker.left.equalTo(self)
maker.right.equalTo(self)
maker.bottom.equalTo(self)
maker.height.equalTo(MalaLayout_DetailHeaderContentHeight)
})
avatarBackground.snp.makeConstraints { (maker) in
maker.left.equalTo(contentView).offset(12)
maker.bottom.equalTo(separatorLine.snp.top).offset(-7)
maker.width.equalTo(MalaLayout_AvatarSize)
maker.height.equalTo(MalaLayout_AvatarSize)
}
avatarView.snp.makeConstraints({ (maker) -> Void in
maker.center.equalTo(avatarBackground)
maker.size.equalTo(avatarBackground).offset(-5)
})
vipIconView.snp.makeConstraints({ (maker) -> Void in
maker.right.equalTo(avatarView).offset(-3)
maker.bottom.equalTo(avatarView).offset(-3)
maker.width.equalTo(MalaLayout_VipIconSize)
maker.height.equalTo(MalaLayout_VipIconSize)
})
nameLabel.snp.makeConstraints({ (maker) -> Void in
maker.top.equalTo(contentView).offset(12)
maker.left.equalTo(avatarView.snp.right).offset(12)
maker.height.equalTo(16)
})
genderIcon.snp.makeConstraints({ (maker) -> Void in
maker.centerY.equalTo(nameLabel)
maker.left.equalTo(nameLabel.snp.right).offset(12)
maker.width.equalTo(13)
maker.height.equalTo(13)
})
subjectLabel.snp.makeConstraints({ (maker) -> Void in
maker.top.equalTo(nameLabel.snp.bottom).offset(8)
maker.left.equalTo(nameLabel)
maker.width.equalTo(36)
maker.height.equalTo(12)
})
priceLabel.snp.makeConstraints({ (maker) -> Void in
maker.top.equalTo(nameLabel.snp.bottom).offset(8)
maker.left.equalTo(subjectLabel.snp.right).offset(12)
maker.right.equalTo(contentView).offset(-12)
maker.height.equalTo(12)
})
separatorLine.snp.makeConstraints { (maker) in
maker.top.equalTo(subjectLabel.snp.bottom).offset(10)
maker.height.equalTo(MalaScreenOnePixel)
maker.left.equalTo(contentView).offset(12)
maker.right.equalTo(contentView).offset(-12)
}
teachingAgeProgressBar.snp.makeConstraints { (maker) in
maker.top.equalTo(separatorLine.snp.bottom).offset(20)
maker.width.equalTo(50)
maker.height.equalTo(50)
maker.right.equalTo(contentView).multipliedBy(0.25)
maker.bottom.equalTo(contentView).offset(-20)
}
teachingAgeIcon.snp.makeConstraints { (maker) in
maker.center.equalTo(teachingAgeProgressBar)
maker.width.equalTo(23)
maker.height.equalTo(23)
}
teachingAgeString.snp.makeConstraints { (maker) in
maker.width.equalTo(30)
maker.height.equalTo(14)
maker.left.equalTo(teachingAgeProgressBar.snp.right).offset(12)
maker.bottom.equalTo(teachingAgeProgressBar.snp.centerY).offset(-5)
}
teachingAgeLabel.snp.makeConstraints { (maker) in
maker.width.equalTo(65)
maker.height.equalTo(14)
maker.left.equalTo(teachingAgeProgressBar.snp.right).offset(12)
maker.top.equalTo(teachingAgeProgressBar.snp.centerY).offset(5)
}
levelProgressBar.snp.makeConstraints { (maker) in
maker.top.equalTo(separatorLine.snp.bottom).offset(20)
maker.width.equalTo(50)
maker.height.equalTo(50)
maker.right.equalTo(contentView).multipliedBy(0.75)
}
levelIcon.snp.makeConstraints { (maker) in
maker.center.equalTo(levelProgressBar)
maker.width.equalTo(23)
maker.height.equalTo(23)
}
levelString.snp.makeConstraints { (maker) in
maker.width.equalTo(30)
maker.height.equalTo(14)
maker.left.equalTo(levelProgressBar.snp.right).offset(12)
maker.bottom.equalTo(levelProgressBar.snp.centerY).offset(-5)
}
levelLabel.snp.makeConstraints { (maker) in
maker.width.equalTo(65)
maker.height.equalTo(14)
maker.left.equalTo(levelProgressBar.snp.right).offset(12)
maker.top.equalTo(levelProgressBar.snp.centerY).offset(5)
}
}
deinit {
println("TeacherDetailsHeaderView Deinit")
}
}
|
mit
|
02daa129ad4f0c857c389e839626fd90
| 34.862385 | 108 | 0.60365 | 4.442045 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.