repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
KhunLam/Swift_weibo | LKSwift_weibo/LKSwift_weibo/Classes/Module/Home/View/cell/LKStatusTopView.swift | 1 | 3971 | //
// LKStatusTopView.swift
// LKSwift_weibo
//
// Created by lamkhun on 15/11/3.
// Copyright © 2015年 lamKhun. All rights reserved.
//
import UIKit
//头部用户信息 View
class LKStatusTopView: UIView {
// MARK: - 微博模型
var statusUser: LKStatus? {
didSet {
// 用户头像
if let iconUrl = statusUser?.user?.profile_image_url {
iconView.lk_setImageWithURL(NSURL(string: iconUrl))
}
// 名称
nameLabel.text = statusUser?.user?.name
// 时间
timeLabel.text = statusUser?.created_at
// 来源
// sourceLabel.text = "来自 \(status?.source) 微博"
sourceLabel.text = "来自 ** 微博"
// 认证类型
// 判断类型设置不同的图片
// 没有认证:-1 认证用户:0 企业认证:2,3,5 达人:220
verifiedView.image = statusUser?.user?.verifiedTypeImage
// 会员等级
memberView.image = statusUser?.user?.mbrankImage
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
// backgroundColor = UIColor.redColor()
prepareUI()
}
// MARK: - 准备UI
func prepareUI() {
// 添加子控件
addSubview(topSeparatorView)
addSubview(iconView)
addSubview(nameLabel)
addSubview(timeLabel)
addSubview(sourceLabel)
addSubview(verifiedView)
addSubview(memberView)
// 添加约束
/// 头像视图
// 添加约束
topSeparatorView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.width(), height: 10))
iconView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topSeparatorView, size: CGSize(width: 35, height: 35), offset: CGPoint(x: StatusCellMargin, y: StatusCellMargin))
/// 名称
nameLabel.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: StatusCellMargin, y: 0))
/// 时间
timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: StatusCellMargin, y: 0))
/// 来源
sourceLabel.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: StatusCellMargin, y: 0))
/// 会员等级
memberView.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: nameLabel, size: CGSize(width: 14, height: 14), offset: CGPoint(x: StatusCellMargin, y: 0))
/// 认证图标
verifiedView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: CGSize(width: 17, height: 17), offset: CGPoint(x: 8.5, y: 8.5))
}
// MARK: - 懒加载
/// 顶部分割视图
private lazy var topSeparatorView: UIView = {
let view = UIView()
// 背景
view.backgroundColor = UIColor(white: 0.9, alpha: 1)
return view
}()
/// 用户头像
private lazy var iconView = UIImageView()
/// 用户名称
private lazy var nameLabel: UILabel = UILabel(fonsize: 14, textColor: UIColor.darkGrayColor())
/// 时间label
private lazy var timeLabel: UILabel = UILabel(fonsize: 9, textColor: UIColor.orangeColor())
/// 来源
private lazy var sourceLabel: UILabel = UILabel(fonsize: 9, textColor: UIColor.lightGrayColor())
/// 认证图标
private lazy var verifiedView = UIImageView()
/// 会员等级
private lazy var memberView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
}
| apache-2.0 | bb66eba368d38ad2bf89b547631674da | 29.983333 | 190 | 0.587144 | 4.33839 | false | false | false | false |
Higgcz/Buildasaur | BuildaGitServer/GitHubEntity.swift | 8 | 1454 | //
// GitHubEntity.swift
// Buildasaur
//
// Created by Honza Dvorsky on 13/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Foundation
public protocol GitHub {
init(json: NSDictionary)
}
public class GitHubEntity : GitHub {
public let htmlUrl: String?
public let url: String?
public let id: Int?
//initializer which takes a dictionary and fills in values for recognized keys
public required init(json: NSDictionary) {
self.htmlUrl = json.optionalStringForKey("html_url")
self.url = json.optionalStringForKey("url")
self.id = json.optionalIntForKey("id")
}
public init() {
self.htmlUrl = nil
self.url = nil
self.id = nil
}
public func dictionarify() -> NSDictionary {
assertionFailure("Must be overriden by subclasses that wish to dictionarify their data")
return NSDictionary()
}
public class func optional<T: GitHubEntity>(json: NSDictionary?) -> T? {
if let json = json {
return T(json: json)
}
return nil
}
}
//parse an array of dictionaries into an array of parsed entities
public func GitHubArray<T where T:GitHub>(jsonArray: NSArray!) -> [T] {
let array = jsonArray as! [NSDictionary]!
let parsed = array.map {
(json: NSDictionary) -> (T) in
return T(json: json)
}
return parsed
}
| mit | a991c9f98bb0a18ce678450f264a2e46 | 23.233333 | 96 | 0.61967 | 4.301775 | false | false | false | false |
couchbase/couchbase-lite-ios | Swift/Tests/TLSIdentityTest.swift | 1 | 16310 | //
// TLSIdentityTest.swift
// CouchbaseLite
//
// Copyright (c) 2020 Couchbase, Inc. All rights reserved.
//
// Licensed under the Couchbase License Agreement (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
import CouchbaseLiteSwift
@available(macOS 10.12, iOS 10.3, *)
class TLSIdentityTest: CBLTestCase {
let serverCertLabel = "CBL-Swift-Server-Cert"
let clientCertLabel = "CBL-Swift-Client-Cert"
func findInKeyChain(params: [String: Any]) -> CFTypeRef? {
var result: CFTypeRef?
let status = SecItemCopyMatching(params as CFDictionary, &result)
if status != errSecSuccess {
if status == errSecItemNotFound {
return nil
} else {
print("Couldn't get an item from the Keychain: \(params) (error: \(status)")
}
}
XCTAssert(result != nil)
return result
}
func publicKeyHashFromCert(cert: SecCertificate) -> Data {
var trust: SecTrust?
let status = SecTrustCreateWithCertificates(cert, SecPolicyCreateBasicX509(), &trust)
XCTAssertEqual(status, errSecSuccess)
XCTAssertNotNil(trust)
let publicKey = SecTrustCopyPublicKey(trust!)
XCTAssertNotNil(publicKey)
let attrs = SecKeyCopyAttributes(publicKey!) as! [String: Any]
let hash = attrs[String(kSecAttrApplicationLabel)] as! Data
return hash
}
func checkIdentityInKeyChain(identity: TLSIdentity) {
// Cert:
let certs = identity.certs
XCTAssert(certs.count > 0)
let cert = certs[0]
// Private Key:
let publicKeyHash = publicKeyHashFromCert(cert: cert)
let privateKey = findInKeyChain(params: [
String(kSecClass): kSecClassKey,
String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
String(kSecAttrKeyClass): kSecAttrKeyClassPrivate,
String(kSecAttrApplicationLabel): publicKeyHash,
String(kSecReturnRef): true
]) as! SecKey?
XCTAssertNotNil(privateKey)
// Get public key from cert via trust:
var trust: SecTrust?
let status = SecTrustCreateWithCertificates(cert, SecPolicyCreateBasicX509(), &trust)
XCTAssertEqual(status, errSecSuccess)
XCTAssertNotNil(trust)
let publicKey = SecTrustCopyPublicKey(trust!)
XCTAssertNotNil(publicKey)
// Check public key data:
var error: Unmanaged<CFError>?
let data = SecKeyCopyExternalRepresentation(publicKey!, &error) as Data?
XCTAssertNil(error)
XCTAssertNotNil(data)
XCTAssert(data!.count > 0)
}
func store(privateKey: SecKey, certs: [SecCertificate], label: String) {
XCTAssert(certs.count > 0)
// Private Key:
store(privateKey: privateKey)
// Certs:
var i = 0;
for cert in certs {
store(cert: cert, label: (i == 0 ? label : nil))
i = i + 1
}
}
func store(privateKey: SecKey) {
let params: [String : Any] = [
String(kSecClass): kSecClassKey,
String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
String(kSecAttrKeyClass): kSecAttrKeyClassPrivate,
String(kSecValueRef): privateKey
]
let status = SecItemAdd(params as CFDictionary, nil)
XCTAssertEqual(status, errSecSuccess)
}
func store(cert: SecCertificate, label: String?) {
var params: [String : Any] = [
String(kSecClass): kSecClassCertificate,
String(kSecValueRef): cert
]
if let l = label {
params[String(kSecAttrLabel)] = l
}
let status = SecItemAdd(params as CFDictionary, nil)
XCTAssertEqual(status, errSecSuccess)
}
func update(cert: SecCertificate, label: String) {
let query: [String : Any] = [
String(kSecClass): kSecClassCertificate,
String(kSecValueRef): cert
]
let update: [String: Any] = [
String(kSecClass): kSecClassCertificate,
String(kSecValueRef): cert,
String(kSecAttrLabel): label
]
let status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
XCTAssertEqual(status, errSecSuccess)
}
override func setUp() {
super.setUp()
if (!keyChainAccessAllowed) { return }
try! TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
try! TLSIdentity.deleteIdentity(withLabel: clientCertLabel)
}
override func tearDown() {
super.tearDown()
if (!keyChainAccessAllowed) { return }
try! TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
try! TLSIdentity.deleteIdentity(withLabel: clientCertLabel)
}
func testCreateGetDeleteServerIdentity() throws {
if (!keyChainAccessAllowed) { return }
// Delete:
try TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
// Get:
var identity: TLSIdentity?
expectError(domain: CBLError.domain, code: CBLError.notFound) {
identity = try TLSIdentity.identity(withLabel: self.serverCertLabel)
}
// Create:
let attrs = [certAttrCommonName: "CBL-Server"]
identity = try TLSIdentity.createIdentity(forServer: true,
attributes: attrs,
expiration: nil,
label: serverCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 1)
checkIdentityInKeyChain(identity: identity!)
// Get:
identity = try TLSIdentity.identity(withLabel: serverCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 1)
checkIdentityInKeyChain(identity: identity!)
// Delete:
try TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
// Get:
expectError(domain: CBLError.domain, code: CBLError.notFound) {
identity = try TLSIdentity.identity(withLabel: self.serverCertLabel)
}
}
func testCreateDuplicateServerIdentity() throws {
if (!keyChainAccessAllowed) { return }
// Create:
var identity: TLSIdentity?
let attrs = [certAttrCommonName: "CBL-Server"]
identity = try TLSIdentity.createIdentity(forServer: true,
attributes: attrs,
expiration: nil,
label: serverCertLabel)
XCTAssertNotNil(identity)
checkIdentityInKeyChain(identity: identity!)
// Get:
identity = try TLSIdentity.identity(withLabel: serverCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 1)
checkIdentityInKeyChain(identity: identity!)
// Create again with the same label:
self.expectError(domain: CBLError.domain, code: CBLError.crypto) {
identity = try TLSIdentity.createIdentity(forServer: true,
attributes: attrs,
expiration: nil,
label: self.serverCertLabel)
}
}
func testCreateGetDeleteClientIdentity() throws {
if (!keyChainAccessAllowed) { return }
// Delete:
try TLSIdentity.deleteIdentity(withLabel: clientCertLabel)
// Get:
var identity: TLSIdentity?
expectError(domain: CBLError.domain, code: CBLError.notFound) {
identity = try TLSIdentity.identity(withLabel: self.clientCertLabel)
}
// Create:
let attrs = [certAttrCommonName: "CBL-Client"]
identity = try TLSIdentity.createIdentity(forServer: false,
attributes: attrs,
expiration: nil,
label: clientCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 1)
checkIdentityInKeyChain(identity: identity!)
// Get:
identity = try TLSIdentity.identity(withLabel: clientCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 1)
checkIdentityInKeyChain(identity: identity!)
// Delete:
try TLSIdentity.deleteIdentity(withLabel: clientCertLabel)
// Get:
expectError(domain: CBLError.domain, code: CBLError.notFound) {
identity = try TLSIdentity.identity(withLabel: self.clientCertLabel)
}
}
func testCreateDuplicateClientIdentity() throws {
if (!keyChainAccessAllowed) { return }
// Create:
var identity: TLSIdentity?
let attrs = [certAttrCommonName: "CBL-Client"]
identity = try TLSIdentity.createIdentity(forServer: false,
attributes: attrs,
expiration: nil,
label: clientCertLabel)
XCTAssertNotNil(identity)
checkIdentityInKeyChain(identity: identity!)
// Get:
identity = try TLSIdentity.identity(withLabel: clientCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 1)
checkIdentityInKeyChain(identity: identity!)
// Create again with the same label:
self.expectError(domain: CBLError.domain, code: CBLError.crypto) {
identity = try TLSIdentity.createIdentity(forServer: false,
attributes: attrs,
expiration: nil,
label: self.clientCertLabel)
}
}
func testGetIdentityWithIdentity() throws {
if (!keyChainAccessAllowed) { return }
// Use SecPKCS12Import to import the PKCS12 data:
var result : CFArray?
var status = errSecSuccess
let data = try dataFromResource(name: "identity/certs", ofType: "p12")
let options = [String(kSecImportExportPassphrase): "123"]
ignoreException {
status = SecPKCS12Import(data as CFData, options as CFDictionary, &result)
}
XCTAssertEqual(status, errSecSuccess)
// Identity:
let importedItems = result! as NSArray
XCTAssert(importedItems.count > 0)
let item = importedItems[0] as! [String: Any]
let secIdentity = item[String(kSecImportItemIdentity)] as! SecIdentity
// Private Key:
var privateKey : SecKey?
status = SecIdentityCopyPrivateKey(secIdentity, &privateKey)
XCTAssertEqual(status, errSecSuccess)
// Certs:
let certs = item[String(kSecImportItemCertChain)] as! [SecCertificate]
XCTAssertEqual(certs.count, 2)
// For iOS, need to save the identity into the KeyChain.
// Save or Update identity with a label so that it could be cleaned up easily:
#if os(iOS)
store(privateKey: privateKey!, certs: certs, label: serverCertLabel)
#else
update(cert: certs[0] as SecCertificate, label: serverCertLabel)
#endif
// Get identity:
let identity = try TLSIdentity.identity(withIdentity: secIdentity, certs: [certs[1]])
XCTAssertNotNil(identity)
XCTAssertEqual(identity.certs.count, 2)
// Delete from KeyChain:
try TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
}
func testImportIdentity() throws {
if (!keyChainAccessAllowed) { return }
// Delete:
try TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
let data = try dataFromResource(name: "identity/certs", ofType: "p12")
var identity: TLSIdentity?
// When importing P12 file on macOS unit test, there is an internal exception thrown
// inside SecPKCS12Import() which doesn't actually cause anything. Ignore the exception
// so that the exception breakpoint will not be triggered.
ignoreException {
identity = try TLSIdentity.importIdentity(withData: data,
password: "123",
label: self.serverCertLabel)
}
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 2)
checkIdentityInKeyChain(identity: identity!)
// Get:
identity = try TLSIdentity.identity(withLabel: serverCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 2)
checkIdentityInKeyChain(identity: identity!)
// Delete:
try TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
// Get:
expectError(domain: CBLError.domain, code: CBLError.notFound) {
identity = try TLSIdentity.identity(withLabel: self.serverCertLabel)
}
}
func testCreateIdentityWithNoAttributes() throws {
if (!keyChainAccessAllowed) { return }
// Delete:
try TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
// Get:
var identity: TLSIdentity?
expectError(domain: CBLError.domain, code: CBLError.notFound) {
identity = try TLSIdentity.identity(withLabel: self.serverCertLabel)
}
XCTAssertNil(identity)
// Create:
self.expectError(domain: CBLError.domain, code: CBLError.crypto) {
identity = try TLSIdentity.createIdentity(forServer: false,
attributes: [:],
expiration: nil,
label: self.clientCertLabel)
}
}
func testCertificateExpiration() throws {
if (!keyChainAccessAllowed) { return }
// Delete:
try TLSIdentity.deleteIdentity(withLabel: serverCertLabel)
// Get:
var identity: TLSIdentity?
expectError(domain: CBLError.domain, code: CBLError.notFound) {
identity = try TLSIdentity.identity(withLabel: self.serverCertLabel)
}
let attrs = [certAttrCommonName: "CBL-Server"]
let expiration = Date(timeIntervalSinceNow: 300)
identity = try TLSIdentity.createIdentity(forServer: true,
attributes: attrs,
expiration: expiration,
label: serverCertLabel)
XCTAssertNotNil(identity)
XCTAssertEqual(identity!.certs.count, 1)
checkIdentityInKeyChain(identity: identity!)
// The actual expiration will be slightly less than the set expiration time:
XCTAssert(abs(expiration.timeIntervalSince1970 - identity!.expiration.timeIntervalSince1970) < 5.0)
}
}
| apache-2.0 | 37ae84ada79e38db83810dbbb59d01bc | 38.301205 | 107 | 0.576701 | 5.358081 | false | false | false | false |
gyro-n/PaymentsIos | GyronPayments/Classes/Resources/ApplicationTokenResource.swift | 1 | 6721 | //
// ApplicationTokenResource.swift
// GyronPayments
//
// Created by David Ye on 2017/09/20.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
import PromiseKit
/**
ApplicationTokenListRequestData is a class that defines the request pararmeters that is used to get a list of application tokens.
*/
open class ApplicationTokenListRequestData: ExtendedAnyObject, RequestDataDelegate, SortRequestDelegate, PaginationRequestDelegate {
/**
The sort order for the list (ASC or DESC)
*/
public var sortOrder: String?
/**
The property name to sort by
*/
public var sortBy: String?
/**
The desired page no
*/
public var page: Int?
/**
The desired page size of the returning data set
*/
public var pageSize: Int?
/**
Whether or not the application token is active
*/
public var active: Bool?
/**
The processing mode (live, test)
*/
public var mode: ProcessingMode?
public init(sortOrder: String? = nil,
sortBy: String? = "created_on",
page: Int? = nil,
pageSize: Int? = nil,
active: Bool? = nil,
mode: ProcessingMode? = nil) {
self.sortOrder = sortOrder
self.sortBy = sortBy
self.page = page
self.pageSize = pageSize
self.active = active
self.mode = mode
}
public func convertToMap() -> RequestData {
return convertToRequestData()
}
}
/**
The ApplicationTokenCreateRequestData class is used to define the parameters used to create an application token.
*/
open class ApplicationTokenCreateRequestData: ExtendedAnyObject, RequestDataDelegate {
/**
The processing mode (live, test)
*/
public var mode: String
/**
The domains for the application token
*/
public var domains: [String]?
public init(mode: ProcessingMode,
domains: [String]? = nil) {
self.mode = mode.rawValue
self.domains = domains
}
public func convertToMap() -> RequestData {
return convertToRequestData()
}
}
/**
The ApplicationTokenUpdateRequestData class is used to define the parameters to update an application token.
*/
open class ApplicationTokenUpdateRequestData: ExtendedAnyObject, RequestDataDelegate {
/**
The domains for the application token
*/
public var domains: [String]?
public init(domains: [String]? = nil) {
self.domains = domains
}
public func convertToMap() -> RequestData {
return convertToRequestData()
}
}
/**
The ApplicationTokenResource class is used to perform operations related to the management of application tokens.
*/
open class ApplicationTokenResource: BaseResource {
/**
The base root path for the request url
*/
let basePath: String = ""
/**
The parameters that are requried in order to make the request for a particular route
*/
public let requiredParams: [String] = ["mode"]
///---------------------------
/// @name Routes
///---------------------------
/**
Gets the parameters to be appended to the end of the base url
*/
public func getPathParams(storeId: String?, appTokenId: String?) -> PathParamsData? {
var pathParams: PathParamsData? = nil
if let sId = storeId {
let id = appTokenId ?? ""
pathParams = PathParamsData([("stores", sId), ("app_tokens", id)])
}
return pathParams
}
/**
Lists the application tokens available based on the store id.
@param storeId the store id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the application tokens list
*/
public func list(storeId: String, data: ApplicationTokenListRequestData?, callback: ResponseCallback<ApplicationTokens>?) -> Promise<ApplicationTokens> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, appTokenId: nil)
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: basePath, pathParams: pathParams, data: data, callback: callback)
}
/**
Creates an application token for the store id
@param storeId the store id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the application token
*/
public func create(storeId: String,data: ApplicationTokenCreateRequestData?, callback: ResponseCallback<ApplicationToken>?) -> Promise<ApplicationToken> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, appTokenId: nil)
return self.runRoute(requiredParams: requiredParams, method: HttpProtocol.HTTPMethod.POST, path: basePath, pathParams: pathParams, data: data, callback: callback)
}
/**
Updates an application token for the store id.
@param storeId the store id
@param id the application token id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the application token
*/
public func update(storeId: String?, id: String, data: ApplicationTokenUpdateRequestData?, callback: ResponseCallback<ApplicationToken>?) -> Promise<ApplicationToken> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, appTokenId: id)
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.PATCH, path: basePath, pathParams: pathParams, data: data, callback: callback)
}
/**
Deletes an application token based on the store id.
@param storeId the store id
@param id the application token id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the application token (But would be empty regardless of outcome)
*/
public func delete(storeId: String, id: String, callback: ResponseCallback<ApplicationToken>?) -> Promise<ApplicationToken> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, appTokenId: id)
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.DELETE, path: basePath, pathParams: pathParams, data: nil, callback: callback)
}
}
| mit | d3e2e747f792f12fdafa72a66c1ae0a1 | 33.461538 | 172 | 0.662202 | 4.95941 | false | false | false | false |
mhaslett/getthegist | CocoaPods-master/examples/Alamofire Example/Example/DetailViewController.swift | 1 | 5162 | // DetailViewController.swift
//
// Copyright (c) 2014 Alamofire (http://alamofire.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Alamofire
class DetailViewController: UITableViewController {
enum Sections: Int {
case Headers, Body
}
var request: Alamofire.Request? {
didSet {
oldValue?.cancel()
self.title = self.request?.description
self.refreshControl?.endRefreshing()
self.headers.removeAll()
self.body = nil
self.elapsedTime = nil
}
}
var headers: [String: String] = [:]
var body: String?
var elapsedTime: NSTimeInterval?
override func awakeFromNib() {
super.awakeFromNib()
self.refreshControl?.addTarget(self, action: #selector(DetailViewController.refresh), forControlEvents: .ValueChanged)
}
// MARK: - UIViewController
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.refresh()
}
// MARK: - IBAction
@IBAction func refresh() {
if self.request == nil {
return
}
self.refreshControl?.beginRefreshing()
let start = CACurrentMediaTime()
self.request?.response
self.request?.responseString { response in
let end = CACurrentMediaTime()
self.elapsedTime = end - start
response.response?.allHeaderFields.forEach { field, value in
self.headers["\(field)"] = "\(value)"
}
switch response.result {
case let .Success(body):
self.body = body
default:
break
}
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Sections(rawValue: section)! {
case .Headers:
return self.headers.count
case .Body:
return self.body == nil ? 0 : 1
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch Sections(rawValue: indexPath.section)! {
case .Headers:
let cell = self.tableView.dequeueReusableCellWithIdentifier("Header")! as UITableViewCell
let field = Array(self.headers.keys).sort(<)[indexPath.row]
let value = self.headers[field]
cell.textLabel!.text = field
cell.detailTextLabel!.text = value
return cell
case .Body:
let cell = self.tableView.dequeueReusableCellWithIdentifier("Body")! as UITableViewCell
cell.textLabel!.text = self.body
return cell
}
}
// MARK: UITableViewDelegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String {
if self.tableView(tableView, numberOfRowsInSection: section) == 0 {
return ""
}
switch Sections(rawValue: section)! {
case .Headers:
return "Headers"
case .Body:
return "Body"
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch Sections(rawValue: indexPath.section)! {
case .Body:
return 300
default:
return tableView.rowHeight
}
}
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String {
if Sections(rawValue: section)! == .Body && self.elapsedTime != nil {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
return "Elapsed Time: \(numberFormatter.stringFromNumber(self.elapsedTime!)) sec"
}
return ""
}
}
| gpl-3.0 | 082dcbbbd98d35a5de10a141676dfcfc | 30.284848 | 126 | 0.633088 | 5.288934 | false | false | false | false |
GYLibrary/A_Y_T | GYVideo/Pods/EZPlayer/EZPlayer/EZPlayerNotification.swift | 1 | 3327 | //
// EZPlayerNotification.swift
// EZPlayer
//
// Created by yangjun zhu on 2016/12/28.
// Copyright © 2016年 yangjun zhu. All rights reserved.
//
import Foundation
public extension Notification.Name {
//
static let EZPlayerHeartbeat = Notification.Name(rawValue: "com.ezplayer.EZPlayerHeartbeat")
static let EZPlayerPlaybackTimeDidChange = Notification.Name(rawValue: "com.ezplayer.EZPlayerPlaybackTimeDidChange")
static let EZPlayerStatusDidChange = Notification.Name(rawValue: "com.ezplayer.EZPlayerStatusDidChange")
static let EZPlayerLoadingDidChange = Notification.Name(rawValue: "com.ezplayer.EZPlayerLoadingDidChange")
// static let EZPlayeStatusDidChangeToStopped = Notification.Name(rawValue: "com.ezplayer.EZPlayeStatusDidChangeToStopped")
//
static let EZPlayerDisplayModeDidChange = Notification.Name(rawValue: "com.ezplayer.EZPlayerStatusDidChang")
//
static let EZPlayerControlsHiddenDidChange = Notification.Name(rawValue: "com.ezplayer.EZPlayerControlsHiddenDidChange")
//
static let EZPlayerThumbnailsGenerated = Notification.Name(rawValue: "com.ezplayer.EZPlayerThumbnailsGenerated")
//
// static let EZPlayeFullscreenWillAppear = Notification.Name(rawValue: "com.ezplayer.EZPlayeFullscreenWillAppear")
//
// static let EZPlayeFullscreenDidAppear = Notification.Name(rawValue: "com.ezplayer.EZPlayeFullscreenDidAppear")
//
// static let EZPlayeFullscreenWillDisappear = Notification.Name(rawValue: "com.ezplayer.EZPlayeFullscreenWillDisappear")
//
// static let EZPlayeFullscreenDidDisappear = Notification.Name(rawValue: "com.ezplayer.EZPlayeFullscreenWillDisappear")
static let EZPlayerDisplayModeChangedWillAppear = Notification.Name(rawValue: "EZPlayerDisplayModeChangedWillAppear")
static let EZPlayerDisplayModeChangedDidAppear = Notification.Name(rawValue: "EZPlayerDisplayModeChangedDidAppear")
static let EZPlayerPlaybackDidFinish = Notification.Name(rawValue: "com.ezplayer.EZPlayerPlaybackDidFinish")
// static let NLMoviePlayerIsAirPlayVideoActiveDidChangeNotification = Notification.Name(rawValue: "com.ezplayer.EZPlayerPlassybackDidFinish")
static let EZPlayerTapGestureRecognizer = Notification.Name(rawValue: "com.ezplayer.EZPlayerTapGestureRecognizer")
}
extension Notification {
struct Key {
//
static let EZPlayerStatusDidChangeKey = "EZPlayerStatusDidChangeKey"
static let EZPlayerLoadingDidChangeKey = "EZPlayerLoadingDidChangeKey"
//
static let EZPlayerDisplayModeDidChangeKey = "EZPlayerDisplayModeDidChangeKey"
//
static let EZPlayerControlsHiddenDidChangeKey = "EZPlayerControlsHiddenDidChangeKey"
static let EZPlayerControlsHiddenDidChangeByAnimatedKey = "EZPlayerControlsHiddenDidChangeByAnimatedKey"
static let EZPlayerThumbnailsKey = "EZPlayerThumbnailsKey"
static let EZPlayerDisplayModeChangedFrom = "EZPlayerDisplayModeChangedFrom"
static let EZPlayerDisplayModeChangedTo = "EZPlayerDisplayModeChangedTo"
static let EZPlayerPlaybackDidFinishReasonKey = "EZPlayerPlaybackDidFinishReasonKey"
static let EZPlayerNumberOfTaps = "EZPlayerNumberOfTaps"
static let EZPlayerTapGestureRecognizer = "EZPlayerTapGestureRecognizer"
}
}
| mit | 706cb2ba27bcacb209ac6d092d743edc | 37.651163 | 149 | 0.787906 | 4.9538 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | source/RSTBSupport/Classes/RSEnhancedInstructionStepDescriptor.swift | 1 | 1288 | //
// RSEnhancedInstructionStepDescriptor.swift
// Pods
//
// Created by James Kizer on 7/30/17.
//
//
import UIKit
import ResearchSuiteTaskBuilder
import Gloss
open class RSEnhancedInstructionStepDescriptor: RSTBInstructionStepDescriptor {
public let buttonText: String?
public let formattedTitle: RSTemplatedTextDescriptor?
public let formattedText: RSTemplatedTextDescriptor?
public let gifTitle: String?
public let gifURL: String?
public let audioTitle: String?
public let moveForwardOnTap: Bool
public let skipButtonText: String?
required public init?(json: JSON) {
self.buttonText = "buttonText" <~~ json
self.formattedTitle = "formattedTitle" <~~ json
self.formattedText = "formattedText" <~~ json
self.gifTitle = "gif" <~~ json
self.audioTitle = "audio" <~~ json
self.moveForwardOnTap = "moveForwardOnTap" <~~ json ?? false
self.skipButtonText = "skipButtonText" <~~ json
if let gifURLJSON: JSON = "gifURL" <~~ json,
let urlArray: [String] = "selectOne" <~~ gifURLJSON {
self.gifURL = urlArray.random()
}
else {
self.gifURL = "gifURL" <~~ json
}
super.init(json: json)
}
}
| apache-2.0 | 85d022b3bbe18a716928c606cb7ac904 | 27.622222 | 79 | 0.63587 | 4.395904 | false | false | false | false |
sayanee/ios-learning | Psychologist/Psychologist/DiagnosedHappinessViewController.swift | 1 | 1594 | //
// DiagnosedHappinessViewController.swift
// Psychologist
//
// Created by Sayanee Basu on 4/1/16.
// Copyright © 2016 Sayanee Basu. All rights reserved.
//
import UIKit
class DiagnosedHappinessViewController: HappinessViewController, UIPopoverPresentationControllerDelegate {
override var happiness: Int {
didSet {
diagnosticHistory += [happiness]
}
}
private let defaults = NSUserDefaults.standardUserDefaults()
var diagnosticHistory: [Int] {
get { return defaults.objectForKey(History.DefaultsKey) as? [Int] ?? [] }
set { defaults.setObject(newValue, forKey: History.DefaultsKey) }
}
private struct History {
static let SegueIdentifier = "Show Diagnostic History"
static let DefaultsKey = "DiagnosedHappinessViewController.History"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case History.SegueIdentifier:
if let tvc = segue.destinationViewController as? TextViewController {
if let ppc = tvc.popoverPresentationController {
ppc.delegate = self
}
tvc.text = "\(diagnosticHistory)"
}
default: break
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
} | mit | 18743be6db36b0b0bbe4fe5950fd2ed2 | 31.530612 | 127 | 0.637163 | 5.771739 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity | EnjoyUniversity/EnjoyUniversity/Classes/View/Community/EUCommunityAnnounceController.swift | 1 | 2029 | //
// EUCommunityAnnounceController.swift
// EnjoyUniversity
//
// Created by lip on 17/4/22.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
class EUCommunityAnnounceController: EUBaseViewController {
let announceTextView = SwiftyTextView(frame: CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: 200), textContainer: nil, placeholder: "请输入社团公告")
/// 上层传入的 社团ID
var cmid:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
navitem.title = "发布公告"
tableview.removeFromSuperview()
announceTextView.font = UIFont.boldSystemFont(ofSize: 15)
announceTextView.textColor = TEXTVIEWCOLOR
view.backgroundColor = UIColor.init(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
view.addSubview(announceTextView)
let rightBtn = UIBarButtonItem(title: "发布", style: .plain, target: nil, action: #selector(commitAnnouncement))
navitem.rightBarButtonItem = rightBtn
announceTextView.becomeFirstResponder()
}
@objc private func commitAnnouncement(){
guard let text = announceTextView.text else{
SwiftyProgressHUD.showBigFaildHUD(text: "请输入公告", duration: 1)
return
}
if text.characters.count < 1 {
SwiftyProgressHUD.showBigFaildHUD(text: "请输入公告", duration: 1)
return
}
SwiftyProgressHUD.showLoadingHUD()
EUNetworkManager.shared.changeCommunityAnnouncement(cmid: cmid, announcement: text) { (isSuccess) in
SwiftyProgressHUD.hide()
if !isSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1)
return
}
SwiftyProgressHUD.showSuccessHUD(duration: 1)
_ = self.navigationController?.popViewController(animated: true)
}
}
}
| mit | 4d8b624af1b7c0951820b210e965a1fe | 30.079365 | 161 | 0.616956 | 4.684211 | false | false | false | false |
kildevaeld/FALocationManager | Example/Tests/Tests.swift | 1 | 1096 | // https://github.com/Quick/Quick
import Quick
import Nimble
import FALocationManager
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will exentually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
| mit | a8bb1b6a7e884cd0cf8c3106a984a801 | 20.8 | 60 | 0.397248 | 5.046296 | false | false | false | false |
grafiti-io/SwiftCharts | SwiftCharts/Views/ChartPointEllipseView.swift | 3 | 2693 | //
// ChartPointEllipseView.swift
// SwiftCharts
//
// Created by ischuetz on 19/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartPointEllipseView: UIView {
open var fillColor: UIColor = UIColor.gray
open var borderColor: UIColor? = nil
open var borderWidth: CGFloat? = nil
open var animDelay: Float = 0
open var animDuration: Float = 0
open var animateSize: Bool = true
open var animateAlpha: Bool = true
open var animDamping: CGFloat = 1
open var animInitSpringVelocity: CGFloat = 1
open var touchHandler: (() -> ())?
convenience public init(center: CGPoint, diameter: CGFloat) {
self.init(center: center, width: diameter, height: diameter)
}
public init(center: CGPoint, width: CGFloat, height: CGFloat) {
super.init(frame: CGRect(x: center.x - width / 2, y: center.y - height / 2, width: width, height: height))
self.backgroundColor = UIColor.clear
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func didMoveToSuperview() {
if animDuration != 0 {
if animateSize {
transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
}
if animateAlpha {
alpha = 0
}
UIView.animate(withDuration: TimeInterval(animDuration), delay: TimeInterval(animDelay), usingSpringWithDamping: animDamping, initialSpringVelocity: animInitSpringVelocity, options: UIViewAnimationOptions(), animations: {
if self.animateSize {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
if self.animateAlpha {
self.alpha = 1
}
}, completion: nil)
}
}
override open func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {return}
let borderOffset = borderWidth ?? 0
let circleRect = (CGRect(x: borderOffset, y: borderOffset, width: frame.size.width - (borderOffset * 2), height: frame.size.height - (borderOffset * 2)))
if let borderWidth = borderWidth, let borderColor = borderColor {
context.setLineWidth(borderWidth)
context.setStrokeColor(borderColor.cgColor)
context.strokeEllipse(in: circleRect)
}
context.setFillColor(fillColor.cgColor)
context.fillEllipse(in: circleRect)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
touchHandler?()
}
}
| apache-2.0 | 1bbdc75f7a70470a111506bcde560a9d | 34.434211 | 233 | 0.617898 | 4.834829 | false | false | false | false |
DianQK/Flix | Flix/Storyboard/FlixStackItemProvider.swift | 1 | 5280 | //
// FlixStackItemProvider.swift
// Flix
//
// Created by DianQK on 24/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
open class FlixStackItemProvider: UIControl, UniqueAnimatableTableViewProvider {
public typealias Cell = UITableViewCell
// Default is nil for cells in UITableViewStylePlain, and non-nil for UITableViewStyleGrouped. The 'backgroundView' will be added as a subview behind all other views.
open var backgroundView: UIView? {
didSet {
_cell?.backgroundView = backgroundView
}
}
// Default is nil for cells in UITableViewStylePlain, and non-nil for UITableViewStyleGrouped. The 'selectedBackgroundView' will be added as a subview directly above the backgroundView if not nil, or behind all other views. It is added as a subview only when the cell is selected. Calling -setSelected:animated: will cause the 'selectedBackgroundView' to animate in and out with an alpha fade.
open var selectedBackgroundView: UIView? {
didSet {
_cell?.selectedBackgroundView = selectedBackgroundView
}
}
open var multipleSelectionBackgroundView: UIView? {
didSet {
_cell?.multipleSelectionBackgroundView = multipleSelectionBackgroundView
}
}
open var selectionStyle: UITableViewCell.SelectionStyle = UITableViewCell.SelectionStyle.default {
didSet {
_cell?.selectionStyle = selectionStyle
}
}
// default is UITableViewCellAccessoryNone. use to set standard type
open var accessoryType: UITableViewCell.AccessoryType = UITableViewCell.AccessoryType.none {
didSet {
_cell?.accessoryType = accessoryType
}
}
// if set, use custom view. ignore accessoryType. tracks if enabled can calls accessory action
open var accessoryView: UIView? {
didSet {
_cell?.accessoryView = accessoryView
}
}
// default is UITableViewCellAccessoryNone. use to set standard type
open var editingAccessoryType: UITableViewCell.AccessoryType = .none {
didSet {
_cell?.editingAccessoryType = editingAccessoryType
}
}
// if set, use custom view. ignore editingAccessoryType. tracks if enabled can calls accessory action
open var editingAccessoryView: UIView? {
didSet {
_cell?.editingAccessoryView = editingAccessoryView
}
}
// allows customization of the separator frame
open var separatorInset: UIEdgeInsets? {
didSet {
if let separatorInset = separatorInset {
_cell?.separatorInset = separatorInset
}
}
}
open var itemHeight: (() -> CGFloat?)?
private let _isHidden = BehaviorRelay(value: false)
open override var isHidden: Bool {
get {
return _isHidden.value
}
set {
_isHidden.accept(newValue)
}
}
private let disposeBag = DisposeBag()
private weak var _cell: UITableViewCell?
open func onCreate(_ tableView: UITableView, cell: UITableViewCell, indexPath: IndexPath) {
cell.selectedBackgroundView = self.selectedBackgroundView
cell.backgroundView = backgroundView
cell.accessoryType = self.accessoryType
cell.accessoryView = self.accessoryView
cell.editingAccessoryType = self.editingAccessoryType
cell.editingAccessoryView = self.editingAccessoryView
cell.multipleSelectionBackgroundView = self.multipleSelectionBackgroundView
cell.selectionStyle = self.selectionStyle
if let separatorInset = self.separatorInset {
cell.separatorInset = separatorInset
}
cell.contentView.addSubview(self)
self.translatesAutoresizingMaskIntoConstraints = false
self.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true
self.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
self.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor).isActive = true
// self.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
self._cell = cell
}
open func itemSelected(_ tableView: UITableView, indexPath: IndexPath, value: FlixStackItemProvider) {
if self.isEnabled {
self.sendActions(for: UIControl.Event.touchUpInside)
}
tableView.deselectRow(at: indexPath, animated: true)
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath, value: FlixStackItemProvider) -> CGFloat? {
return self.itemHeight?()
}
open func createValues() -> Observable<[FlixStackItemProvider]> {
return self._isHidden.asObservable()
.map { [weak self] isHidden in
guard let `self` = self, !isHidden else { return [] }
return [self]
}
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard let result = super.hitTest(point, with: event), (result !== self && result.isUserInteractionEnabled) else { return nil }
return result
}
}
| mit | 8e0ce264b26ef55c4c59894e3db86a53 | 35.916084 | 397 | 0.674181 | 5.487526 | false | false | false | false |
lzngit/SortingAlgorithms | SortingAlgorithms/SortingAlgorithms/QuickSort.swift | 1 | 3274 | //
// QuickSort.swift
// AlgorithmAccumulation
// 快速排序算法
// Created by lzn on 16/2/24.
// Copyright © 2016年 Study. All rights reserved.
//
import Foundation
/*
1.设置基准数,一般设数组第0个元素
2.重新排序数列.比较规则:所有元素比基准小的放在左边,所有元素比基准大的放在右边
排序后,基准数出在中间位置
3.递归左边小数列和右边大数列
*/
/**
三循环快速排列算法
1.从小到大排列
2.传入的数组结果直接更改到传入的数组中
- parameter sArray: 源数组
- parameter head: 头号索引
- parameter end: 尾部索引
*/
func qs_threeCirculate(inout source sArray:[Int], head: Int, end: Int) -> Void {
//如果头部数据大于等于尾部数据,说明没有需要排序的数据,直接返回结束递归
if (head >= end) {
return
}
//数组左边循环索引值
var i: Int = head
//数组右边循环索引值
var j: Int = end
//数组最左边元素为基准数据
let tmp: Int = sArray[i]
//i>=j 退出循环
while (i < j) {
//数组右边循环比较基准数,直到遇到小的数据
while((sArray[j] >= tmp) && (i < j)) {
j--
}
//把小数据放在左边位置上
sArray[i] = sArray[j]
//然后数组左边循环比较基准数,直到遇到大的数据
while((sArray[i] <= tmp)&&(i < j)) {
i++
}
//然后把大的数据放在右边位置上,原 j 停留的位置上
sArray[j] = sArray[i]
//最后把基准数据放在 i 停留的位置上
sArray[i] = tmp;
//左边小数据递归
qs_threeCirculate(source: &sArray, head: head, end: i-1)
//右边大数据递归
qs_threeCirculate(source: &sArray, head: j+1, end: end)
}
}
func qs_whileCirculate(inout source sArray:[Int], head: Int, end: Int) -> Void {
if (head >= end) {
return
}
var left = head
var right = end
let tmpData = sArray[left]
while (left < right) {
if (sArray[left+1] < tmpData) {
sArray[left] = sArray[left+1]
left++
}else {
//交换数据
if (left+1 != right) {
//swap函数不支持同地址互换(必须是两个不同地址的数据)
swap(&sArray[left+1], &sArray[right])
}
right--
}
}
sArray[left] = tmpData
qs_whileCirculate(source: &sArray, head: head, end: left-1)
qs_whileCirculate(source: &sArray, head: left+1, end: end)
}
func qs_forCirculate(inout source sArray:[Int], head: Int, end: Int) -> Void {
if (head >= end) {
return
}
var index = head
let tmpData = sArray[index]
for (var i = head+1; i <= end; i++) {
if (sArray[i] < tmpData) {
index++
if (index != i) {
//swap函数不支持同地址互换(必须是两个不同地址的数据)
swap(&sArray[index], &sArray[i])
}
}
}
swap(&sArray[index], &sArray[head])
qs_forCirculate(source: &sArray, head: head, end: index-1)
qs_forCirculate(source: &sArray, head: index+1, end: end)
}
| mit | c2c422c02886f13d1cf604db2ce6dd65 | 23.424528 | 80 | 0.533411 | 2.829508 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporterCore/ScoreReporterCore/Search/SearchViewController.swift | 1 | 8127 | //
// SearchViewController.swift
// ScoreReporter
//
// Created by Bradley Smith on 11/6/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import UIKit
import Anchorage
import KVOController
import CoreData
public typealias SearchAnimationCompletion = () -> Void
public protocol SearchViewControllerDelegate: class {
func didSelect(item: Searchable)
func didSelectCancel()
func willBeginEditing()
}
public class SearchViewController<Model: NSManagedObject>: UIViewController, KeyboardObservable where Model: Searchable {
fileprivate let dataSource: SearchDataSource<Model>
fileprivate let visualEffectView = UIVisualEffectView(effect: nil)
fileprivate let tableView = InfiniteScrollTableView(frame: .zero, style: .grouped)
fileprivate var tableViewProxy: TableViewProxy?
fileprivate var searchBarProxy: SearchBarProxy?
public let searchBar = UISearchBar(frame: .zero)
public weak var delegate: SearchViewControllerDelegate?
public init(dataSource: SearchDataSource<Model>) {
self.dataSource = dataSource
super.init(nibName: nil, bundle: nil)
tableViewProxy = TableViewProxy(dataSource: self, delegate: self)
searchBarProxy = SearchBarProxy(delegate: self)
searchBar.autocapitalizationType = .none
searchBar.autocorrectionType = .no
searchBar.spellCheckingType = .no
searchBar.placeholder = Model.searchBarPlaceholder
searchBar.tintColor = UIColor.scBlue
searchBar.delegate = searchBarProxy
let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
public override func loadView() {
view = UIView()
view.backgroundColor = UIColor.clear
configureViews()
configureLayout()
}
public override func viewDidLoad() {
super.viewDidLoad()
configureObservers()
addKeyboardObserver { [weak self] (_, keyboardFrame) in
guard let sself = self else {
return
}
let frameInWindow = sself.view.convert(sself.tableView.frame, to: nil)
let bottomInset = max(0.0, frameInWindow.maxY - keyboardFrame.minY)
self?.tableView.contentInset.bottom = bottomInset
self?.tableView.scrollIndicatorInsets.bottom = bottomInset
}
dataSource.refreshBlock = { [weak self] in
self?.tableView.reloadData()
}
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
transitionCoordinator?.animate(alongsideTransition: nil) { [weak self] _ in
self?.searchBar.becomeFirstResponder()
}
deselectRows(in: tableView, animated: animated)
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchBar.resignFirstResponder()
}
}
// MARK: - Public
public extension SearchViewController {
func beginAppearanceAnimation(completion: SearchAnimationCompletion?) {
tableView.alpha = 0.0
tableView.transform = CGAffineTransform(translationX: 0.0, y: 44.0)
let animations = {
self.visualEffectView.effect = UIBlurEffect(style: .light)
self.tableView.alpha = 1.0
self.tableView.transform = CGAffineTransform.identity
}
UIView.animate(withDuration: 0.25, animations: animations) { _ in
completion?()
}
}
func beginDisappearanceAnimation(completion: SearchAnimationCompletion?) {
let animations = {
self.visualEffectView.effect = nil
self.tableView.alpha = 0.0
self.tableView.transform = CGAffineTransform(translationX: 0.0, y: 44.0)
}
UIView.animate(withDuration: 0.25, animations: animations) { _ in
self.tableView.alpha = 1.0
self.tableView.transform = CGAffineTransform.identity
completion?()
}
}
}
// MARK: - Private
private extension SearchViewController {
func configureViews() {
view.addSubview(visualEffectView)
tableView.dataSource = tableViewProxy
tableView.delegate = tableViewProxy
tableView.register(headerFooterClass: SectionHeaderView.self)
tableView.register(cellClass: SearchCell.self)
tableView.backgroundColor = UIColor.clear
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
view.addSubview(tableView)
let image = UIImage(named: "icn-search")
let title = Model.searchEmptyTitle
let message = Model.searchEmptyMessage
let contentView = EmptyContentView(frame: .zero)
contentView.configure(withImage: image, title: title, message: message)
tableView.emptyView.set(contentView: contentView, forState: .empty)
}
func configureLayout() {
visualEffectView.edgeAnchors == edgeAnchors
tableView.edgeAnchors == edgeAnchors
}
func configureObservers() {
kvoController.observe(dataSource, keyPath: "empty") { [weak self] (empty: Bool) in
self?.tableView.empty = empty
}
}
}
// MARK: - TableViewProxyDataSource
extension SearchViewController: TableViewProxyDataSource {
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return dataSource.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let searchable = dataSource.item(at: indexPath)
let cell = tableView.dequeueCell(for: indexPath) as SearchCell
cell.configure(with: searchable)
cell.separatorHidden = indexPath.item == 0
return cell
}
}
// MARK: - TableViewProxyDelegate
extension SearchViewController: TableViewProxyDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
guard let _ = dataSource.title(for: section) else {
return 0.0
}
return SectionHeaderView.height
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let title = dataSource.title(for: section) else {
return nil
}
let headerView = tableView.dequeueHeaderFooterView() as SectionHeaderView
headerView.contentView.backgroundColor = UIColor.clear
headerView.configure(with: title)
return headerView
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
guard let searchable = dataSource.item(at: indexPath) else {
return
}
delegate?.didSelect(item: searchable)
}
}
// MARK: - SearchBarProxyDelegate
extension SearchViewController: SearchBarProxyDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
searchBar.setShowsCancelButton(false, animated: true)
searchBar.resignFirstResponder()
dataSource.search(for: nil)
delegate?.didSelectCancel()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
dataSource.search(for: searchText)
}
func searchBarTextWillBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
delegate?.willBeginEditing()
}
}
| mit | 7e95a329ea3774acdaa0fdcc1f6f05ce | 30.866667 | 121 | 0.671425 | 5.388594 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/UI/Views/Progress Indicators/PieProgressView.swift | 1 | 5370 | //
// PieChart.swift
// YourGoals
//
// Created by André Claaßen on 22.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable class PieProgressView:UIView {
// Mark : - Inspectable
/// The color of the empty progress track (gets drawn over)
@IBInspectable open var trackTintColor: UIColor {
get {
return progressLayer.trackTintColor
}
set {
progressLayer.trackTintColor = newValue
progressLayer.setNeedsDisplay()
}
}
/// progress bar color
@IBInspectable open var progressTintColor: UIColor {
get {
return progressLayer.progressTintColor
}
set {
progressLayer.progressTintColor = newValue
progressLayer.setNeedsDisplay()
}
}
/// fill bar color
@IBInspectable open var fillColor: UIColor {
get {
return progressLayer.fillColor
}
set {
progressLayer.fillColor = newValue
progressLayer.setNeedsDisplay()
}
}
/// current progress (not observed from any active animations)
@IBInspectable open var progress: CGFloat {
get {
return progressLayer.progress
}
set {
progressLayer.progress = newValue
progressLayer.setNeedsDisplay()
}
}
@IBInspectable open var clockwise: Bool {
get {
return progressLayer.clockwise
}
set {
progressLayer.clockwise = newValue
progressLayer.setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupDefaults()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupDefaults()
}
open override func didMoveToWindow() {
super.didMoveToWindow()
if let window = window {
progressLayer.contentsScale = window.screen.scale
progressLayer.setNeedsDisplay()
}
}
override func layoutSubviews() {
self.layer.setNeedsDisplay()
}
func setupDefaults() {
self.backgroundColor = UIColor.clear
}
// MARK: - Custom Base Layer
fileprivate var progressLayer: ProgressLayer! {
get {
return layer as! ProgressLayer
}
}
open override class var layerClass : AnyClass {
return ProgressLayer.self
}
}
class ProgressLayer: CALayer {
// This needs to have a setter/getter for it to work with CoreAnimation, therefore NSManaged
var progress:CGFloat = 0.3
var thicknessRatio: CGFloat = 0.1
var progressTintColor = UIColor.blue
var trackTintColor = UIColor.blue
var fillColor = UIColor.blue.withAlphaComponent(0.3)
var clockwise = true
func fillProgressIfNecessary(ctx: CGContext, centerPoint:CGPoint, radius:CGFloat, radians:CGFloat) {
guard progress >= 0.0 else {
return
}
ctx.setFillColor(progressTintColor.cgColor)
let progressPath = CGMutablePath()
progressPath.move(to: centerPoint)
let topAngle = CGFloat(3 * (Double.pi / 2))
if clockwise {
progressPath.addArc(center: centerPoint, radius: radius, startAngle: topAngle, endAngle: radians, clockwise: false )
} else {
progressPath.addArc(center: centerPoint, radius: radius, startAngle: radians, endAngle: topAngle, clockwise: true)
}
progressPath.closeSubpath()
ctx.addPath(progressPath)
ctx.fillPath()
}
func fillBackgroundCircle(ctx:CGContext, centerPoint:CGPoint, radius:CGFloat) {
let rect = CGRect(x: centerPoint.x - radius, y: centerPoint.y - radius, width: radius * 2, height: radius * 2)
ctx.setFillColor(self.fillColor.cgColor)
ctx.fillEllipse(in: rect)
}
func fillOuterCircle(ctx:CGContext, centerPoint:CGPoint, radius:CGFloat) {
let lineWidth = thicknessRatio * radius
let rect = CGRect(x: centerPoint.x - radius, y: centerPoint.y - radius, width: radius * 2, height: radius * 2).insetBy(dx: lineWidth / 2.0, dy: lineWidth / 2.0 )
ctx.setStrokeColor(trackTintColor.cgColor)
ctx.setLineWidth(lineWidth)
ctx.strokeEllipse(in: rect)
}
override func draw(in ctx: CGContext) {
let rect = bounds
let centerPoint = CGPoint(x: rect.size.width / 2, y: rect.size.height / 2)
let radius = min(rect.size.height, rect.size.width) / 2
let progressRadius = radius * (1 - thicknessRatio * 2.0)
let progress: CGFloat = min(self.progress, CGFloat(1 - Float.ulpOfOne))
// clockwise progress
let radians = clockwise ?
CGFloat((Double(progress) * 2.0 * Double.pi) - (Double.pi / 2)) :
CGFloat( 2.0 * Double.pi - (Double(progress) * 2.0 * Double.pi) - (Double.pi / 2.0))
fillProgressIfNecessary(ctx: ctx, centerPoint: centerPoint, radius: progressRadius, radians: radians)
fillBackgroundCircle(ctx: ctx, centerPoint: centerPoint, radius: radius)
fillOuterCircle(ctx: ctx, centerPoint: centerPoint, radius: radius)
}
}
| lgpl-3.0 | 02cd5ac96ce0022ca9e8c34a81fc6c87 | 30.011561 | 169 | 0.609692 | 4.82464 | false | false | false | false |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleStickerCell.swift | 1 | 8589 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
import VBFPopFlatButton
import YYImage
open class AABubbleStickerCell: AABubbleBaseFileCell {
// Views
let preview = UIImageView()
let timeBg = UIImageView()
let timeLabel = UILabel()
let statusView = UIImageView()
// Binded data
var bindedLayout: StikerCellLayout!
var contentLoaded = false
fileprivate var callback: AAFileCallback? = nil
// Constructors
public init(frame: CGRect) {
super.init(frame: frame, isFullSize: false)
timeBg.image = ActorSDK.sharedActor().style.statusBackgroundImage
timeLabel.font = UIFont.italicSystemFont(ofSize: 11)
timeLabel.textColor = appStyle.chatMediaDateColor
statusView.contentMode = UIViewContentMode.center
preview.contentMode = .scaleAspectFit
contentView.addSubview(preview)
contentView.addSubview(timeBg)
contentView.addSubview(timeLabel)
contentView.addSubview(statusView)
preview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleStickerCell.mediaDidTap)))
preview.isUserInteractionEnabled = true
contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
let longPressTap = UILongPressGestureRecognizer(target:self,action:#selector(AABubbleCell.longTap(tap:)))
self.contentView.isUserInteractionEnabled = true
self.contentView.addGestureRecognizer(longPressTap)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Binding
open override func bind(_ message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) {
self.bindedLayout = cellLayout as! StikerCellLayout
bubbleInsets = UIEdgeInsets(
top: setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop,
left: 10 + (AADevice.isiPad ? 16 : 0),
bottom: setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom,
right: 10 + (AADevice.isiPad ? 16 : 0))
if (!reuse) {
bindBubbleType(BubbleType.sticker, isCompact: false)
// Reset content state
preview.image = nil
contentLoaded = false
// Bind file
fileBind(message, autoDownload: true)
}
// Update time
timeLabel.text = cellLayout.date
// Update status
if (isOut) {
statusView.isHidden = false
switch(message.messageState.toNSEnum()) {
case .SENT:
if message.sortDate <= readDate {
self.statusView.image = appStyle.chatIconCheck2
self.statusView.tintColor = appStyle.chatStatusMediaRead
} else if message.sortDate <= receiveDate {
self.statusView.image = appStyle.chatIconCheck2
self.statusView.tintColor = appStyle.chatStatusMediaReceived
} else {
self.statusView.image = appStyle.chatIconCheck1
self.statusView.tintColor = appStyle.chatStatusMediaSent
}
break
case .ERROR:
self.statusView.image = appStyle.chatIconError
self.statusView.tintColor = appStyle.chatStatusMediaError
break
default:
self.statusView.image = appStyle.chatIconClock;
self.statusView.tintColor = appStyle.chatStatusMediaSending
break;
}
} else {
statusView.isHidden = true
}
}
// File state binding
open override func fileStateChanged(_ reference: String?, progress: Int?, isPaused: Bool, isUploading: Bool, selfGeneration: Int) {
if let r = reference {
if (contentLoaded) {
return
}
contentLoaded = true
let filePath = CocoaFiles.pathFromDescriptor(r)
let loadedContent = YYImage(contentsOfFile: filePath)
if (loadedContent == nil) {
return
}
runOnUiThread(selfGeneration, closure: { () -> () in
self.preview.image = loadedContent!
})
}
}
// Media Action
open func mediaDidTap() {
}
// Layouting
open override func layoutContent(_ maxWidth: CGFloat, offsetX: CGFloat) {
let insets = fullContentInsets
let contentWidth = self.contentView.frame.width
_ = self.contentView.frame.height
let bubbleWidth = self.bindedLayout.screenSize.width
let bubbleHeight = self.bindedLayout.screenSize.height
layoutBubble(bubbleWidth, contentHeight: bubbleHeight)
if (isOut) {
preview.frame = CGRect(x: contentWidth - insets.left - bubbleWidth, y: insets.top, width: bubbleWidth, height: bubbleHeight)
} else {
preview.frame = CGRect(x: insets.left, y: insets.top, width: bubbleWidth, height: bubbleHeight)
}
//progress.frame = CGRectMake(preview.frame.origin.x + preview.frame.width/2 - 32, preview.frame.origin.y + preview.frame.height/2 - 32, 64, 64)
timeLabel.frame = CGRect(x: 0, y: 0, width: 1000, height: 1000)
timeLabel.sizeToFit()
let timeWidth = (isOut ? 23 : 0) + timeLabel.bounds.width
let timeHeight: CGFloat = 20
timeLabel.frame = CGRect(x: preview.frame.maxX - timeWidth - 18, y: preview.frame.maxY - timeHeight - 6, width: timeLabel.frame.width, height: timeHeight)
if (isOut) {
statusView.frame = CGRect(x: timeLabel.frame.maxX, y: timeLabel.frame.minY, width: 23, height: timeHeight)
}
timeBg.frame = CGRect(x: timeLabel.frame.minX - 4, y: timeLabel.frame.minY - 1, width: timeWidth + 8, height: timeHeight + 2)
}
}
/**
Media cell layout
*/
open class StikerCellLayout: AACellLayout {
// public let fastThumb: NSData?
open let contentSize: CGSize
open let screenSize: CGSize
open let autoDownload: Bool
/**
Creting layout for media bubble
*/
public init(id: Int64, width: CGFloat, height:CGFloat, date: Int64, stickerContent: ACStickerContent?, autoDownload: Bool, layouter: AABubbleLayouter) {
// Saving content size
self.contentSize = CGSize(width: width, height: height)
// Saving autodownload flag
self.autoDownload = autoDownload
self.screenSize = CGSize(width: width, height:height)
// Prepare fast thumb
// self.fastThumb = sticker?.getFileReference256().toByteArray().toNSData()
// Creating layout
super.init(height: self.screenSize.height + 2, date: date, key: "media", layouter: layouter)
}
/**
Creating layout for sticker content
*/
public convenience init(id: Int64, stickerContent: ACStickerContent, date: Int64, layouter: AABubbleLayouter) {
self.init(id: id, width: CGFloat(150), height: CGFloat(150), date: date, stickerContent: stickerContent, autoDownload: true, layouter: layouter)
}
/**
Creating layout for message
*/
public convenience init(message: ACMessage, layouter: AABubbleLayouter) {
if let content = message.content as? ACStickerContent {
self.init(id: Int64(message.rid), stickerContent: content, date: Int64(message.date), layouter: layouter)
} else {
fatalError("Unsupported content for media cell")
}
}
}
/**
Layouter for media bubbles
*/
open class AABubbleStickerCellLayouter: AABubbleLayouter {
open func isSuitable(_ message: ACMessage) -> Bool {
if message.content is ACStickerContent {
return true
}
return false
}
open func buildLayout(_ peer: ACPeer, message: ACMessage) -> AACellLayout {
return StikerCellLayout(message: message, layouter: self)
}
open func cellClass() -> AnyClass {
return AABubbleStickerCell.self
}
}
| agpl-3.0 | 2a409c251106c3d71b84bb02f0eafe0b | 32.948617 | 162 | 0.603796 | 4.871809 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ColorPixel/RGB/RGBA32ColorPixel.swift | 1 | 1590 | //
// RGBA32ColorPixel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
@frozen
public struct RGBA32ColorPixel: _RGBColorPixel {
public var r: UInt8
public var g: UInt8
public var b: UInt8
public var a: UInt8
@inlinable
@inline(__always)
public init(red: UInt8, green: UInt8, blue: UInt8, opacity: UInt8 = 0xFF) {
self.r = red
self.g = green
self.b = blue
self.a = opacity
}
}
| mit | ea337450eba49ddff1e1ac12bddbf5c8 | 36.857143 | 81 | 0.707547 | 4.087404 | false | false | false | false |
melsomino/unified-ios | Unified/Interfaces/Storage/Database/DatabaseExtentions.swift | 1 | 9205 | //
// Created by Власов М.Ю. on 17.05.16.
// Copyright (c) 2016 Tensor. All rights reserved.
//
import Foundation
public class DatabaseValueReader<Value>: GeneratorType {
public typealias Element = Value
let statement: DatabaseSelectStatement
let reader: DatabaseReader
let readValue: (DatabaseReader) -> Value?
init(database: StorageDatabase, sql: String, setParams: (DatabaseSelectStatement) -> Void, readValue: (DatabaseReader) -> Value?) throws {
statement = try database.createSelectStatement(sql)
setParams(statement)
reader = try statement.execute()
self.readValue = readValue
}
deinit {
reader.close()
statement.close()
}
@warn_unused_result public func next() -> Element? {
while reader.read() {
let readed = readValue(reader)
if readed != nil {
return readed
}
}
return nil
}
}
public class DatabaseValueSequence<Value>: SequenceType {
typealias Element = Value
private let database: StorageDatabase
private let sql: String
private let setParams: (DatabaseSelectStatement) -> Void
private let readValue: (DatabaseReader) -> Value?
init(database: StorageDatabase, sql: String, setParams: (DatabaseSelectStatement) -> Void, readValue: (DatabaseReader) -> Value?) {
self.database = database
self.sql = sql
self.setParams = setParams
self.readValue = readValue
}
@warn_unused_result public func generate() -> DatabaseValueReader<Value> {
return try! DatabaseValueReader(database: database, sql: sql, setParams: setParams, readValue: readValue)
}
}
public class DatabaseRecordReader<Record>: GeneratorType {
public typealias Element = Record
let statement: DatabaseSelectStatement
let reader: DatabaseReader
let readRecord: (DatabaseReader, Record) -> Void
var record: Record
init(database: StorageDatabase, sql: String, record: Record, setParams: (DatabaseSelectStatement) -> Void, readRecord: (DatabaseReader, Record) -> Void) throws {
statement = try database.createSelectStatement(sql)
setParams(statement)
reader = try statement.execute()
self.readRecord = readRecord
self.record = record
}
deinit {
reader.close()
statement.close()
}
@warn_unused_result public func next() -> Element? {
guard reader.read() else {
return nil
}
readRecord(reader, record)
return record
}
}
public class DatabaseRecordSequence<Record>: SequenceType {
typealias Element = Record
private let database: StorageDatabase
private let sql: String
private let record: Record
private let setParams: (DatabaseSelectStatement) -> Void
private let readRecord: (DatabaseReader, Record) -> Void
init(database: StorageDatabase, sql: String, record: Record, setParams: (DatabaseSelectStatement) -> Void, readRecord: (DatabaseReader, Record) -> Void) {
self.database = database
self.sql = sql
self.record = record
self.setParams = setParams
self.readRecord = readRecord
}
@warn_unused_result public func generate() -> DatabaseRecordReader<Record> {
return try! DatabaseRecordReader(database: database, sql: sql, record: record, setParams: setParams, readRecord: readRecord)
}
}
public enum DatabaseRecordFieldFilter {
case All, Key, NonKey
}
public class DatabaseRecordField<Record> {
public typealias ParamSetter = (DatabaseUpdateStatement, Int, Record) -> Void
public let name: String
public let isKey: Bool
public let paramSetter: ParamSetter
init(_ name: String, _ isKey: Bool, _ paramSetter: ParamSetter) {
self.name = name
self.isKey = isKey
self.paramSetter = paramSetter
}
}
public class DatabaseSqlFactory<Record> {
typealias ReaderGetter = (Record, DatabaseReader, Int) -> Void
typealias ParamSetter = (DatabaseUpdateStatement, Int, Record) -> Void
typealias SqlWithFields = (String, [DatabaseRecordField<Record>])
let tableName: String
let getFieldSet: (Record) -> Int
let fields: [DatabaseRecordField<Record>]
let create: (Int, DatabaseSqlFactory<Record>) -> SqlWithFields
let lock = NSLock()
init(_ tableName: String, _ getFieldSet: (Record) -> Int, _ fields: [DatabaseRecordField<Record>], create: (Int, DatabaseSqlFactory<Record>) -> SqlWithFields) {
self.tableName = tableName
self.getFieldSet = getFieldSet
self.fields = fields
self.create = create
}
var cache = [Int: SqlWithFields]()
func iterateFieldSet(fieldSet: Int, _ filter: DatabaseRecordFieldFilter, _ iterate: (DatabaseRecordField<Record>, Bool) -> Void) {
var flag = 1
var isFirst = true
for index in 0 ..< fields.count {
if (flag & fieldSet) != 0 {
let field = fields[index]
if filter == .All || field.isKey == (filter == .Key) {
iterate(field, isFirst)
isFirst = false
}
}
flag *= 2
}
}
func get(fieldSet: Int) -> SqlWithFields {
lock.lock()
defer {
lock.unlock()
}
if let cached = cache[fieldSet] {
return cached
}
let created = create(fieldSet, self)
cache[fieldSet] = created
return created
}
func createInsert(fieldSet: Int) -> DatabaseSqlFactory<Record>.SqlWithFields {
var insertSection = "INSERT INTO \(tableName)("
var valuesSection = ") VALUES ("
var fields = [DatabaseRecordField < Record>]()
iterateFieldSet(fieldSet, .All) {
field, isFirst in
if !isFirst {
insertSection += ", "
valuesSection += ", "
}
insertSection += "\(field.name)"
valuesSection += "?"
fields.append(field)
}
return (insertSection + valuesSection + ")", fields)
}
func createUpdate(fieldSet: Int) -> DatabaseSqlFactory<Record>.SqlWithFields {
var sql = "UPDATE \(tableName) SET "
var fields = [DatabaseRecordField < Record>]()
iterateFieldSet(fieldSet, .NonKey) {
field, isFirst in
if !isFirst {
sql += ", "
}
sql += "\(field.name)=?"
fields.append(field)
}
sql += " WHERE "
iterateFieldSet(fieldSet, .Key) {
field, isFirst in
if !isFirst {
sql += " AND "
}
sql += "\(field.name)=?"
fields.append(field)
}
return (sql, fields)
}
func createDelete(fieldSet: Int) -> DatabaseSqlFactory<Record>.SqlWithFields {
var sql = "DELETE FROM \(tableName) WHERE "
var fields = [DatabaseRecordField < Record>]()
iterateFieldSet(fieldSet, .All) {
field, isFirst in
if !isFirst {
sql += " AND "
}
sql += "\(field.name)=?"
fields.append(field)
}
return (sql, fields)
}
}
public class DatabaseStatementFactory<Record> {
typealias StatementWithFields = (DatabaseUpdateStatement, [DatabaseRecordField<Record>])
let database: StorageDatabase
let sqlFactory: DatabaseSqlFactory<Record>
var cache = [Int: StatementWithFields]()
init(_ database: StorageDatabase, _ factory: DatabaseSqlFactory<Record>) {
self.database = database
self.sqlFactory = factory
}
func get(fieldSet: Int) -> StatementWithFields {
if let cached = cache[fieldSet] {
return cached
}
let (sql, fields) = sqlFactory.get(fieldSet)
let created = (try! database.createUpdateStatement(sql), fields)
cache[fieldSet] = created
return created
}
func execute(record: Record) -> Void {
let (statement, fields) = get(sqlFactory.getFieldSet(record))
for index in 0 ..< fields.count {
fields[index].paramSetter(statement, index, record)
}
try! statement.execute()
}
func execute(records: [Record]) -> Void {
for record in records {
execute(record)
}
}
}
public class DatabaseRecordSqlFactory<Record> {
public let updates: DatabaseSqlFactory<Record>
public let inserts: DatabaseSqlFactory<Record>
public let deletes: DatabaseSqlFactory<Record>
init(_ tableName: String, _ getFieldSet: (Record) -> Int, _ fields: [DatabaseRecordField<Record>]) {
updates = DatabaseSqlFactory<Record>(tableName, getFieldSet, fields) {
fieldSet, factory in return factory.createUpdate(fieldSet)
}
inserts = DatabaseSqlFactory<Record>(tableName, getFieldSet, fields) {
fieldSet, factory in return factory.createInsert(fieldSet)
}
deletes = DatabaseSqlFactory<Record>(tableName, getFieldSet, fields) {
fieldSet, factory in return factory.createDelete(fieldSet)
}
}
}
public class DatabaseRecordStatementFactory<Record> {
let database: StorageDatabase
let updates: DatabaseStatementFactory<Record>
let inserts: DatabaseStatementFactory<Record>
let deletes: DatabaseStatementFactory<Record>
init(_ database: StorageDatabase, _ factory: DatabaseRecordSqlFactory<Record>) {
self.database = database
updates = DatabaseStatementFactory<Record>(database, factory.updates)
inserts = DatabaseStatementFactory<Record>(database, factory.inserts)
deletes = DatabaseStatementFactory<Record>(database, factory.deletes)
}
}
extension StorageDatabase {
public func iterateRecords<Record>(sql: String,
record: Record,
setParams: (DatabaseSelectStatement) -> Void,
readRecord: (DatabaseReader, Record) -> Void) throws -> DatabaseRecordSequence<Record> {
return DatabaseRecordSequence(database: self, sql: sql, record: record, setParams: setParams, readRecord: readRecord)
}
public func iterateValues<Value>(sql: String,
setParams: (DatabaseSelectStatement) -> Void,
readValue: (DatabaseReader) -> Value?) throws -> DatabaseValueSequence<Value> {
return DatabaseValueSequence(database: self, sql: sql, setParams: setParams, readValue: readValue)
}
}
| mit | 81dd601ad1c7789b599f2aab527bebb3 | 26.453731 | 162 | 0.720561 | 3.613752 | false | false | false | false |
jmayoralas/Sems | Sems/ViewController.swift | 1 | 9792 | //
// ViewController.swift
// Sems
//
// Created by Jose Luis Fernandez-Mayoralas on 27/6/16.
// Copyright © 2016 Jose Luis Fernandez-Mayoralas. All rights reserved.
//
import Cocoa
import JMZeta80
private let kColorSpace = CGColorSpaceCreateDeviceRGB()
private let kInstantLoadEnabled = "(Instant load enabled)"
private let kInstantLoadDisabled = "(Instant load disabled)"
class ViewController: NSViewController, VirtualMachineStatus {
private let open_dialog = NSOpenPanel()
@IBOutlet weak var screenView: NSImageView!
@objc var screen: VmScreen!
var vm: VirtualMachine!
let appVersionString = String(
format: "Sems v%@.%@",
Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String,
Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setup()
vm.run()
}
override func viewDidAppear() {
self.view.window!.title = String(format: "%@ %@", appVersionString, kInstantLoadDisabled)
}
// MARK: Initialization
func setup() {
self.setupOpenDialog()
self.screenView.imageScaling = .scaleProportionallyUpOrDown
self.screen = VmScreen(zoomFactor: 2)
configureVM()
self.loadSpeccyRom()
NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.keyDown) {(theEvent: NSEvent) -> NSEvent? in return self.onKeyDown(theEvent: theEvent)}
NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.keyUp) {(theEvent: NSEvent) -> NSEvent? in return self.onKeyUp(theEvent: theEvent)}
NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.flagsChanged) {(theEvent: NSEvent) -> NSEvent? in return self.onFlagsChanged(theEvent: theEvent)}
}
private func setupOpenDialog() {
open_dialog.showsResizeIndicator = true
open_dialog.showsHiddenFiles = false
open_dialog.canChooseDirectories = true
open_dialog.canCreateDirectories = true
open_dialog.allowsMultipleSelection = false
}
private func loadSpeccyRom() {
loadRomData(data: NSDataAsset(name: "Rom48k")!.data as NSData)
}
private func loadRomFile(path: String) {
loadRomData(data: NSData(contentsOfFile: path)!)
}
private func loadRomData(data: NSData) {
var buffer = [UInt8](repeating: 0, count: data.length)
(data as NSData).getBytes(&buffer, length: data.length)
try! self.vm.loadRomAtAddress(0x0000, data: buffer)
}
private func configureVM() {
let clock = Clock()
let bus = Bus16(clock: clock, screen: screen)
let cpu = Cpu(bus: bus, clock: clock)
let ula = Ula(screen: screen, clock: clock)
vm = VirtualMachine(bus: bus, cpu: cpu, ula: ula, clock: clock, screen: screen)
vm.delegate = self
}
private func errorShow(messageText: String) {
let alert = NSAlert()
alert.alertStyle = NSAlert.Style.critical
alert.addButton(withTitle: "OK")
alert.messageText = messageText
alert.runModal()
}
// MARK: Keyboard handling
private func onKeyDown(theEvent: NSEvent) -> NSEvent? {
if !theEvent.modifierFlags.contains(NSEvent.ModifierFlags.command) {
if self.vm.isRunning() {
self.vm.keyDown(char: KeyEventHandler.getChar(event: theEvent))
return nil
}
}
return theEvent
}
private func onKeyUp(theEvent: NSEvent) -> NSEvent? {
if self.vm.isRunning() {
self.vm.keyUp(char: KeyEventHandler.getChar(event: theEvent))
return nil
}
return theEvent
}
private func onFlagsChanged(theEvent: NSEvent) -> NSEvent? {
if self.vm.isRunning() {
self.vm.specialKeyUpdate(special_keys: KeyEventHandler.getSpecialKeys(event: theEvent))
return nil
}
return theEvent
}
// MARK: Screen handling
func Z80VMScreenRefresh() {
let image = imageFromARGB32Bitmap(
pixels: self.screen.buffer,
width: self.screen!.width,
height: self.screen!.height
)
DispatchQueue.main.async { [unowned self] in
self.screenView.image = image
}
}
func imageFromARGB32Bitmap(pixels:[PixelData], width:Int, height:Int) -> NSImage {
let bitsPerComponent = 8
let bitsPerPixel = 32
assert(pixels.count == Int(width * height))
var data = pixels // Copy to mutable []
let providerRef = CGDataProvider.init(data: NSData(bytes: &data, length: data.count * MemoryLayout<PixelData>.size))
let cgim = CGImage.init(
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: width * MemoryLayout<PixelData>.size,
space: kColorSpace,
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue),
provider: providerRef!,
decode: nil,
shouldInterpolate: true,
intent: CGColorRenderingIntent.defaultIntent
)
return NSImage(cgImage: cgim!, size: NSZeroSize)
}
// MARK: Menu selectors
@IBAction func loadCustomRom(_ sender: AnyObject) {
open_dialog.title = "Choose ROM file"
open_dialog.allowedFileTypes = ["rom", "bin"]
if open_dialog.runModal() == NSApplication.ModalResponse.OK {
if let result = open_dialog.url {
self.loadRomFile(path: result.path)
self.resetMachine(sender)
}
}
}
@IBAction func openTape(_ sender: AnyObject) {
open_dialog.title = "Choose a file"
open_dialog.allowedFileTypes = ["tap", "tzx"]
if open_dialog.runModal() == NSApplication.ModalResponse.OK {
if let result = open_dialog.url {
let path = result.path
do {
try self.vm.openTape(path: path)
} catch let error as TapeLoaderError {
self.handleTapeError(error: error)
} catch {
self.handleUnknownError()
}
}
}
}
@IBAction func playTape(_ sender: AnyObject) {
guard !self.vm.instantLoadEnabled() else {
self.errorShow(messageText: "Cannot play a tape when instant load is enabled")
return
}
if self.vm.tapeIsPlaying() {
self.vm.stopTape()
} else {
do {
try vm.startTape()
} catch let error as TapeLoaderError {
self.handleTapeError(error: error)
} catch {
self.errorShow(messageText: "Unknown error")
}
}
}
@IBAction func resetMachine(_ sender: AnyObject) {
self.vm.reset()
}
@IBAction func warpEmulation(_ sender: AnyObject) {
self.vm.toggleWarp()
}
@IBAction func toggleInstantLoad(_ sender: AnyObject) {
if self.vm.instantLoadEnabled() {
self.view.window!.title = String(format: "%@ %@", self.appVersionString, kInstantLoadDisabled)
self.vm.disableInstantLoad()
} else {
self.view.window!.title = String(format: "%@ %@", self.appVersionString, kInstantLoadEnabled)
self.vm.enableInstantLoad()
}
}
@IBAction func showTapeBlockSelector(_ sender: AnyObject) {
// do some validations here
do {
let tapeBlockDirectory = try self.vm.getBlockDirectory()
let storyBoard = NSStoryboard(name: "Main", bundle: nil)
let tapeBlockSelectorWindowController = storyBoard.instantiateController(withIdentifier: "TapeBlockSelectorWindowController") as! NSWindowController
if let tapeBlockSelectorWindow = tapeBlockSelectorWindowController.window {
let tapeBlockSelectorViewController = tapeBlockSelectorWindowController.contentViewController as! TapeBlockSelectorViewController
tapeBlockSelectorViewController.setBlockDirectory(blockDirectory: tapeBlockDirectory)
let application = NSApplication.shared
let modalResult = application.runModal(for: tapeBlockSelectorWindow)
self.view.window!.makeMain()
self.view.window!.makeKey()
if modalResult == NSApplication.ModalResponse.OK {
do {
try self.vm.setCurrentTapeBlock(index: tapeBlockSelectorViewController.getSelectedTapeBlockIndex())
} catch let error as TapeLoaderError {
self.handleTapeError(error: error)
} catch {
self.handleUnknownError()
}
}
}
} catch let error as TapeLoaderError {
self.handleTapeError(error: error)
} catch {
self.handleUnknownError()
}
}
// MARK: Error handlers
func handleTapeError(error: TapeLoaderError) {
self.errorShow(messageText: error.description)
}
func handleUnknownError() {
self.errorShow(messageText: "Unknown error!")
}
}
| gpl-3.0 | f0da1db9be0d575b5a896f9cf54335f6 | 33.843416 | 170 | 0.594628 | 4.818406 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/model/API/RegionInfoAPIModel.swift | 1 | 4366 | //
// RegionAPIModel.swift
// TripKit
//
// Created by Adrian Schoenig on 28/10/16.
// Copyright © 2016 SkedGo. All rights reserved.
//
import Foundation
extension TKAPI {
public struct RegionInfo: Codable, Hashable {
public let streetBicyclePaths: Bool
public let streetWheelchairAccessibility: Bool
public let transitModes: [TKModeInfo]
public let transitBicycleAccessibility: Bool
public let transitConcessionPricing: Bool
public let transitWheelchairAccessibility: Bool
public let paratransit: Paratransit?
/// Additional information for some of the modes in the region.
/// Dictionary of a generic mode identifier to the details.
///
/// Use `TKTransportMode.genericModeIdentifier` to get the
/// generic part of any mode identifier.
public let modes: [String: GenericModeDetails]
}
/// Informational class for paratransit information (i.e., transport for people with disabilities).
/// Contains name of service, URL with more information and phone number.
///
/// Formerly known as `TKParatransitInfo`
/// - SeeAlso: `TKBuzzInfoProvider`'s `fetchParatransitInformation`
public struct Paratransit: Codable, Hashable {
public let name: String
public let url: URL
public let number: String
private enum CodingKeys: String, CodingKey {
case name
case url = "URL"
case number
}
}
public enum Integrations: String, Codable {
case routing
case realTime = "real_time"
case bookings
case payments
}
/// Additional details about a group of modes,
/// e.g., all bike or car share providers in a city
public struct GenericModeDetails: Codable, Hashable {
/// Name of the group
public let title: String
/// Additional info about the mode group
public let modeInfo: TKModeInfo
/// The specific modes of this group that are
/// available for your API key.
@DefaultEmptyArray public var specificModes: [SpecificModeDetails]
/// Additional specific modes that are available
/// on the platform, but not currently available
/// for your API key.
///
/// See https://developer.tripgo.com/extensions/
/// for how to unlock them, or get in touch with
/// someone from the TripGo API team.
@DefaultEmptyArray public var lockedModes: [SpecificModeDetails]
}
/// Additional details about a specific mode, where the
/// specific mode usually relates to a certain transport
/// provider, such as a car-sharing provider, bike-sharing
/// provider, limousine company, or TNC.
public struct SpecificModeDetails: Codable, Hashable {
/// Name of thise mode
public let title: String?
/// Additional info about the mode
public let modeInfo: TKModeInfo
/// Available integrations for this mode that are available
/// through the TripGo API.
@DefaultEmptyArray public var integrations: [Integrations]
/// URL of the primary transport provider of this mode.
public let url: URL?
/// Minimum cost for a membership for the provider
/// of this mode. Typically applies to car share
/// and bike share.
public let minimumLocalCostForMembership: Decimal?
/// List of public transport operator names servicing
/// this mode. (Public transport modes only)
@DefaultEmptyArray public var operators: [String]
/// List of image name-parts related to this operator
@DefaultEmptyArray public var modeImageNames: [String]
public var identifier: String {
if let id = modeInfo.identifier {
return id
} else {
assertionFailure("Specific mode details should always have an identifier. Missing for '\(String(describing:self))'.")
return ""
}
}
}
}
extension TKAPI.RegionInfo {
/// - Parameter modeIdentifier: A mode identifier
/// - Returns: The specific mode details for this this mode identifier
/// (only returns something if it's a specific mode identifier, i.e.,
/// one with two underscores in it.)
public func specificModeDetails(for modeIdentifier: String) -> TKAPI.SpecificModeDetails? {
let genericMode = TKTransportMode.genericModeIdentifier(forModeIdentifier: modeIdentifier)
return modes[genericMode]?.specificModes.first { modeIdentifier == $0.identifier }
}
}
| apache-2.0 | 8ecf5986a3d18546a63d347a45c5eb05 | 32.576923 | 125 | 0.695074 | 4.678457 | false | false | false | false |
slimane-swift/WS | Sources/CloseCode.swift | 1 | 3273 | // CloseCode.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 enum CloseCode: Equatable {
case normal
case goingAway
case protocolError
case unsupported
case noStatus
case abnormal
case unsupportedData
case policyViolation
case tooLarge
case missingExtension
case internalError
case serviceRestart
case tryAgainLater
case tlsHandshake
case raw(UInt16)
init(code: UInt16) {
switch code {
case 1000: self = .normal
case 1001: self = .goingAway
case 1002: self = .protocolError
case 1003: self = .unsupported
case 1005: self = .noStatus
case 1006: self = .abnormal
case 1007: self = .unsupportedData
case 1008: self = .policyViolation
case 1009: self = .tooLarge
case 1010: self = .missingExtension
case 1011: self = .internalError
case 1012: self = .serviceRestart
case 1013: self = .tryAgainLater
case 1015: self = .tlsHandshake
default: self = .raw(UInt16(code))
}
}
var code: UInt16 {
switch self {
case .normal: return 1000
case .goingAway: return 1001
case .protocolError: return 1002
case .unsupported: return 1003
case .noStatus: return 1005
case .abnormal: return 1006
case .unsupportedData: return 1007
case .policyViolation: return 1008
case .tooLarge: return 1009
case .missingExtension: return 1010
case .internalError: return 1011
case .serviceRestart: return 1012
case .tryAgainLater: return 1013
case .tlsHandshake: return 1015
case .raw(let code): return code
}
}
var isValid: Bool {
let code = self.code
if code >= 1000 && code <= 5000 {
return code != 1004 && code != 1005 && code != 1006 && code != 1014 && code != 1015 &&
code != 1016 && code != 1100 && code != 2000 && code != 2999
}
return false
}
}
public func == (lhs: CloseCode, rhs: CloseCode) -> Bool {
return lhs.code == rhs.code
}
| mit | d4ae68da715c4c21322a52815fe6d27c | 33.09375 | 98 | 0.643752 | 4.471311 | false | false | false | false |
damizhou/Leetcode | LeetCode/LeetCode/Easy/ExcelSheetColumnTitle_168.swift | 1 | 1557 | //
// Day9_MoveZeroes_283.swift
// LeetCode
//
// Created by 潘传洲 on 16/11/3.
// Copyright © 2016年 pcz. All rights reserved.
//
import Foundation
class ExcelSheetColumnTitle_168: NSObject {
/// Given a positive integer, return its corresponding column title as appear in an Excel sheet.给定一个数字,输出对应的字符串.
/// For example:
/// 1 -> A
/// 2 -> B
/// 3 -> C
/// ...
/// 26 -> Z
/// 27 -> AA
/// 28 -> AB
/// 52 -> AZ
/// 702 -> ZZ
/// 703 -> AAA
/// 解题思路:本题可以类比为进制转换.将十进制转换为二十六进制.但是与正常的进制转换不同的是,在转换后的进制中最后一位和其他位的相同字符的含义并不一致.以A举例,当结果并非一位时,A在最后一位代表0,在其他位代表1.若结果只有一位A代表1.
/// 因此:在循环的时候进行标记.判断当前的位数,如果是最后一位,取余结果-1
///
/// - Parameter n: 给定整数
/// - Returns: 返回的对应字符串
static func convertToTitle(_ n: Int) -> String {
let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var result = ""
var newN = n - 1
var remainder = 0
var j = 0
repeat {
newN -= j
remainder = newN % 26
newN /= 26
let index = str.index(str.startIndex, offsetBy: remainder)
j = 1
result = String(str[index]) + result
} while newN > 0
return result
}
}
| apache-2.0 | 22cd565e52411cec827d52da4ca9abd6 | 24.142857 | 126 | 0.540584 | 3.167095 | false | false | false | false |
xedin/swift | test/ParseableInterface/ModuleCache/prebuilt-module-cache-forwarding.swift | 1 | 3578 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/MCP)
// RUN: %empty-directory(%t/prebuilt-cache)
// First, prebuild a module and put it in the prebuilt cache.
// RUN: sed -e 's/FromInterface/FromPrebuilt/g' %S/Inputs/prebuilt-module-cache/Lib.swiftinterface | tr -d '\r' > %t/Lib.swiftinterface.tmp
// RUN: mv %t/Lib.swiftinterface.tmp %t/Lib.swiftinterface
// RUN: %target-swift-frontend -build-module-from-parseable-interface -module-cache-path %t/MCP -serialize-parseable-module-interface-dependency-hashes -o %t/prebuilt-cache/Lib.swiftmodule %t/Lib.swiftinterface
// Next, use the module and check if the forwarding module is in place.
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -sdk %S/Inputs -I %S/Inputs/prebuilt-module-cache/ -prebuilt-module-cache-path %t/prebuilt-cache %s 2>&1 | %FileCheck -check-prefix=FROM-PREBUILT %s
// Make sure we installed a forwarding module.
// RUN: %{python} %S/Inputs/check-is-forwarding-module.py %t/MCP/Lib-*.swiftmodule
// Make sure it passes:
// RUN: sleep 1
// Now invalidate a dependency of the prebuilt module, and make sure the forwarding file is replaced with a real module.
// RUN: %{python} %S/Inputs/make-old.py %t/Lib.swiftinterface
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -sdk %S/Inputs -I %S/Inputs/prebuilt-module-cache/ -prebuilt-module-cache-path %t/prebuilt-cache %s 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// Delete the cached module we just created, and create the forwarding module again
// RUN: %empty-directory(%t/MCP)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -sdk %S/Inputs -I %S/Inputs/prebuilt-module-cache/ -prebuilt-module-cache-path %t/prebuilt-cache %s 2>&1 | %FileCheck -check-prefix=FROM-PREBUILT %s
// Move the prebuilt module out of the way, so the forwarding module points to nothing.
// RUN: mv %t/prebuilt-cache/Lib.swiftmodule %t/prebuilt-cache/NotLib.swiftmodule
// Make sure we delete the existing forwarding module and rebuild from an interface.
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -sdk %S/Inputs -I %S/Inputs/prebuilt-module-cache/ -prebuilt-module-cache-path %t/prebuilt-cache %s 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// Move the prebuilt module back to its original path
// RUN: mv %t/prebuilt-cache/NotLib.swiftmodule %t/prebuilt-cache/Lib.swiftmodule
// If the forwarding module is corrupted, we shouldn't rebuild the module in the cache,
// we should delete it and generate a new forwarding module.
// RUN: %empty-directory(%t/MCP)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -sdk %S/Inputs -I %S/Inputs/prebuilt-module-cache/ -prebuilt-module-cache-path %t/prebuilt-cache %s 2>&1
// RUN: %{python} %S/Inputs/check-is-forwarding-module.py %t/MCP/Lib-*.swiftmodule
// RUN: %{python} %S/../Inputs/make-unreadable.py %t/MCP/Lib-*.swiftmodule
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -sdk %S/Inputs -I %S/Inputs/prebuilt-module-cache/ -prebuilt-module-cache-path %t/prebuilt-cache %s 2>&1 | %FileCheck -check-prefix=FROM-PREBUILT %s
// RUN: %{python} %S/Inputs/check-is-forwarding-module.py %t/MCP/Lib-*.swiftmodule
import Lib
struct X {}
let _: X = Lib.testValue
// FROM-INTERFACE: [[@LINE-1]]:16: error: cannot convert value of type 'FromInterface' to specified type 'X'
// FROM-PREBUILT: [[@LINE-2]]:16: error: cannot convert value of type 'FromPrebuilt' to specified type 'X'
| apache-2.0 | a5de4a5be900cb4ffd946d3577beffbf | 70.56 | 235 | 0.738401 | 3.246824 | false | false | false | false |
soapyigu/Swift30Projects | Project 27 - NotificationsUI/NotificationsUI/AppDelegate.swift | 1 | 3256 | //
// AppDelegate.swift
// NotificationsUI
//
// Copyright © 2016 Pranjal Satija. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
/// Request local notification authorizations.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { accepted, error in
if !accepted {
print("Notification access denied.")
}
}
/// Render actions for notification.
let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
let category = UNNotificationCategory(identifier: "normal", actions: [action], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
return true
}
/// Create a local notification at specific date.
///
/// - Parameter date: Time to trigger notification.
func scheduleNotification(at date: Date) {
UNUserNotificationCenter.current().delegate = self
/// Create date component from date.
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents.init(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
/// Create trigger and content.
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Coding Reminder"
content.body = "Ready to code? Let us do some Swift!"
content.sound = UNNotificationSound.default
content.categoryIdentifier = "normal"
/// Add a image as attachment.
if let path = Bundle.main.path(forResource: "Swift", ofType: "png") {
let url = URL(fileURLWithPath: path)
do {
let attachment = try UNNotificationAttachment(identifier: "Swift", url: url, options: nil)
content.attachments = [attachment]
} catch {
print("The attachment was not loaded.")
}
}
/// Make a notification request.
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
/// Remove pending notifications to avoid duplicates.
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
/// Provide request to notification center.
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("Error: " + error.localizedDescription)
}
}
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == "remindLater" {
let newDate = Date(timeInterval: 60, since: Date())
scheduleNotification(at: newDate)
}
}
}
| apache-2.0 | 0b667fa2ad2d4d77ef4c3c6a27a59192 | 37.75 | 179 | 0.706912 | 5.183121 | false | false | false | false |
cuzv/VendorsExtension | Sources/UIControl+Vendor.swift | 1 | 9390 | //
// UIControl+Vendor.swift
// ExtensionKit
//
// Created by Moch Xiao on 1/5/16.
// Copyright © @2016 Moch Xiao (https://github.com/cuzv).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import SnapKit
import ReactiveCocoa
import ReactiveSwift
import ExtensionKit
// MARK: - SegmentedToggleControl
final public class SegmentedToggleControl: UIControl {
fileprivate var items: [String]
fileprivate var buttons: [UIButton] = []
fileprivate let normalTextColor: UIColor
fileprivate let selectedTextColor: UIColor
fileprivate var font: UIFont!
fileprivate var lastSelectedIndex = 0
fileprivate var firstTime: Bool = true
public var selectedSegmentIndex: Int = 0 {
didSet {
if selectedSegmentIndex >= items.count {
selectedSegmentIndex = items.count - 1
}
rac_index.value = selectedSegmentIndex
updateAppearance()
}
}
public var rac_index: MutableProperty<Int> = MutableProperty(0)
public var autoComputeLineWidth: Bool = true
let lineView: UIView = {
let view = UIView()
return view
}()
public init(
items: [String],
normalTextColor: UIColor = UIColor.black,
selectedTextColor: UIColor = UIColor.tint)
{
if items.count < 2 {
fatalError("items.count can not less 2.")
}
self.items = items
self.normalTextColor = normalTextColor
self.selectedTextColor = selectedTextColor
super.init(frame: CGRect.zero)
setup()
}
override fileprivate init(frame: CGRect) {
fatalError("Use init(actionHandler:) instead.")
}
fileprivate init() {
fatalError("Use init(actionHandler:) instead.")
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var intrinsicContentSize : CGSize {
// Calculate text size
let str = items.reduce("") { (str1, str2) -> String in
return "\(str1)\(str2)"
}
if let font = font {
var size = str.layoutSize(font: font)
size.width += CGFloat(items.count * 12)
var height = size.height
if height < 44 {
height = 44
}
size.height = height
return size
} else {
return CGSize(width: 60, height: 44)
}
}
public override func layoutSubviews() {
super.layoutSubviews()
if !autoComputeLineWidth && firstTime {
lineView.snp.remakeConstraints({ (make) -> Void in
make.width.equalTo(lineViewWidthForIndex(selectedSegmentIndex))
make.height.equalTo(1)
make.bottom.equalTo(self)
let currentButton = buttons[selectedSegmentIndex]
make.centerX.equalTo(currentButton)
})
firstTime = false
}
}
}
public extension SegmentedToggleControl {
fileprivate func setup() {
let blurBackgroundView = UIToolbar(frame: CGRect.zero)
blurBackgroundView.barStyle = .default
blurBackgroundView.isTranslucent = true
blurBackgroundView.clipsToBounds = true
addSubview(blurBackgroundView)
blurBackgroundView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
var lastButton: UIButton!
let count = items.count
for i in 0 ..< count {
// Make button
let button = UIButton(type: .system)
button.tag = i
button.addTarget(self, action: #selector(SegmentedToggleControl.hanleClickAction(_:)), for: .touchUpInside)
button.title = items[i]
button.setTitleColor(normalTextColor, for: .normal)
button.setTitleColor(selectedTextColor, for: .selected)
button.tintColor = UIColor.clear
button.backgroundColor = UIColor.clear
addSubview(button)
// Set position
button.snp.makeConstraints({ (make) -> Void in
make.top.equalTo(self)
make.bottom.equalTo(self)
if let lastButton = lastButton {
make.left.equalTo(lastButton.snp.right)
make.width.equalTo(lastButton.snp.width)
} else {
make.left.equalTo(self)
}
if i == count - 1 {
make.right.equalTo(self)
}
})
lastButton = button
buttons.append(button)
}
font = lastButton.titleLabel?.font
if let firstButton = buttons.first {
firstButton.isSelected = true
addSubview(lineView)
lineView.backgroundColor = selectedTextColor
lineView.snp.makeConstraints { (make) -> Void in
make.width.equalTo(lineViewWidthForIndex(0))
make.height.equalTo(1)
make.centerX.equalTo(firstButton)
make.bottom.equalTo(self)
}
}
}
fileprivate func updateAppearance() {
let sender = buttons[selectedSegmentIndex]
// toggle selected button
buttons.forEach { (button) -> () in
button.isSelected = false
}
sender.isSelected = true
// Move lineView
if let index = buttons.index(of: sender) {
remakeLineViewConstraintsForIndex(index)
}
// Send action
sendActions(for: .valueChanged)
}
internal func hanleClickAction(_ sender: UIButton) {
selectedSegmentIndex = sender.tag
}
fileprivate func remakeLineViewConstraintsForIndex(_ index: Int) {
lineView.snp.remakeConstraints({ (make) -> Void in
make.width.equalTo(lineViewWidthForIndex(index))
make.height.equalTo(1)
make.bottom.equalTo(self)
let currentButton = buttons[index]
make.centerX.equalTo(currentButton)
})
let duration: TimeInterval = fabs(Double(lastSelectedIndex - index)) * 0.1
if duration <= 0 || nil == window {
setNeedsLayout()
layoutIfNeeded()
} else {
UIView.animate(withDuration: duration, animations: { () -> Void in
self.setNeedsLayout()
self.layoutIfNeeded()
})
}
lastSelectedIndex = selectedSegmentIndex
}
fileprivate func lineViewWidthForIndex(_ index: Int) -> CGFloat {
if autoComputeLineWidth {
return items[index].layoutSize(font: font).width
} else {
return (bounds.size.width / CGFloat(items.count)).ceilling
}
}
}
public extension SegmentedToggleControl {
/// can only have image or title, not both. must be 0..#segments - 1 (or ignored). default is nil
public func set(title: String, forSegmentAtIndex segment: Int) {
if items.count <= segment {
debugPrint("Index beyound the boundary.")
return
}
let button = buttons[segment]
button.title = title
button.image = nil
items.replace(at: segment, with: title)
remakeLineViewConstraintsForIndex(segment)
}
public func titleForSegmentAtIndex(_ segment: Int) -> String? {
if items.count <= segment {
return nil
}
return items[segment]
}
/// can only have image or title, not both. must be 0..#segments - 1 (or ignored). default is nil
public func set(image: UIImage, forSegmentAtIndex segment: Int) {
if items.count <= segment {
debugPrint("Index beyound the boundary.")
return
}
let button = buttons[segment]
button.image = image
button.title = nil
}
public func imageForSegmentAtIndex(_ segment: Int) -> UIImage? {
if items.count <= segment {
return nil
}
return buttons[segment].image
}
}
| mit | c66f3c34588c0631b3bcd05bd8261d37 | 32.176678 | 119 | 0.588348 | 5.075135 | false | false | false | false |
valitovaza/IntervalReminder | IntervalReminder/NotificationPresenter.swift | 1 | 1274 | import Foundation
protocol NotificationPresenterProtocol {
func presentNotification(_ title: String)
}
protocol NotificationDeliverer {
func deliver(_ notification: NSUserNotification)
var delegate: NSUserNotificationCenterDelegate? {get set}
}
extension NSUserNotificationCenter: NotificationDeliverer {}
class NotificationPresenter: NSObject, NotificationPresenterProtocol, NSUserNotificationCenterDelegate {
var deliverer: NotificationDeliverer!
init(deliverer: NotificationDeliverer = NSUserNotificationCenter.default) {
self.deliverer = deliverer
}
func presentNotification(_ title: String) {
deliverer.delegate = self
deliverer.deliver(notification(title))
}
private func notification(_ title: String) -> NSUserNotification {
let notification = NSUserNotification()
notification.title = "IntervalReminder"
notification.informativeText = title
notification.soundName = NSUserNotificationDefaultSoundName
return notification
}
// MARK: - NSUserNotificationCenterDelegate
func userNotificationCenter(_ center: NSUserNotificationCenter,
shouldPresent notification: NSUserNotification) -> Bool {
return true
}
}
| mit | 10dbb7965258cab0858c53e01ae14000 | 38.8125 | 104 | 0.733909 | 6.434343 | false | false | false | false |
xsunsmile/zentivity | zentivity/ShadowButton.swift | 1 | 1247 | //
// ShadowButton.swift
// zentivity
//
// Created by Hao Sun on 3/14/15.
// Copyright (c) 2015 Zendesk. All rights reserved.
//
import UIKit
class ShadowButton: UIButton {
var cornerRadius: CGFloat? {
didSet {
self.setNeedsDisplay()
}
}
required init(coder decoder: NSCoder) {
super.init(coder: decoder)
cornerRadius = frame.width/2
}
override func drawRect(rect: CGRect) {
updateLayerProperties()
}
func updateLayerProperties() {
layer.masksToBounds = true
layer.cornerRadius = cornerRadius!
//superview is your optional embedding UIView
if let superview = superview {
superview.backgroundColor = UIColor.clearColor()
superview.layer.shadowColor = UIColor.blackColor().CGColor
superview.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius!).CGPath
superview.layer.shadowOffset = CGSize(width: -1.0, height: 1.0)
superview.layer.shadowOpacity = 0.7
superview.layer.shadowRadius = 1
superview.layer.masksToBounds = true
superview.clipsToBounds = false
}
}
}
| apache-2.0 | 6b7c953ebf365924813b9d551c8a6278 | 26.711111 | 110 | 0.614274 | 4.890196 | false | false | false | false |
mohsenShakiba/ListView | ListView/Classes/CoreListViewSection.swift | 1 | 6941 | //
// CoreListViewSection.swift
// Pods
//
// Created by mohsen shakiba on 2/10/1396 AP.
//
//
import Foundation
import UIKit
import RxSwift
open class CoreListViewSection: VisibleItem {
// header and footer height
var _footerHeight: CGFloat = 0.1
var _headerHeight: CGFloat = 0.1
// header and footer view
var _footerView: UIView?
var _headerView: UIView?
// next operation for section
var nextOperation: NextOperation = .changeToCommit
var nextOperationIndex: Int?
// section identifier
var id: String
// index of this section in table view
var index: Int? = nil
// weak referenced pointer to controller
weak var controller: ListViewController?
// used to determine next status for section
var visibilityObserver = VisiblityObserver(true)
var disposeBag = DisposeBag()
let repository = ListViewRepository<ListViewRow>()
// config handler
// this handler is called once the section is finalized
// once handler is called, it is removed
var configHandler: ((ListViewSection) -> Void)?
// if repository needs to rebuild the visible cells
// needed to more efficently create cache
var needsCacheInvalidation = false
// reached bottom status
var reachedBottomRowIndex = -1
// default initializer
init(id: String, controller: ListViewController) {
self.id = id
self.controller = controller
}
// find row by row
func rowBy(index: Int) -> CoreListViewRow {
return repository.visibleItems[index]
}
// current visibllity status of section wihtout changing the lastVisibilityState
func isVisible() -> Bool {
return self.visibilityObserver.isVisible
}
// row reuseIdentifier
func cellReuseIdentifierBy(row: Int) -> String? {
return repository.visibleItems[row].reuseIdentifier
}
// get row height
func rowHeightBy(row: Int) -> CGFloat {
let row = self.repository.visibleItems[row]
let height = row.rowHeight()
return height
}
// section header height
func getHeaderHeight() -> CGFloat {
if self.repository.visibleItems.count == 0 {
return 0.1
}
return self._headerHeight
}
// section footer height
func getFooterHeight() -> CGFloat {
if repository.visibleItems.count == 0 {
return 0.1
}
return self._footerHeight
}
// heade view
func getHeaderView() -> UIView? {
return _headerView
}
// footer view
func getFooterView() -> UIView? {
return _footerView
}
// clear all references for this section
func dispose() {
self.configHandler = nil
for row in self.repository.allItems {
row.dispose()
}
}
// if row is the last row in section
func didReachBottom(row: Int) -> Bool {
// count of visible rows
let rowCount = self.repository.visibleItems.count
// if row is less than the row count
if row < rowCount - 1 {
return false
}
// if row is less than the last
if row <= reachedBottomRowIndex {
return false
}
// set the reached bottom index
reachedBottomRowIndex = row
return true
}
func showRow(_ row: CoreListViewRow) {
beginUpdatesIfNeeded()
row.nextOperation = .changoToVisible
endUpdatesIfNeeded()
}
func hideRow(_ row: CoreListViewRow) {
beginUpdatesIfNeeded()
row.nextOperation = .changeToHidden
endUpdatesIfNeeded()
}
func showRowBy(id: String) {
if let row = rowBy(id: id) {
showRow(row)
}
}
func hideRowBy(id: String) {
if let row = rowBy(id: id) {
hideRow(row)
}
}
func rowIndexBy(id: String) -> Int? {
return repository.visibleItems.index(where: {$0.id == id})
}
// commit row
func commitRow(_ row: ListViewRow, at: Int? = nil) {
if rowBy(id: row.id) != nil {
#if DEBUG
fatalError("duplicate id detected for section \(self.id) the id is \(row.id)")
#else
return
#endif
}
beginUpdatesIfNeeded()
_ = repository.insert(row: row, at: at)
endUpdatesIfNeeded()
}
func removeRowBy(id: String) {
guard let row = rowBy(id: id) else {
return
}
beginUpdatesIfNeeded()
row.nextOperation = .changeToRemove
endUpdatesIfNeeded()
}
func beginUpdatesIfNeeded() {
self.controller?.beginUpdatesIfNeeded()
}
func endUpdatesIfNeeded() {
self.controller?.endUpdatesIfNeeded()
}
func rowBy(id: String) -> ListViewRow? {
return repository.allItems.first(where: {$0.id == id})
}
func updateIfNeeded(index: Int?, next: Int?) {
let beforeUpdateRows = self.repository.visibleItems.count
var numberOfInserts = 0
var numberOfDeleted = 0
let rowsToHide = repository.itemsToDelete()
for row in rowsToHide {
if let noi = row.nextOperationIndex {
if let sectionIndex = index {
numberOfDeleted += 1
let indexPath = IndexPath(item: noi, section: sectionIndex)
logEvent("deleting row at index \(noi)")
self.controller?._tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
let rowsToCommit = repository.itemsToInsert()
for row in rowsToCommit {
if let noi = row.nextOperationIndex {
if let sectionIndex = next {
numberOfInserts += 1
let indexPath = IndexPath(item: noi, section: sectionIndex)
logEvent("inserting row at index \(noi)")
self.controller?._tableView.insertRows(at: [indexPath], with: .fade)
}
}
}
self.repository.invalidateCache(log: false)
logEvent("update finished for section: \(self.id) the index is current: \(index ?? -1), next: \(next ?? -1) inserts: \(numberOfInserts) deletes: \(numberOfDeleted) before: \(beforeUpdateRows) after: \(self.repository.visibleItems.count)")
}
func configIfNeeded() {
self.beginUpdatesIfNeeded()
if self.configHandler != nil {
self.configHandler?(self as! ListViewSection)
self.configHandler = nil
}
self.endUpdatesIfNeeded()
}
}
enum NextOperation {
case changeToHidden
case changoToVisible
case hidden
case visible
case changeToRemove
case changeToCommit
}
| mit | 46f863c7a235780b618476a8abdf6825 | 26.987903 | 246 | 0.583778 | 4.760631 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Storage/Database/SDSDatabaseStorage.swift | 1 | 20154 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
public protocol SDSDatabaseStorageDelegate {
var storageCoordinatorState: StorageCoordinatorState { get }
}
// MARK: -
@objc
public class SDSDatabaseStorage: SDSTransactable {
@objc
public static var shared: SDSDatabaseStorage {
return SSKEnvironment.shared.databaseStorage
}
private weak var delegate: SDSDatabaseStorageDelegate?
static public var shouldLogDBQueries: Bool = true
private var hasPendingCrossProcessWrite = false
private let crossProcess = SDSCrossProcess()
let observation = SDSDatabaseStorageObservation()
// MARK: - Initialization / Setup
@objc
public var yapPrimaryStorage: OWSPrimaryStorage {
return yapStorage.storage
}
private var _yapStorage: YAPDBStorageAdapter?
var yapStorage: YAPDBStorageAdapter {
if let storage = _yapStorage {
return storage
} else {
let storage = createYapStorage()
_yapStorage = storage
return storage
}
}
private var _grdbStorage: GRDBDatabaseStorageAdapter?
@objc
public var grdbStorage: GRDBDatabaseStorageAdapter {
if let storage = _grdbStorage {
return storage
} else {
let storage = createGrdbStorage()
_grdbStorage = storage
return storage
}
}
@objc
required init(delegate: SDSDatabaseStorageDelegate) {
self.delegate = delegate
super.init()
addObservers()
}
private func addObservers() {
// Cross process writes
switch FeatureFlags.storageMode {
case .ydb:
// YDB uses a different mechanism for cross process writes.
break
case .grdb, .grdbThrowawayIfMigrating:
crossProcess.callback = { [weak self] in
DispatchQueue.main.async {
self?.handleCrossProcessWrite()
}
}
NotificationCenter.default.addObserver(self,
selector: #selector(didBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
case .ydbTests, .grdbTests:
// No need to listen for cross process writes during tests.
break
}
}
deinit {
Logger.verbose("")
NotificationCenter.default.removeObserver(self)
}
// GRDB TODO: Remove
@objc
public static var shouldUseDisposableGrdb: Bool {
// We don't need to use a "disposable" database in our tests;
// TestAppContext ensures that our entire appSharedDataDirectoryPath
// is disposable in that case.
if .grdbThrowawayIfMigrating == FeatureFlags.storageMode {
// .grdbThrowawayIfMigrating allows us to re-test the migration on each launch.
// It doesn't make sense (and won't work) if there's no YDB database
// to migrate.
//
// Specifically, state persisted in NSUserDefaults won't be "throw away"
// and this will break the app if we throw away our database.
return StorageCoordinator.hasYdbFile
}
return false
}
private class func baseDir() -> URL {
return URL(fileURLWithPath: CurrentAppContext().appDatabaseBaseDirectoryPath(),
isDirectory: true)
}
@objc
public static var grdbDatabaseDirUrl: URL {
return GRDBDatabaseStorageAdapter.databaseDirUrl(baseDir: baseDir())
}
@objc
public static var grdbDatabaseFileUrl: URL {
return GRDBDatabaseStorageAdapter.databaseFileUrl(baseDir: baseDir())
}
func createGrdbStorage() -> GRDBDatabaseStorageAdapter {
if !canLoadGrdb {
Logger.error("storageMode: \(FeatureFlags.storageMode).")
Logger.error(
"StorageCoordinatorState: \(storageCoordinatorStateDescription).")
switch FeatureFlags.storageModeStrictness {
case .fail:
owsFail("Unexpected GRDB load.")
case .failDebug:
owsFailDebug("Unexpected GRDB load.")
case .log:
Logger.error("Unexpected GRDB load.")
}
}
if FeatureFlags.storageMode == .ydb {
owsFailDebug("Unexpected storage mode: \(FeatureFlags.storageMode)")
}
// crash if we can't read the DB.
do {
return try Bench(title: "Creating GRDB storage") {
return try GRDBDatabaseStorageAdapter(baseDir: type(of: self).baseDir())
}
} catch {
owsFail("\(error)")
}
}
@objc
public func deleteGrdbFiles() {
GRDBDatabaseStorageAdapter.removeAllFiles(baseDir: type(of: self).baseDir())
}
@objc
public func resetAllStorage() {
OWSStorage.resetAllStorage()
GRDBDatabaseStorageAdapter.resetAllStorage(baseDir: type(of: self).baseDir())
}
func createYapStorage() -> YAPDBStorageAdapter {
if !canLoadYdb {
Logger.error("storageMode: \(FeatureFlags.storageMode).")
Logger.error(
"StorageCoordinatorState: \(storageCoordinatorStateDescription).")
switch FeatureFlags.storageModeStrictness {
case .fail:
owsFail("Unexpected YDB load.")
case .failDebug:
owsFailDebug("Unexpected YDB load.")
case .log:
Logger.error("Unexpected YDB load.")
}
}
return Bench(title: "Creating YDB storage") {
let yapPrimaryStorage = OWSPrimaryStorage()
return YAPDBStorageAdapter(storage: yapPrimaryStorage)
}
}
// MARK: -
@objc
public func newDatabaseQueue() -> SDSAnyDatabaseQueue {
var yapDatabaseQueue: YAPDBDatabaseQueue?
var grdbDatabaseQueue: GRDBDatabaseQueue?
switch FeatureFlags.storageMode {
case .ydb:
yapDatabaseQueue = yapStorage.newDatabaseQueue()
break
case .grdb, .grdbThrowawayIfMigrating:
// If we're about to migrate or already migrating,
// we need to create a YDB queue as well.
if storageCoordinatorState == .beforeYDBToGRDBMigration ||
storageCoordinatorState == .duringYDBToGRDBMigration {
yapDatabaseQueue = yapStorage.newDatabaseQueue()
}
grdbDatabaseQueue = grdbStorage.newDatabaseQueue()
case .ydbTests, .grdbTests:
yapDatabaseQueue = yapStorage.newDatabaseQueue()
grdbDatabaseQueue = grdbStorage.newDatabaseQueue()
break
}
return SDSAnyDatabaseQueue(yapDatabaseQueue: yapDatabaseQueue,
grdbDatabaseQueue: grdbDatabaseQueue,
crossProcess: crossProcess)
}
// MARK: - Touch
@objc(touchInteraction:transaction:)
public func touch(interaction: TSInteraction, transaction: SDSAnyWriteTransaction) {
switch transaction.writeTransaction {
case .yapWrite(let yap):
let uniqueId = interaction.uniqueId
yap.touchObject(forKey: uniqueId, inCollection: TSInteraction.collection())
case .grdbWrite(let grdb):
UIDatabaseObserver.serializedSync {
if let conversationViewDatabaseObserver = grdbStorage.conversationViewDatabaseObserver {
conversationViewDatabaseObserver.didTouch(interaction: interaction, transaction: grdb)
} else if AppReadiness.isAppReady() {
owsFailDebug("conversationViewDatabaseObserver was unexpectedly nil")
}
if let genericDatabaseObserver = grdbStorage.genericDatabaseObserver {
genericDatabaseObserver.didTouch(interaction: interaction,
transaction: grdb)
} else if AppReadiness.isAppReady() {
owsFailDebug("genericDatabaseObserver was unexpectedly nil")
}
GRDBFullTextSearchFinder.modelWasUpdated(model: interaction, transaction: grdb)
}
}
}
@objc(touchThread:transaction:)
public func touch(thread: TSThread, transaction: SDSAnyWriteTransaction) {
switch transaction.writeTransaction {
case .yapWrite(let yap):
yap.touchObject(forKey: thread.uniqueId, inCollection: TSThread.collection())
case .grdbWrite(let grdb):
UIDatabaseObserver.serializedSync {
if let homeViewDatabaseObserver = grdbStorage.homeViewDatabaseObserver {
homeViewDatabaseObserver.didTouch(threadId: thread.uniqueId, transaction: grdb)
} else if AppReadiness.isAppReady() {
owsFailDebug("homeViewDatabaseObserver was unexpectedly nil")
}
if let genericDatabaseObserver = grdbStorage.genericDatabaseObserver {
genericDatabaseObserver.didTouchThread(transaction: grdb)
} else if AppReadiness.isAppReady() {
owsFailDebug("genericDatabaseObserver was unexpectedly nil")
}
GRDBFullTextSearchFinder.modelWasUpdated(model: thread, transaction: grdb)
}
}
}
// MARK: - Cross Process Notifications
private func handleCrossProcessWrite() {
AssertIsOnMainThread()
Logger.info("")
guard CurrentAppContext().isMainApp else {
return
}
if CurrentAppContext().isMainAppAndActive {
// If already active, update immediately.
postCrossProcessNotification()
} else {
// If not active, set flag to update when we become active.
hasPendingCrossProcessWrite = true
}
}
@objc func didBecomeActive() {
AssertIsOnMainThread()
guard hasPendingCrossProcessWrite else {
return
}
hasPendingCrossProcessWrite = false
postCrossProcessNotification()
}
@objc
public static let didReceiveCrossProcessNotification = Notification.Name("didReceiveCrossProcessNotification")
private func postCrossProcessNotification() {
Logger.info("")
// TODO: The observers of this notification will inevitably do
// expensive work. It'd be nice to only fire this event
// if this had any effect, if the state of the database
// has changed.
//
// In the meantime, most (all?) cross process write notifications
// will be delivered to the main app while it is inactive. By
// de-bouncing notifications while inactive and only updating
// once when we become active, we should be able to effectively
// skip most of the perf cost.
NotificationCenter.default.postNotificationNameAsync(SDSDatabaseStorage.didReceiveCrossProcessNotification, object: nil)
}
// MARK: - Misc.
@objc
public func logFileSizes() {
Logger.info("Database : \(databaseFileSize)")
Logger.info("\t WAL file size: \(databaseWALFileSize)")
Logger.info("\t SHM file size: \(databaseSHMFileSize)")
}
// MARK: - Generic Observation
@objc(addDatabaseStorageObserver:)
public func add(databaseStorageObserver: SDSDatabaseStorageObserver) {
observation.add(databaseStorageObserver: databaseStorageObserver)
}
// MARK: - SDSTransactable
@objc
public func uiRead(block: @escaping (SDSAnyReadTransaction) -> Void) {
switch dataStoreForReads {
case .grdb:
do {
try grdbStorage.uiRead { transaction in
block(transaction.asAnyRead)
}
} catch {
owsFail("error: \(error)")
}
case .ydb:
yapStorage.uiRead { transaction in
block(transaction.asAnyRead)
}
}
}
@objc
public override func read(block: @escaping (SDSAnyReadTransaction) -> Void) {
switch dataStoreForReads {
case .grdb:
do {
try grdbStorage.read { transaction in
block(transaction.asAnyRead)
}
} catch {
owsFail("error: \(error)")
}
case .ydb:
yapStorage.read { transaction in
block(transaction.asAnyRead)
}
}
}
@objc
public override func write(block: @escaping (SDSAnyWriteTransaction) -> Void) {
switch dataStoreForWrites {
case .grdb:
do {
try grdbStorage.write { transaction in
Bench(title: "Slow Write Transaction", logIfLongerThan: 0.1) {
block(transaction.asAnyWrite)
}
}
} catch {
owsFail("error: \(error)")
}
case .ydb:
yapStorage.write { transaction in
Bench(title: "Slow Write Transaction", logIfLongerThan: 0.1) {
block(transaction.asAnyWrite)
}
}
}
crossProcess.notifyChangedAsync()
}
public func uiReadThrows(block: @escaping (SDSAnyReadTransaction) throws -> Void) throws {
switch dataStoreForReads {
case .grdb:
try grdbStorage.uiReadThrows { transaction in
try autoreleasepool {
try block(transaction.asAnyRead)
}
}
case .ydb:
try yapStorage.uiReadThrows { transaction in
try block(transaction.asAnyRead)
}
}
}
public func uiReadReturningResult<T>(block: @escaping (SDSAnyReadTransaction) -> T) -> T {
var value: T!
uiRead { (transaction) in
value = block(transaction)
}
return value
}
}
// MARK: - Coordination
extension SDSDatabaseStorage {
@objc
public enum DataStore: Int {
case ydb
case grdb
}
private var storageCoordinatorState: StorageCoordinatorState {
guard let delegate = delegate else {
owsFail("Missing delegate.")
}
return delegate.storageCoordinatorState
}
private var storageCoordinatorStateDescription: String {
return NSStringFromStorageCoordinatorState(storageCoordinatorState)
}
@objc
var dataStoreForReads: DataStore {
// Before the migration starts and during the migration, read from YDB.
switch storageCoordinatorState {
case .YDB, .beforeYDBToGRDBMigration, .duringYDBToGRDBMigration:
return .ydb
case .GRDB:
return .grdb
case .ydbTests:
return .ydb
case .grdbTests:
return .grdb
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return .grdb
}
}
@objc
var dataStoreForWrites: DataStore {
// Before the migration starts (but NOT during the migration), write to YDB.
switch storageCoordinatorState {
case .YDB, .beforeYDBToGRDBMigration:
return .ydb
case .duringYDBToGRDBMigration, .GRDB:
return .grdb
case .ydbTests:
return .ydb
case .grdbTests:
return .grdb
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return .grdb
}
}
var dataStoreForReporting: DataStore {
switch storageCoordinatorState {
case .YDB:
return .ydb
case .beforeYDBToGRDBMigration, .duringYDBToGRDBMigration, .GRDB:
return .grdb
case .ydbTests:
return .ydb
case .grdbTests:
return .grdb
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return .grdb
}
}
@objc
var canLoadYdb: Bool {
switch storageCoordinatorState {
case .YDB, .beforeYDBToGRDBMigration, .duringYDBToGRDBMigration:
return true
case .GRDB:
return false
case .ydbTests, .grdbTests:
return true
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return true
}
}
@objc
var canReadFromYdb: Bool {
// We can read from YDB before and during the YDB-to-GRDB migration.
switch storageCoordinatorState {
case .YDB, .beforeYDBToGRDBMigration, .duringYDBToGRDBMigration:
return true
case .GRDB:
return false
case .ydbTests, .grdbTests:
return true
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return true
}
}
@objc
var canWriteToYdb: Bool {
// We can write to YDB before but not during the YDB-to-GRDB migration.
switch storageCoordinatorState {
case .YDB, .beforeYDBToGRDBMigration:
return true
case .duringYDBToGRDBMigration, .GRDB:
return false
case .ydbTests, .grdbTests:
return true
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return true
}
}
@objc
var canLoadGrdb: Bool {
switch storageCoordinatorState {
case .YDB:
return false
case .beforeYDBToGRDBMigration, .duringYDBToGRDBMigration, .GRDB:
return true
case .ydbTests, .grdbTests:
return true
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return true
}
}
@objc
var canReadFromGrdb: Bool {
// We can read from GRDB during but not before the YDB-to-GRDB migration.
switch storageCoordinatorState {
case .YDB, .beforeYDBToGRDBMigration:
return false
case .duringYDBToGRDBMigration, .GRDB:
return true
case .ydbTests, .grdbTests:
return true
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return true
}
}
@objc
var canWriteToGrdb: Bool {
// We can write to GRDB during but not before the YDB-to-GRDB migration.
switch storageCoordinatorState {
case .YDB, .beforeYDBToGRDBMigration:
return false
case .duringYDBToGRDBMigration, .GRDB:
return true
case .ydbTests, .grdbTests:
return true
@unknown default:
owsFailDebug("Unknown state: \(storageCoordinatorState)")
return true
}
}
}
// MARK: -
protocol SDSDatabaseStorageAdapter {
associatedtype ReadTransaction
associatedtype WriteTransaction
func uiRead(block: @escaping (ReadTransaction) -> Void) throws
func read(block: @escaping (ReadTransaction) -> Void) throws
func write(block: @escaping (WriteTransaction) -> Void) throws
}
// MARK: -
@objc
public class SDS: NSObject {
@objc
public class func fitsInInt64(_ value: UInt64) -> Bool {
return value <= Int64.max
}
@objc
public func fitsInInt64(_ value: UInt64) -> Bool {
return SDS.fitsInInt64(value)
}
@objc(fitsInInt64WithNSNumber:)
public class func fitsInInt64(nsNumber value: NSNumber) -> Bool {
return fitsInInt64(value.uint64Value)
}
@objc(fitsInInt64WithNSNumber:)
public func fitsInInt64(nsNumber value: NSNumber) -> Bool {
return SDS.fitsInInt64(nsNumber: value)
}
}
| gpl-3.0 | 3c8a31e19f03dc2ed9e231816dcec819 | 31.092357 | 128 | 0.594373 | 5.067639 | false | false | false | false |
dimix/ImageSlideShow | Demo/Demo/ViewController.swift | 1 | 2771 | //
// ViewController.swift
// Demo
//
// Created by Dimitri Giani on 16/10/2016.
// Copyright © 2016 Dimitri Giani. All rights reserved.
//
import UIKit
// Very bad Class, but just for Demo ;-)
class Image: NSObject, ImageSlideShowProtocol
{
private let url: URL
let title: String?
init(title: String, url: URL) {
self.title = title
self.url = url
}
func slideIdentifier() -> String {
return String(describing: url)
}
func image(completion: @escaping (_ image: UIImage?, _ error: Error?) -> Void) {
let session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: self.url) { data, response, error in
if let data = data, error == nil
{
let image = UIImage(data: data)
completion(image, nil)
}
else
{
completion(nil, error)
}
}.resume()
}
}
class ViewController: UIViewController {
fileprivate var images:[Image] = []
override func viewDidLoad() {
super.viewDidLoad()
self.generateImages()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func generateImages()
{
let scale:Int = Int(UIScreen.main.scale)
let height:Int = Int(view.frame.size.height) * scale
let width:Int = Int(view.frame.size.width) * scale
images = [
Image(title: "Image 1", url: URL(string: "https://dummyimage.com/\(width)x\(height)/09a/fff.png&text=Image+1")!),
Image(title: "Image 2", url: URL(string: "https://dummyimage.com/\(600)x\(600)/09b/fff.png&text=Image+2")!),
Image(title: "Image 3", url: URL(string: "https://dummyimage.com/\(width)x\(height)/09c/fff.png&text=Image+3")!),
Image(title: "Image 4", url: URL(string: "https://dummyimage.com/\(600)x\(600)/09d/fff.png&text=Image+4")!),
Image(title: "Image 5", url: URL(string: "https://dummyimage.com/\(width)x\(height)/09e/fff.png&text=Image+5")!),
Image(title: "Image 6", url: URL(string: "https://dummyimage.com/\(width)x\(height)/09f/fff.png&text=Image+6")!),
]
}
@IBAction func presentSlideShow(_ sender:AnyObject?)
{
ImageSlideShowViewController.presentFrom(self){ [weak self] controller in
controller.dismissOnPanGesture = true
controller.slides = self?.images
controller.enableZoom = true
controller.controllerDidDismiss = {
debugPrint("Controller Dismissed")
debugPrint("last index viewed: \(controller.currentIndex)")
}
controller.slideShowViewDidLoad = {
debugPrint("Did Load")
}
controller.slideShowViewWillAppear = { animated in
debugPrint("Will Appear Animated: \(animated)")
}
controller.slideShowViewDidAppear = { animated in
debugPrint("Did Appear Animated: \(animated)")
}
}
}
}
| mit | 84caf3a76cfdc6944efc0a49705c535a | 25.132075 | 116 | 0.67148 | 3.341375 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureOnboarding/Sources/FeatureOnboardingUI/OnboardingChecklist/OnboardingChecklistState.swift | 1 | 16574 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainComponentLibrary
import BlockchainNamespace
import Combine
import ComposableArchitecture
import ComposableNavigation
import Errors
import Foundation
import Localization
import SwiftUI
import ToolKit
public enum OnboardingChecklist {
public struct Item: Identifiable, Hashable {
public enum Identifier: Hashable {
case verifyIdentity
case linkPaymentMethods
case buyCrypto
case requestCrypto
}
public let id: Identifier
public let icon: Icon
public let title: String
public let detail: String?
public let actionColor: Color
public let accentColor: Color
public let backgroundColor: Color
}
public enum Route: NavigationRoute {
case fullScreenChecklist
@ViewBuilder
public func destination(in store: Store<State, Action>) -> some View {
switch self {
case .fullScreenChecklist:
OnboardingChecklistView(store: store)
}
}
}
public struct State: Equatable, NavigationState {
public struct Promotion: Equatable {
public var visible: Bool
public var id: L & I_blockchain_ux_onboarding_type_promotion
public var ux: UX.Dialog
public static func == (lhs: OnboardingChecklist.State.Promotion, rhs: OnboardingChecklist.State.Promotion) -> Bool {
lhs.visible == rhs.visible
&& lhs.id == rhs.id
&& lhs.ux == rhs.ux
}
}
var promotion: Promotion?
var isSynchronised: Bool = false
var items: [Item]
var pendingItems: Set<Item>
var completedItems: Set<Item>
public var route: RouteIntent<Route>?
public init() {
items = OnboardingChecklist.allItems
pendingItems = []
completedItems = []
}
func hasCompleted(_ item: Item) -> Bool {
completedItems.contains(item)
}
var firstIncompleteItem: Item? {
items.first { !hasCompleted($0) }
}
}
public enum ItemSelectionSource {
case item
case callToActionButton
}
public enum Action: Equatable, NavigationAction {
case route(RouteIntent<Route>?)
case didSelectItem(Item.Identifier, ItemSelectionSource)
case dismissFullScreenChecklist
case presentFullScreenChecklist
case startObservingUserState
case stopObservingUserState
case userStateDidChange(UserState)
case updatePromotion
case updatedPromotion(State.Promotion?)
}
public struct Environment {
let app: AppProtocol
/// A publisher that streams `UserState` values on subscription and every time the state changes
let userState: AnyPublisher<UserState, Never>
/// A closure that presents the Buy Flow from the top-most view controller on screen and automatically dismissed the presented flow when done.
/// The closure takes a `completion` closure. Call it with `true` if the user completed the presented flow by taking the desired action. Call it with `false` if the flow was dismissed by the user.
/// This should really return a `View` and be used to generate a `RouteIntent`, but we don't have such a `View` yet or the flow is complex.
let presentBuyFlow: (@escaping (Bool) -> Void) -> Void
/// A closure that presents the KYC Flow from the top-most view controller on screen and automatically dismissed the presented flow when done.
/// The closure takes a `completion` closure. Call it with `true` if the user completed the presented flow by taking the desired action. Call it with `false` if the flow was dismissed by the user.
/// This should really return a `View` and be used to generate a `RouteIntent`, but we don't have such a `View` yet or the flow is complex.
let presentKYCFlow: (@escaping (Bool) -> Void) -> Void
/// A closure that presents the Payment Method Linking Flow from the top-most view controller on screen and automatically dismissed the presented flow when done.
/// The closure takes a `completion` closure. Call it with `true` if the user completed the presented flow by taking the desired action. Call it with `false` if the flow was dismissed by the user.
/// This should really return a `View` and be used to generate a `RouteIntent`, but we don't have such a `View` yet or the flow is complex.
let presentPaymentMethodLinkingFlow: (@escaping (Bool) -> Void) -> Void
/// A `DispatchQueue` running on the main thread.
let mainQueue: AnySchedulerOf<DispatchQueue>
let analyticsRecorder: AnalyticsEventRecorderAPI
public init(
app: AppProtocol,
userState: AnyPublisher<UserState, Never>,
presentBuyFlow: @escaping (@escaping (Bool) -> Void) -> Void,
presentKYCFlow: @escaping (@escaping (Bool) -> Void) -> Void,
presentPaymentMethodLinkingFlow: @escaping (@escaping (Bool) -> Void) -> Void,
analyticsRecorder: AnalyticsEventRecorderAPI,
mainQueue: AnySchedulerOf<DispatchQueue> = .main
) {
self.app = app
self.userState = userState
self.presentBuyFlow = presentBuyFlow
self.presentKYCFlow = presentKYCFlow
self.presentPaymentMethodLinkingFlow = presentPaymentMethodLinkingFlow
self.analyticsRecorder = analyticsRecorder
self.mainQueue = mainQueue
}
}
public static let reducer = Reducer<State, Action, Environment> { state, action, environment in
struct UserStateObservableIdentifier: Hashable {}
struct UserDidUpdateIdentifier: Hashable {}
struct PromotionIdentifier: Hashable {}
switch action {
case .route(let route):
state.route = route
return .none
case .didSelectItem(let item, _):
let completedItems = state.completedItems
return .fireAndForget {
environment.presentOnboaringFlow(upTo: item, completedItems: completedItems)
}
case .dismissFullScreenChecklist:
return .dismiss()
case .presentFullScreenChecklist:
return .enter(into: .fullScreenChecklist, context: .none)
case .startObservingUserState:
return .merge(
.concatenate(
.cancel(id: UserDidUpdateIdentifier()),
environment.app.on(blockchain.user.event.did.update)
.receive(on: environment.mainQueue)
.eraseToEffect { _ in OnboardingChecklist.Action.updatePromotion }
.cancellable(id: UserDidUpdateIdentifier())
),
.concatenate(
// cancel any active observation of state to avoid duplicates
.cancel(id: UserStateObservableIdentifier()),
// start observing the user state
environment
.userState
.receive(on: environment.mainQueue)
.map(OnboardingChecklist.Action.userStateDidChange)
.eraseToEffect()
.cancellable(id: UserStateObservableIdentifier())
)
)
case .stopObservingUserState:
return .cancel(
ids: [UserStateObservableIdentifier(), UserDidUpdateIdentifier(), PromotionIdentifier()]
)
case .userStateDidChange(let userState):
state.isSynchronised = true
state.completedItems = userState.completedOnboardingChecklistItems
state.pendingItems = userState.kycStatus == .verificationPending ? [.verifyIdentity] : []
return Effect(value: .updatePromotion)
case .updatePromotion:
return .concatenate(
.cancel(id: PromotionIdentifier()),
.task(priority: .userInitiated) { @MainActor in
do {
let app = environment.app
let promotion: L & I_blockchain_ux_onboarding_type_promotion = try {
switch try app.state.get(blockchain.user.account.tier) as Tag {
case blockchain.user.account.tier.none:
return try app.state.get(blockchain.user.email.is.verified)
? blockchain.ux.onboarding.promotion.cowboys.raffle
: blockchain.ux.onboarding.promotion.cowboys.welcome
case blockchain.user.account.tier.silver:
do {
return try [
blockchain.user.account.kyc.state.under_review[],
blockchain.user.account.kyc.state.pending[],
blockchain.user.account.kyc.state.verified[]
].contains(app.state.get(blockchain.user.account.kyc[blockchain.user.account.tier.gold].state))
? blockchain.ux.onboarding.promotion.cowboys.user.kyc.is.under.review
: blockchain.ux.onboarding.promotion.cowboys.verify.identity
} catch {
return blockchain.ux.onboarding.promotion.cowboys.verify.identity
}
case _:
return blockchain.ux.onboarding.promotion.cowboys.refer.friends
}
}()
let isEnabled: Bool = try await app.get(blockchain.ux.onboarding.promotion.cowboys.is.enabled)
return try await .updatedPromotion(
State.Promotion(
visible: app.get(blockchain.user.is.cowboy.fan) && isEnabled,
id: promotion,
ux: app.get(promotion.announcement)
)
)
} catch {
return .updatedPromotion(nil)
}
}
.cancellable(id: PromotionIdentifier())
)
case .updatedPromotion(let promotion):
state.promotion = promotion
return .none
}
}
.analytics()
}
extension OnboardingChecklist.Environment {
// swiftlint:disable:next cyclomatic_complexity
fileprivate func presentOnboaringFlow(
upTo item: OnboardingChecklist.Item.Identifier,
completedItems: Set<OnboardingChecklist.Item>
) {
switch item {
case .verifyIdentity:
presentKYCFlow { _ in
// no-op: flow ends here
}
case .linkPaymentMethods:
if completedItems.contains(.verifyIdentity) {
presentPaymentMethodLinkingFlow { [presentBuyFlow] didCompleteLinking in
guard didCompleteLinking else { return }
presentBuyFlow { _ in
// no-op: flow ends here
}
}
} else {
presentKYCFlow { [presentPaymentMethodLinkingFlow] didCompleteKYC in
guard didCompleteKYC else { return }
presentPaymentMethodLinkingFlow { _ in
// no-op: flow ends here
}
}
}
case .buyCrypto:
if completedItems.contains(.linkPaymentMethod) {
presentBuyFlow { _ in
// no-op: flow ends here
}
} else if completedItems.contains(.verifyIdentity) {
presentPaymentMethodLinkingFlow { [presentBuyFlow] didAddPaymentMethod in
guard didAddPaymentMethod else { return }
presentBuyFlow { _ in
// no-op: flow ends here
}
}
} else {
presentKYCFlow { [presentPaymentMethodLinkingFlow, presentBuyFlow] didCompleteKYC in
guard didCompleteKYC else { return }
presentPaymentMethodLinkingFlow { didAddPaymentMethod in
guard didAddPaymentMethod else { return }
presentBuyFlow { _ in
// no-op: flow ends here
}
}
}
}
default:
unimplemented()
}
}
}
extension OnboardingChecklist.Item {
var pendingDetail: String {
LocalizationConstants.Onboarding.Checklist.pendingPlaceholder
}
}
extension OnboardingChecklist.Item {
static let verifyIdentity = OnboardingChecklist.Item(
id: .verifyIdentity,
icon: Icon.identification,
title: LocalizationConstants.Onboarding.Checklist.verifyIdentityTitle,
detail: LocalizationConstants.Onboarding.Checklist.verifyIdentitySubtitle,
actionColor: .purple500,
accentColor: .purple600,
backgroundColor: .purple000
)
static let linkPaymentMethod = OnboardingChecklist.Item(
id: .linkPaymentMethods,
icon: Icon.bank,
title: LocalizationConstants.Onboarding.Checklist.linkPaymentMethodsTitle,
detail: LocalizationConstants.Onboarding.Checklist.linkPaymentMethodsSubtitle,
actionColor: .semantic.primary,
accentColor: .semantic.primary,
backgroundColor: .semantic.blueBG
)
static let buyCrypto = OnboardingChecklist.Item(
id: .buyCrypto,
icon: Icon.cart,
title: LocalizationConstants.Onboarding.Checklist.buyCryptoTitle,
detail: LocalizationConstants.Onboarding.Checklist.buyCryptoSubtitle,
actionColor: .semantic.success,
accentColor: .semantic.success,
backgroundColor: .semantic.greenBG
)
static let buyCryptoAlternative = OnboardingChecklist.Item(
id: .buyCrypto,
icon: Icon.cart,
title: LocalizationConstants.Onboarding.Checklist.buyCryptoTitle,
detail: nil,
actionColor: .semantic.primary,
accentColor: .semantic.primary,
backgroundColor: .semantic.blueBG
)
static let requestCrypto = OnboardingChecklist.Item(
id: .requestCrypto,
icon: Icon.qrCode,
title: LocalizationConstants.Onboarding.Checklist.requestCryptoTitle,
detail: LocalizationConstants.Onboarding.Checklist.requestCryptoSubtitle,
actionColor: .teal500,
accentColor: .teal500,
backgroundColor: .teal000
)
}
extension OnboardingChecklist {
fileprivate static let allItems: [OnboardingChecklist.Item] = [
.verifyIdentity,
.linkPaymentMethod,
.buyCrypto
]
}
extension Color {
fileprivate static let purple000 = Color(
red: 239 / 255,
green: 236 / 255,
blue: 254 / 255
)
fileprivate static let purple500 = Color(
red: 115 / 255,
green: 73 / 255,
blue: 242 / 255
)
fileprivate static let purple600 = Color(
red: 83 / 255,
green: 34 / 255,
blue: 229 / 255
)
fileprivate static let teal000 = Color(
red: 230 / 255,
green: 248 / 255,
blue: 250 / 255
)
fileprivate static let teal500 = Color(
red: 18 / 255,
green: 165 / 255,
blue: 178 / 255
)
}
extension UserState {
fileprivate var completedOnboardingChecklistItems: Set<OnboardingChecklist.Item> {
var result = Set<OnboardingChecklist.Item>()
if kycStatus.canBuyCrypto {
result.insert(.verifyIdentity)
}
if hasLinkedPaymentMethods {
result.insert(.linkPaymentMethod)
}
if hasEverPurchasedCrypto {
result.insert(.buyCrypto)
}
return result
}
private var hasCompletedAllOnboardingChecklistItems: Bool {
completedOnboardingChecklistItems == Set(OnboardingChecklist.allItems)
}
}
| lgpl-3.0 | fc6337b1b098c81445835514a675165b | 37.631702 | 204 | 0.587643 | 5.43199 | false | false | false | false |
FardadCo/LaraCrypt | LaraCrypt/Classes/LaraCrypt.swift | 1 | 8266 | //
// LaraCrypt.swift
// LaraCrypt
//
// Created by Fardad Co
// Copyright © 2017 Fardad Co. All rights reserved.
//
import UIKit
extension Data {
//MARK: Converting string to Hex
func hexEncodedString() -> String {
return map { String(format: "%02hhx", $0) }.joined()
}
}
extension String {
func indexer(from: Int) -> Index {
return self.index(startIndex, offsetBy: from)
}
func substr(from: Int) -> String {
let fromIndex = indexer(from: from)
return substring(from: fromIndex)
}
func substr(to: Int) -> String {
let toIndex = indexer(from: to)
return substring(to: toIndex)
}
func substr(with r: Range<Int>) -> String {
let startIndex = indexer(from: r.lowerBound)
let endIndex = indexer(from: r.upperBound)
return substring(with: startIndex..<endIndex)
}
}
public class LaraCrypt: NSObject {
//MARK: Generating random string with 16 char length
func generateRandomBytes() -> String? {
var keyData = Data(count: 10)
let result = keyData.withUnsafeMutableBytes {
(mutableBytes: UnsafeMutablePointer<UInt8>) -> Int32 in
SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
}
if result == errSecSuccess {
return keyData.base64EncodedString()
} else {
print("Problem generating random bytes")
return nil
}
}
//MARK: Converting data format to array of UInt8
func DATA_TO_UINT8(_ d:Data) -> Array<UInt8> {
return d.withUnsafeBytes {
[UInt8](UnsafeBufferPointer(start: $0, count: (d.count)))
}
}
//MARK: Converting string to JSON model
func stringSerilizer(String str:String) -> String {
return String(format:"s:%lu:\"%@\";",str.characters.count,str)
}
//MARK: Converting JSON to string model
func stringUnserilizer(String str:String) -> String {
var index:Int = 0
for (i,char) in str.characters.enumerated() {
if char == "\"" {
index = i
break
}
}
let stringChangedA:String = str.substr(from: index+1)
let stringChangedB:String = stringChangedA.substr(to: stringChangedA.characters.count-2)
return stringChangedB
}
//MARK: Converting JSON to Dictionary model
func convertToDictionary(text: String) -> [String: String]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: String]
} catch {
print(error.localizedDescription)
}
}
return nil
}
//MARK: Making hmac like hash_hmac in PHP
func HMAC_CREATOR(MIX_STR mixStr:String,KEY_DATA_UINT8 keyDataUint8:Array<UInt8>) -> String {
let signatureData : Data = mixStr.data(using: .utf8)!
let digest = UnsafeMutablePointer<UInt8>.allocate(capacity:Int(CC_SHA256_DIGEST_LENGTH))
var hmacContext = CCHmacContext()
CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), (keyDataUint8), (keyDataUint8.count))
CCHmacUpdate(&hmacContext, [UInt8](signatureData), [UInt8](signatureData).count)
CCHmacFinal(&hmacContext, digest)
let macData = Data(bytes: digest, count: Int(CC_SHA256_DIGEST_LENGTH))
return macData.hexEncodedString()
}
//MARK: Encrypting data with AES-256-CBC method
func AES256CBC(data:Data, keyData:Data, ivData:Data, operation:Int) -> Data {
let cryptLength = size_t(data.count + kCCBlockSizeAES128)
var cryptData = Data(count:cryptLength)
let keyLength = size_t(kCCKeySizeAES256)
let options = CCOptions(kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
data.withUnsafeBytes {dataBytes in
ivData.withUnsafeBytes {ivBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(operation),
CCAlgorithm(kCCAlgorithmAES),
options,
keyBytes, keyLength,
ivBytes,
dataBytes, data.count,
cryptBytes, cryptLength,
&numBytesEncrypted)
}
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.removeSubrange(numBytesEncrypted..<cryptData.count)
} else {
print("Error: \(cryptStatus)")
}
return cryptData;
}
//MARK: Laravel encryption method
public func encrypt(Message message:String,Key key:String) -> String {
//Preparing initial data
let serilizedMessage = stringSerilizer(String: message)
let serilizedMessageData:Data = serilizedMessage.data(using: .utf8)!
let keyData:Data = Data(base64Encoded: key)!
let keyDataUint8 = DATA_TO_UINT8(keyData)
let iv :String = generateRandomBytes()!
let ivBase6Str:String = Data(iv.utf8).base64EncodedString()
let ivData:Data = iv.data(using: .utf8)!
//Encrypting data
let encData = AES256CBC(data: serilizedMessageData, keyData: keyData, ivData: ivData, operation: kCCEncrypt)
//Converting encrypted data to base64
let encDataBase64Str = encData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
//Mixing base64 iv with base64 encrypted data
let mixStr:String = String(format:"%@%@",ivBase6Str,encDataBase64Str)
//Creating Hmac from mixed string
let macHexStr:String = HMAC_CREATOR(MIX_STR: mixStr, KEY_DATA_UINT8: keyDataUint8)
//Combinig base64 iv with base64 encrypted data and Hmac
let combineDict:Dictionary = ["iv":ivBase6Str,"value":encDataBase64Str,"mac":macHexStr]
do {
let jsonData = try JSONSerialization.data(withJSONObject: combineDict, options: .init(rawValue: 0))
let jsonBase64Str_ENCRYPTED:String = jsonData.base64EncodedString()
return jsonBase64Str_ENCRYPTED
} catch {
print(error.localizedDescription)
return (error.localizedDescription)
}
}
//MARK: Laravel decryption method
public func decrypt(Message message:String,Key key:String) -> String {
//Preparing initial data
let keyData:Data = Data(base64Encoded: key)!
let messageDecodedData = NSData(base64Encoded: message, options:.ignoreUnknownCharacters)
let messageDecodedString = NSString(data: messageDecodedData! as Data, encoding: String.Encoding.utf8.rawValue)
//Combinig base64 iv with base64 encrypted data and Hmac
let combineDict:Dictionary = convertToDictionary(text: messageDecodedString! as String)!
//IV
let ivStr:String = combineDict["iv"]!
let ivData:Data = Data(base64Encoded: ivStr)!
//Value
let value:String = combineDict["value"]!
let valueData:Data = Data(base64Encoded: value)!
//Decrypting data
let decData = AES256CBC(data: valueData, keyData: keyData, ivData: ivData, operation: kCCDecrypt)
//Decrypted UInt8
let decDataUInt8:Array<UInt8> = DATA_TO_UINT8(decData)
//Decrypted Data
let decAsData = NSData(bytes: decDataUInt8 as [UInt8], length: decDataUInt8.count)
//Serialized Decrypted Message
let deceSrializedString:String = String(data: decAsData as Data, encoding: String.Encoding.utf8)!
//Unserialized Decrypted Message
let decrypted:String = stringUnserilizer(String: deceSrializedString)
return decrypted
}
}
| mit | 9fd58ac2dfa7d7b898105d00f3acbc9f | 33.873418 | 119 | 0.598911 | 4.489408 | false | false | false | false |
Onizuka89/Simple-Comic | Classes/Progress Bar/TSSTInfoWindow.swift | 1 | 1696 | //
// TSSTInfoWindow.swift
// SimpleComic
//
// Created by C.W. Betts on 1/17/16.
// Copyright © 2016 Dancing Tortoise Software. All rights reserved.
//
import Cocoa
/// This panel subclass is used by both the loupe,
/// and the speech bubble styled page preview.
class TSSTInfoWindow: NSPanel {
override init(contentRect: NSRect, styleMask aStyle: Int, backing bufferingType: NSBackingStoreType, `defer` flag: Bool) {
super.init(contentRect: contentRect, styleMask: NSBorderlessWindowMask, backing: bufferingType, `defer`: flag)
opaque = false
ignoresMouseEvents = true
}
required init?(coder: NSCoder) {
super.init(coder: coder)
styleMask = NSBorderlessWindowMask
opaque = false
ignoresMouseEvents = true
}
func caretAtPoint(point: NSPoint, size: NSSize, withLimitLeft left: CGFloat, right: CGFloat) {
let limitWidth = right - left
let relativePosition = (point.x - left) / limitWidth
let offset = size.width * relativePosition
let frameRect = NSMakeRect( point.x - offset - 10, point.y, size.width + 20, size.height + 25)
(contentView as? TSSTInfoView)?.caretPosition = offset + 10
setFrame(frameRect, display: true, animate: false)
invalidateShadow()
}
func centerAtPoint(center: NSPoint) {
let frame = self.frame
setFrameOrigin(NSPoint(x: center.x - frame.width / 2, y: center.y - frame.height / 2))
invalidateShadow()
}
func resizeToDiameter(diameter: CGFloat) {
let frame = self.frame
let center = NSPoint(x: frame.minX + frame.width / 2, y: frame.minY + frame.height / 2)
setFrame(NSRect(x: center.x - diameter / 2, y: center.y - diameter / 2, width: diameter, height: diameter),
display: true,
animate: false)
}
}
| mit | f9418a54a1e800df32f9dee370b76d46 | 31.596154 | 123 | 0.715044 | 3.538622 | false | false | false | false |
chrisjmendez/swift-exercises | Walkthroughs/NextSteps/NextSteps/WalkthroughViewController.swift | 1 | 2125 | //
// WalkthroughViewController.swift
// NextSteps
//
// Created by Chris Mendez on 2/23/16.
// Copyright © 2016 Chris Mendez. All rights reserved.
//
import UIKit
import Pages
class WalkthroughViewController: UIViewController {
var pages:PagesController?
func pagesControllerInCode() -> PagesController {
let viewController1 = UIViewController()
viewController1.view.backgroundColor = .blackColor()
viewController1.title = "Controller A"
let viewController2 = UIViewController()
viewController2.view.backgroundColor = .blueColor()
viewController2.title = "Controller B"
let viewController3 = UIViewController()
viewController3.view.backgroundColor = .redColor()
viewController3.title = "Controller C"
let viewController4 = UIViewController()
viewController4.view.backgroundColor = .yellowColor()
viewController4.title = "Controller D"
let pages = PagesController([viewController1,
viewController2,
viewController3,
viewController4
])
pages.enableSwipe = true
pages.showBottomLine = true
return pages
}
func pagesControllerInStoryboard() -> PagesController {
let storyboardIds = ["One","Two"]
return PagesController(storyboardIds)
}
override func viewDidLoad() {
super.viewDidLoad()
pages = pagesControllerInCode()
self.view.window?.rootViewController = UINavigationController(rootViewController: pages!)
pages?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Previous Page",
style: .Plain,
target: pages,
action: "previous")
pages?.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next Page",
style: .Plain,
target: pages,
action: "next")
self.view.window?.rootViewController = navigationController
self.view.window?.makeKeyAndVisible()
}
}
| mit | 175e18235fc806758eae0eebc5a06c04 | 27.702703 | 97 | 0.628531 | 5.545692 | false | false | false | false |
RobotsAndPencils/Scythe | Dependencies/HarvestKit-Swift/HarvestKit-Shared/Company.swift | 1 | 2830 | //
// Company.swift
// HarvestKit
//
// Created by Matthew Cheetham on 16/01/2016.
// Copyright © 2016 Matt Cheetham. All rights reserved.
//
import Foundation
/**
A struct representation of a company. Typiclaly returned from the API when querying about the current authenticated user
*/
public struct Company {
/**
Determines whether or not this company account is active
*/
public var active: Bool?
/**
The plan this buisiness is on. Determines how much their monthly payments are
*/
public var planType: String?
/**
Not documented in Harvest Documentation. Presumably the format that timers from this account should be displayed in.
*/
public var timeFormat: String?
/**
The URL that users must go to to access this harvest account
*/
public var baseURL: URL?
/**
The day that this company considers to be the beginning of the working week
*/
public var weekStartDay: String?
/**
An dictionary of objects determining what modules this company has enabled. This can determine which controllers you can use as some methods will return 404 where that feature is not enabled in the modules. Admins can configure modules.
*/
public var modules: [String: Bool]?
/**
The seperator that should be used for numbers over a thousand if any. Helps to localise figures where appropriate
*/
public var thousandsSeperator: String?
/**
The color scheme that the company has applied to their account in the website. You may use this to theme your application if you wish.
*/
public var colorScheme: String?
/**
The symbol that should be use to denote a decimal. Varies per company locale.
*/
public var decimalSymbol: String?
/**
The name of the company
*/
public var companyName: String?
/**
The time format used by the company. 12h or 24h for example.
*/
public var clockFormat: String?
internal init(dictionary: [String: AnyObject]) {
active = dictionary["active"] as? Bool
planType = dictionary["plan_type"] as? String
timeFormat = dictionary["time_format"] as? String
if let baseURLString = dictionary["base_uri"] as? String {
baseURL = URL(string: baseURLString)
}
weekStartDay = dictionary["week_start_day"] as? String
modules = dictionary["modules"] as? [String: Bool]
thousandsSeperator = dictionary["thousands_separator"] as? String
colorScheme = dictionary["color_scheme"] as? String
decimalSymbol = dictionary["decimal_symbol"] as? String
companyName = dictionary["name"] as? String
clockFormat = dictionary["clock"] as? String
}
}
| mit | 77453e2da3adf1420c726b42b7ed61ce | 30.087912 | 240 | 0.654648 | 4.778716 | false | false | false | false |
hirohitokato/SimpleGaplessPlayer | HKLAVGaplessPlayer/HKLAVGaplessPlayer/AssetHolder.swift | 1 | 1571 | //
// AssetHolder.swift
// SimpleGaplessPlayer
//
// Created by Hirohito Kato on 2015/01/20.
// Copyright (c) 2015年 Hirohito Kato. All rights reserved.
//
import Foundation
import AVFoundation
/**
* アセット配列に格納するデータ構造。AVAsset.durationなどのvalueにアクセスするのは
* 毎回ロックが入るなどして高コストであるため(iOS8.1.2時点)、値をアセットと共にキャッシュするのが目的
*/
class AssetHolder {
/// 外部から渡されたアセット
let asset: AVAsset
/// アセットの再生時間。キャッシュした値があればそれを返す
var duration: CMTime {
get {
if _duration != nil {
return _duration
} else {
_duration = asset.duration
return _duration
}
}
set { _duration = newValue }
}
init(_ asset: AVAsset, completionHandler: @escaping (CMTime) -> Void) {
self.asset = asset
// AssetReaderFragmentのビルドに必要な情報を非同期に読み込み始めておく
// (もしビルドまでに間に合わなかった場合でも、処理がブロックされる
// 時間を短くできることを狙っている)
let keys = ["duration","tracks", "preferredTransform", "readable"]
asset.loadValuesAsynchronously(forKeys: keys) {
self.duration = asset.duration
completionHandler(self.duration)
}
}
private var _duration: CMTime! = nil
}
| bsd-3-clause | aebfff96e2d3e4179343bbab512502bc | 26.883721 | 75 | 0.614679 | 3.258152 | false | false | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/07729-addprotocols.swift | 11 | 351 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d = a(array: A.f == 0.c
var d = {
var d = b) {
struct d<c : d<T where B : e where e: d<T where B : P {
let a {
init() {
protocol P {
class d<T where H.e == {
class
case c,
let a
| mit | 591df9ac6e2ab7d7cbdc0385cbff62a8 | 22.4 | 87 | 0.65812 | 2.94958 | false | true | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxCocoa/RxCocoa/Deprecated.swift | 3 | 17795 | //
// Deprecated.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/19/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import Dispatch
extension ObservableType {
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better, and enables
writing more consistent binding code.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
@available(*, deprecated, renamed: "bind(to:)")
public func bindTo<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
return self.subscribe(observer)
}
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better, and enables
writing more consistent binding code.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
@available(*, deprecated, renamed: "bind(to:)")
public func bindTo<O: ObserverType>(_ observer: O) -> Disposable where O.E == E? {
return self.map { $0 }.subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
@available(*, deprecated, renamed: "bind(to:)")
public func bindTo(_ variable: Variable<E>) -> Disposable {
return self.subscribe { e in
switch e {
case let .next(element):
variable.value = element
case let .error(error):
let error = "Binding error to variable: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
case .completed:
break
}
}
}
/**
Creates new subscription and sends elements to variable.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
@available(*, deprecated, renamed: "bind(to:)")
public func bindTo(_ variable: Variable<E?>) -> Disposable {
return self.map { $0 as E? }.bindTo(variable)
}
/**
Subscribes to observable sequence using custom binder function.
- parameter binder: Function used to bind elements from `self`.
- returns: Object representing subscription.
*/
@available(*, deprecated, renamed: "bind(to:)")
public func bindTo<R>(_ binder: (Self) -> R) -> R {
return binder(self)
}
/**
Subscribes to observable sequence using custom binder function and final parameter passed to binder function
after `self` is passed.
public func bindTo<R1, R2>(binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return binder(self)(curriedArgument)
}
- parameter binder: Function used to bind elements from `self`.
- parameter curriedArgument: Final argument passed to `binder` to finish binding process.
- returns: Object representing subscription.
*/
@available(*, deprecated, renamed: "bind(to:)")
public func bindTo<R1, R2>(_ binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 {
return binder(self)(curriedArgument)
}
/**
Subscribes an element handler to an observable sequence.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@available(*, deprecated, renamed: "bind(onNext:)")
public func bindNext(_ onNext: @escaping (E) -> Void) -> Disposable {
return self.subscribe(onNext: onNext, onError: { error in
let error = "Binding error: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
})
}
}
#if os(iOS) || os(tvOS)
import UIKit
extension NSTextStorage {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxTextStorageDelegateProxy {
fatalError()
}
}
extension UIScrollView {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxScrollViewDelegateProxy {
fatalError()
}
}
extension UICollectionView {
@available(*, unavailable, message: "createRxDataSourceProxy is now unavailable, check DelegateProxyFactory")
public func createRxDataSourceProxy() -> RxCollectionViewDataSourceProxy {
fatalError()
}
}
extension UITableView {
@available(*, unavailable, message: "createRxDataSourceProxy is now unavailable, check DelegateProxyFactory")
public func createRxDataSourceProxy() -> RxTableViewDataSourceProxy {
fatalError()
}
}
extension UINavigationBar {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxNavigationControllerDelegateProxy {
fatalError()
}
}
extension UINavigationController {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxNavigationControllerDelegateProxy {
fatalError()
}
}
extension UITabBar {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxTabBarDelegateProxy {
fatalError()
}
}
extension UITabBarController {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxTabBarControllerDelegateProxy {
fatalError()
}
}
extension UISearchBar {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxSearchBarDelegateProxy {
fatalError()
}
}
#endif
#if os(iOS)
extension UISearchController {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxSearchControllerDelegateProxy {
fatalError()
}
}
extension UIPickerView {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxPickerViewDelegateProxy {
fatalError()
}
@available(*, unavailable, message: "createRxDataSourceProxy is now unavailable, check DelegateProxyFactory")
public func createRxDataSourceProxy() -> RxPickerViewDataSourceProxy {
fatalError()
}
}
extension UIWebView {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxWebViewDelegateProxy {
fatalError()
}
}
#endif
#if os(macOS)
import Cocoa
extension NSTextField {
@available(*, unavailable, message: "createRxDelegateProxy is now unavailable, check DelegateProxyFactory")
public func createRxDelegateProxy() -> RxTextFieldDelegateProxy {
fatalError()
}
}
#endif
/**
This method can be used in unit tests to ensure that driver is using mock schedulers instead of
main schedulers.
**This shouldn't be used in normal release builds.**
*/
@available(*, deprecated, renamed: "SharingScheduler.mock(scheduler:action:)")
public func driveOnScheduler(_ scheduler: SchedulerType, action: () -> Void) {
SharingScheduler.mock(scheduler: scheduler, action: action)
}
extension Variable {
/// Converts `Variable` to `SharedSequence` unit.
///
/// - returns: Observable sequence.
@available(*, deprecated, renamed: "asDriver()")
public func asSharedSequence<SharingStrategy: SharingStrategyProtocol>(strategy: SharingStrategy.Type = SharingStrategy.self) -> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.observeOn(SharingStrategy.scheduler)
return SharedSequence(source)
}
}
#if !os(Linux)
extension DelegateProxy {
@available(*, unavailable, renamed: "assignedProxy(for:)")
public static func assignedProxyFor(_ object: ParentObject) -> Delegate? {
fatalError()
}
@available(*, unavailable, renamed: "currentDelegate(for:)")
public static func currentDelegateFor(_ object: ParentObject) -> Delegate? {
fatalError()
}
}
#endif
/**
Observer that enforces interface binding rules:
* can't bind errors (in debug builds binding of errors causes `fatalError` in release builds errors are being logged)
* ensures binding is performed on main thread
`UIBindingObserver` doesn't retain target interface and in case owned interface element is released, element isn't bound.
In case event binding is attempted from non main dispatch queue, event binding will be dispatched async to main dispatch
queue.
*/
@available(*, deprecated, renamed: "Binder")
public final class UIBindingObserver<UIElementType, Value> : ObserverType where UIElementType: AnyObject {
public typealias E = Value
weak var UIElement: UIElementType?
let binding: (UIElementType, Value) -> Void
/// Initializes `ViewBindingObserver` using
@available(*, deprecated, renamed: "UIBinder.init(_:scheduler:binding:)")
public init(UIElement: UIElementType, binding: @escaping (UIElementType, Value) -> Void) {
self.UIElement = UIElement
self.binding = binding
}
/// Binds next element to owner view as described in `binding`.
public func on(_ event: Event<Value>) {
if !DispatchQueue.isMain {
DispatchQueue.main.async {
self.on(event)
}
return
}
switch event {
case .next(let element):
if let view = self.UIElement {
self.binding(view, element)
}
case .error(let error):
bindingError(error)
case .completed:
break
}
}
/// Erases type of observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Value> {
return AnyObserver(eventHandler: self.on)
}
}
#if os(iOS)
extension Reactive where Base: UIRefreshControl {
/// Bindable sink for `beginRefreshing()`, `endRefreshing()` methods.
@available(*, deprecated, renamed: "isRefreshing")
public var refreshing: Binder<Bool> {
return self.isRefreshing
}
}
#endif
#if os(iOS) || os(tvOS)
extension Reactive where Base: UIImageView {
/// Bindable sink for `image` property.
/// - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...)
@available(*, deprecated, renamed: "image")
public func image(transitionType: String? = nil) -> Binder<UIImage?> {
return Binder(base) { imageView, image in
if let transitionType = transitionType {
if image != nil {
let transition = CATransition()
transition.duration = 0.25
#if swift(>=4.2)
transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
transition.type = CATransitionType(rawValue: transitionType)
#else
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = transitionType
#endif
imageView.layer.add(transition, forKey: kCATransition)
}
}
else {
imageView.layer.removeAllAnimations()
}
imageView.image = image
}
}
}
extension Reactive where Base: UISegmentedControl {
@available(*, deprecated, renamed: "enabledForSegment(at:)")
public func enabled(forSegmentAt segmentAt: Int) -> Binder<Bool> {
return enabledForSegment(at: segmentAt)
}
}
#endif
#if os(macOS)
extension Reactive where Base: NSImageView {
/// Bindable sink for `image` property.
///
/// - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...)
@available(*, deprecated, renamed: "image")
public func image(transitionType: String? = nil) -> Binder<NSImage?> {
return Binder(self.base) { control, value in
if let transitionType = transitionType {
if value != nil {
let transition = CATransition()
transition.duration = 0.25
#if swift(>=4.2)
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.type = CATransitionType(rawValue: transitionType)
#else
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = transitionType
#endif
control.layer?.add(transition, forKey: kCATransition)
}
}
else {
control.layer?.removeAllAnimations()
}
control.image = value
}
}
}
#endif
import RxSwift
extension Variable {
/// Converts `Variable` to `Driver` trait.
///
/// - returns: Driving observable sequence.
public func asDriver() -> Driver<E> {
let source = self.asObservable()
.observeOn(DriverSharingStrategy.scheduler)
return Driver(source)
}
}
private let errorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" +
"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n"
extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy {
/**
Creates new subscription and sends elements to variable.
This method can be only called from `MainThread`.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
public func drive(_ variable: Variable<E>) -> Disposable {
MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage)
return self.drive(onNext: { e in
variable.value = e
})
}
/**
Creates new subscription and sends elements to variable.
This method can be only called from `MainThread`.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
public func drive(_ variable: Variable<E?>) -> Disposable {
MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage)
return self.drive(onNext: { e in
variable.value = e
})
}
}
extension ObservableType {
/**
Creates new subscription and sends elements to variable.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter to: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
public func bind(to variable: Variable<E>) -> Disposable {
return self.subscribe { e in
switch e {
case let .next(element):
variable.value = element
case let .error(error):
let error = "Binding error to variable: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
case .completed:
break
}
}
}
/**
Creates new subscription and sends elements to variable.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter to: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
public func bind(to variable: Variable<E?>) -> Disposable {
return self.map { $0 as E? }.bind(to: variable)
}
}
| apache-2.0 | 701362c4839f4f7133dd51f24cebeaad | 34.166008 | 169 | 0.638698 | 5.259829 | false | false | false | false |
ProteanBear/ProteanBear_Swift | library/pb.swift.ui/ExtensionUITextField.swift | 1 | 747 | //
// ExtensionUITextField.swift
// PbSwiftDemo
//
// Created by Maqiang on 15/9/22.
// Copyright © 2015年 ProteanBear. All rights reserved.
//
import Foundation
import UIKit
extension UITextField
{
/// 设置左侧边距
/// - parameter width:边距宽度
public func pbSetLeftPadding(_ width:CGFloat)
{
var rect=self.frame
rect.size.width = width
self.leftViewMode = .always
self.leftView=UIView(frame:rect)
}
/// 设置右侧边距
/// - parameter width:边距宽度
public func pbSetRightPadding(_ width:CGFloat)
{
var rect=self.frame
rect.size.width = width
self.rightViewMode = .always
self.rightView=UIView(frame:rect)
}
}
| apache-2.0 | b232aca24c866352c20602e52c4ee207 | 20.333333 | 55 | 0.62642 | 3.805405 | false | false | false | false |
einsteinx2/iSub | Classes/AudioEngine/Bass Wrapper/GaplessPlayer.swift | 1 | 41410 | //
// GaplessPlayer.swift
// iSub
//
// Created by Benjamin Baron on 1/20/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
import AVFoundation
fileprivate let deviceNumber: UInt32 = 1
fileprivate let bufferSize: UInt32 = 800
fileprivate let defaultSampleRate: UInt32 = 44100
fileprivate let retryDelay = 2.0
fileprivate let minSizeToFail: Int64 = 15 * 1024 * 1024 // 15MB
final class GaplessPlayer {
struct Notifications {
static let songStarted = Notification.Name("GaplessPlayer_songStarted")
static let songPaused = Notification.Name("GaplessPlayer_songPaused")
static let songEnded = Notification.Name("GaplessPlayer_songEnded")
}
static let si = GaplessPlayer()
let controller = BassStreamController(deviceNumber: deviceNumber)
let equalizer = Equalizer()
let visualizer = Visualizer()
// MARK: - Lifecycle -
init() {
NotificationCenter.addObserverOnMainThread(self, selector: #selector(handleInterruption(_:)), name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance())
NotificationCenter.addObserverOnMainThread(self, selector: #selector(routeChanged(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: AVAudioSession.sharedInstance())
NotificationCenter.addObserverOnMainThread(self, selector: #selector(mediaServicesWereLost(_:)), name: NSNotification.Name.AVAudioSessionMediaServicesWereLost, object: AVAudioSession.sharedInstance())
NotificationCenter.addObserverOnMainThread(self, selector: #selector(mediaServicesWereReset(_:)), name: NSNotification.Name.AVAudioSessionMediaServicesWereReset, object: AVAudioSession.sharedInstance())
NotificationCenter.addObserverOnMainThread(self, selector: #selector(readyForPlayback(_:)), name: StreamHandler.Notifications.readyForPlayback)
}
deinit {
NotificationCenter.removeObserverOnMainThread(self, name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance())
NotificationCenter.removeObserverOnMainThread(self, name: NSNotification.Name.AVAudioSessionRouteChange, object: AVAudioSession.sharedInstance())
NotificationCenter.removeObserverOnMainThread(self, name: NSNotification.Name.AVAudioSessionMediaServicesWereLost, object: AVAudioSession.sharedInstance())
NotificationCenter.removeObserverOnMainThread(self, name: NSNotification.Name.AVAudioSessionMediaServicesWereReset, object: AVAudioSession.sharedInstance())
NotificationCenter.removeObserverOnMainThread(self, name: StreamHandler.Notifications.readyForPlayback, object: nil)
}
// MARK: - Notifications -
fileprivate var shouldResumeFromInterruption = false
@objc fileprivate func handleInterruption(_ notification: Notification) {
if notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt == AVAudioSessionInterruptionType.began.rawValue {
shouldResumeFromInterruption = isPlaying
pause()
} else {
let shouldResume = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt == AVAudioSessionInterruptionOptions.shouldResume.rawValue
if shouldResumeFromInterruption && shouldResume {
play()
}
shouldResumeFromInterruption = false
}
}
@objc fileprivate func routeChanged(_ notification: Notification) {
if notification.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt == AVAudioSessionRouteChangeReason.oldDeviceUnavailable.rawValue {
pause()
}
}
@objc fileprivate func mediaServicesWereLost(_ notification: Notification) {
log.debug("mediaServicesWereLost: \(String(describing: notification.userInfo))")
}
@objc fileprivate func mediaServicesWereReset(_ notification: Notification) {
log.debug("mediaServicesWereReset: \(String(describing: notification.userInfo))")
}
@objc fileprivate func readyForPlayback(_ notification: Notification) {
guard let song = notification.userInfo?[StreamHandler.Notifications.Keys.song] as? Song else {
return
}
if !isPlaying, song == PlayQueue.si.currentSong && (controller.currentBassStream?.song == nil || controller.currentBassStream?.song == song) {
start(song: song)
} else if song == PlayQueue.si.nextSong && (controller.nextBassStream?.song == nil || controller.nextBassStream?.song == song) {
prepareNextStream()
}
}
// MARK: - Playback -
var startByteOffset: Int64 = 0
var isPlaying = false
var isStarted: Bool {
if let currentBassStream = controller.currentBassStream, currentBassStream.stream != 0 {
return true
}
return false
}
var currentByteOffset: Int64 {
if let currentBassStream = controller.currentBassStream {
return Int64(BASS_StreamGetFilePosition(currentBassStream.stream, DWORD(BASS_FILEPOS_CURRENT))) + startByteOffset
}
return 0
}
var rawProgress: Double {
guard let currentBassStream = controller.currentBassStream else {
return 0
}
BASS_SetDevice(deviceNumber)
var pcmBytePosition = Double(BASS_Mixer_ChannelGetPosition(currentBassStream.stream, DWORD(BASS_POS_BYTE)))
let chanCount = Double(currentBassStream.channelCount)
let filledSpace = Double(ringBuffer.filledSpace)
let sampleRate = Double(currentBassStream.sampleRate)
let defaultRate = Double(defaultSampleRate)
let totalDrained = Double(totalBytesDrained)
let denom = (2.0 * (1.0 / chanCount))
let realPosition = pcmBytePosition - (filledSpace / denom)
let sampleRateRatio = sampleRate / defaultRate
pcmBytePosition = realPosition
pcmBytePosition = pcmBytePosition < 0 ? 0 : pcmBytePosition
let position = totalDrained * sampleRateRatio * chanCount
if let position = UInt64(exactly: position) {
let seconds = BASS_ChannelBytes2Seconds(currentBassStream.stream, position)
return seconds
}
return 0
}
var previousSongForProgress: Song?
var progress: Double {
guard let currentBassStream = controller.currentBassStream else {
return 0
}
let seconds = rawProgress
if seconds < 0 {
// Use the previous song (i.e the one still coming out of the speakers), since we're actually finishing it right now
let prevDuration = previousSongForProgress?.duration ?? 0
return Double(prevDuration) + seconds
}
return seconds + BASS_ChannelBytes2Seconds(currentBassStream.stream, QWORD(startByteOffset))
}
var progressPercent: Double {
guard let currentBassStream = controller.currentBassStream else {
return 0
}
var seconds = rawProgress
if let durationInt = previousSongForProgress?.duration {
let duration = Double(durationInt)
if seconds < 0 {
if duration > 0 {
seconds = duration + seconds
return seconds / duration
}
return 0
}
}
if let duration = currentBassStream.song.duration, duration > 0 {
return seconds / Double(duration)
}
return 0
}
var bitRate: Int {
return controller.currentBassStream == nil ? 0 : Bass.estimateBitRate(bassStream: controller.currentBassStream!)
}
func stop() {
BASS_SetDevice(deviceNumber)
if isPlaying {
BASS_Pause()
isPlaying = false
}
cleanupOutput()
}
func play() {
if !isPlaying {
playPause()
}
}
func pause() {
if isPlaying {
playPause()
}
}
func playPause() {
BASS_SetDevice(deviceNumber)
if isPlaying {
BASS_Pause()
isPlaying = false
NotificationCenter.postOnMainThread(name: Notifications.songPaused)
} else if controller.currentBassStream == nil {
// See if we're at the end of the playlist
if PlayQueue.si.currentSong != nil {
PlayQueue.si.startSong(byteOffset: startByteOffset)
} else {
DispatchQueue.main.async {
PlayQueue.si.playPreviousSong()
}
}
} else {
BASS_Start()
isPlaying = true
NotificationCenter.postOnMainThread(name: Notifications.songStarted)
}
}
func seek(bytes: Int64, fadeDuration: TimeInterval = 0.0) {
BASS_SetDevice(deviceNumber)
guard let currentBassStream = controller.currentBassStream else {
return
}
currentBassStream.isEnded = false
if BASS_Mixer_ChannelSetPosition(currentBassStream.stream, UInt64(bytes), UInt32(BASS_POS_BYTE)) {
currentBassStream.neededSize = Int64.max
if currentBassStream.isWaiting {
currentBassStream.shouldBreakWaitLoop = true
}
ringBuffer.reset()
if fadeDuration > 0.0 {
let fadeDurationMillis = UInt32(fadeDuration * 1000)
BASS_ChannelSlideAttribute(controller.outStream, UInt32(BASS_ATTRIB_VOL), 0, fadeDurationMillis)
} else {
BASS_ChannelStop(controller.outStream)
BASS_ChannelPlay(controller.outStream, false)
}
totalBytesDrained = Int(Double(bytes) / Double(currentBassStream.channelCount) / (Double(currentBassStream.sampleRate) / Double(defaultSampleRate)))
} else {
Bass.printBassError()
}
}
func seek(seconds: Double, fadeDuration: TimeInterval = 0.0) {
if let currentBassStream = controller.currentBassStream {
BASS_SetDevice(deviceNumber)
let bytes = BASS_ChannelSeconds2Bytes(currentBassStream.stream, seconds)
seek(bytes: Int64(bytes), fadeDuration: fadeDuration)
}
}
func seek(percent: Double, fadeDuration: TimeInterval = 0.0) {
if let currentBassStream = controller.currentBassStream, let duration = currentBassStream.song.duration {
let seconds = Double(duration) * percent
seek(seconds: seconds, fadeDuration: fadeDuration)
}
}
// MARK: - Output Stream -
// MARK: Initialization
fileprivate(set) var isAudioSessionActive = false
fileprivate func activateAudioSession() {
guard !isAudioSessionActive else {
return
}
do {
try AVAudioSession.sharedInstance().setActive(true)
isAudioSessionActive = true
} catch {
printError(error)
}
initializeOutput()
}
fileprivate func initializeOutput() {
log.debug("initializeOutput")
// Disable mixing. To be called before BASS_Init.
BASS_SetConfig(UInt32(BASS_CONFIG_IOS_MIXAUDIO), 0)
// Set the buffer length to the minimum amount + bufferSize
BASS_SetConfig(UInt32(BASS_CONFIG_BUFFER), BASS_GetConfig(UInt32(BASS_CONFIG_UPDATEPERIOD)) + bufferSize)
// Set DSP effects to use floating point math to avoid clipping within the effects chain
BASS_SetConfig(UInt32(BASS_CONFIG_FLOATDSP), 1)
// Initialize default device.
if (BASS_Init(1, defaultSampleRate, 0, nil, nil))
{
controller.bassOutputBufferLengthMillis = BASS_GetConfig(UInt32(BASS_CONFIG_BUFFER))
// Eventually replace this workaround with pure Swift
bassLoadPlugins()
}
else
{
controller.bassOutputBufferLengthMillis = 0
printError("Can't initialize device")
Bass.printBassError()
}
controller.mixerStream = BASS_Mixer_StreamCreate(UInt32(defaultSampleRate), 2, UInt32(BASS_STREAM_DECODE))
controller.outStream = BASS_StreamCreate(UInt32(defaultSampleRate), 2, 0, streamProc, bridge(obj: self))
// Add the slide callback to handle fades
BASS_ChannelSetSync(controller.outStream, UInt32(BASS_SYNC_SLIDE), 0, slideSyncProc, bridge(obj: self))
visualizer.channel = controller.outStream
equalizer.channel = controller.outStream
if SavedSettings.si.isEqualizerOn {
equalizer.enable()
}
}
fileprivate func cleanupOutput() {
log.debug("cleanup")
BASS_SetDevice(deviceNumber)
startSongRetryTimer?.cancel()
startSongRetryTimer = nil
nextSongRetryTimer?.cancel()
nextSongRetryTimer = nil
ringBufferFillWorkItem?.cancel()
ringBufferFillWorkItem = nil
controller.cleanup()
BASS_ChannelStop(controller.outStream)
ringBuffer.reset()
isPlaying = false
}
// MARK: Ring buffer
fileprivate let ringBuffer = RingBuffer(size: 640 * 1024) // 640KB
fileprivate var totalBytesDrained = 0
fileprivate var ringBufferFillWorkItem: DispatchWorkItem?
fileprivate var waitLoopBassStream: BassStream?
fileprivate func stopFillingRingBuffer() {
log.debug("stopFillingRingBuffer")
ringBufferFillWorkItem?.cancel()
ringBufferFillWorkItem = nil
}
fileprivate func startFillingRingBuffer() {
guard ringBufferFillWorkItem == nil else {
return
}
log.debug("startFillingRingBuffer")
var workItem: DispatchWorkItem! = nil
workItem = DispatchWorkItem {
// Make sure we're using the right device
BASS_SetDevice(deviceNumber)
// Grab the mixerStream and ringBuffer as local references, so that if cleanup is run, and we're still inside this loop
// it won't start filling the new buffer
let ringBuffer = self.ringBuffer
let mixerStream = self.controller.mixerStream
let readSize = 64 * 1024
while !workItem.isCancelled {
// Fill the buffer if there is empty space
if ringBuffer.freeSpace > readSize {
autoreleasepool {
/*
* Read data to fill the buffer
*/
if let bassStream = self.controller.currentBassStream {
let tempBuffer = UnsafeMutablePointer<CChar>.allocate(capacity: readSize)
let tempLength = BASS_ChannelGetData(mixerStream, tempBuffer, UInt32(readSize))
if tempLength > 0 {
bassStream.isSongStarted = true
if !ringBuffer.fill(with: tempBuffer, length: Int(tempLength)) {
printError("Overran ring buffer and it was unable to expand")
}
}
tempBuffer.deallocate()
/*
* Handle pausing to wait for more data
*/
if bassStream.isFileUnderrun && BASS_ChannelIsActive(bassStream.stream) != UInt32(BASS_ACTIVE_STOPPED) {
// Get a strong reference to the current song's userInfo object, so that
// if the stream is freed while the wait loop is sleeping, the object will
// still be around to respond to shouldBreakWaitLoop
self.waitLoopBassStream = bassStream
// Mark the stream as waiting
bassStream.isWaiting = true
bassStream.isFileUnderrun = false
bassStream.wasFileJustUnderrun = true
// Handle waiting for additional data
if !bassStream.song.isFullyCached {
// Bail if the thread was canceled
if workItem.isCancelled {
return
}
if SavedSettings.si.isOfflineMode {
// This is offline mode and the song can not continue to play
self.moveToNextSong()
} else {
// Calculate the needed size:
// Choose either the current player bitRate, or if for some reason it is not detected properly,
// use the best estimated bitRate. Then use that to determine how much data to let download to continue.
let size = bassStream.song.localFileSize
let bitRate = Bass.estimateBitRate(bassStream: bassStream)
// Get the stream for this song
var recentDownloadSpeedInBytesPerSec = 0
if StreamQueue.si.song == bassStream.song, let handler = StreamQueue.si.streamHandler {
recentDownloadSpeedInBytesPerSec = handler.recentDownloadSpeedInBytesPerSec
} else if DownloadQueue.si.currentSong == bassStream.song, let handler = DownloadQueue.si.streamHandler {
recentDownloadSpeedInBytesPerSec = handler.recentDownloadSpeedInBytesPerSec
}
// Calculate the bytes to wait based on the recent download speed. If the handler is nil or recent download speed is 0
// it will just use the default (currently 10 seconds)
let bytesToWait = Bass.bytesToBuffer(forKiloBitRate: bitRate, speedInBytesPerSec: recentDownloadSpeedInBytesPerSec)
bassStream.neededSize = size + bytesToWait
// Sleep for 100000 microseconds, or 1/10th of a second
let sleepTime: UInt32 = 100000
// Check file size every second, so 1000000 microseconds
let fileSizeCheckWait: UInt32 = 1000000
var totalSleepTime: UInt32 = 0
while true {
// Bail if the thread was canceled
if workItem.isCancelled {
return
}
// Check if we should break every 10th of a second
usleep(sleepTime)
totalSleepTime += sleepTime
if bassStream.shouldBreakWaitLoop || bassStream.shouldBreakWaitLoopForever {
return
}
// Bail if the thread was canceled
if workItem.isCancelled {
return
}
// Only check the file size every second
if totalSleepTime >= fileSizeCheckWait {
autoreleasepool {
totalSleepTime = 0
if bassStream.song.localFileSize >= bassStream.neededSize {
// If enough of the file has downloaded, break the loop
return
} else if bassStream.song.isTempCached && bassStream.song != StreamQueue.si.song {
// Handle temp cached songs ending. When they end, they are set as the last temp cached song, so we know it's done and can stop waiting for data.
return
} else if bassStream.song.isFullyCached {
// If the song has finished caching, we can stop waiting
return
} else if SavedSettings.si.isOfflineMode {
// If we're not in offline mode, stop waiting and try next song
// Bail if the thread was canceled
if workItem.isCancelled {
return
}
self.moveToNextSong()
return
}
}
}
}
}
}
// Bail if the thread was canceled
if workItem.isCancelled {
return
}
bassStream.isWaiting = false
bassStream.shouldBreakWaitLoop = false
self.waitLoopBassStream = nil
}
}
}
}
// Bail if the thread was canceled
if workItem.isCancelled {
return
}
// Sleep for 1/4th of a second to prevent a tight loop
usleep(150000)
}
}
ringBufferFillWorkItem = workItem
DispatchQueue.utility.async(execute: workItem)
}
// MARK: Other
fileprivate var startSongRetryTimer: DispatchSourceTimer?
func start(song: Song, byteOffset: Int64 = 0) {
log.debug("start song: \(song)")
BASS_SetDevice(deviceNumber)
startByteOffset = 0
cleanupOutput()
guard song.fileExists else {
log.debug("file doesn't exist")
return
}
activateAudioSession()
if let bassStream = prepareStream(forSong: song) {
log.debug("stream created, starting playback")
BASS_Mixer_StreamAddChannel(controller.mixerStream, bassStream.stream, UInt32(BASS_MIXER_NORAMPIN))
totalBytesDrained = 0
BASS_Start()
// Add the stream to the queue
controller.add(bassStream: bassStream)
// Skip to the byte offset
startByteOffset = byteOffset
totalBytesDrained = Int(byteOffset)
if byteOffset > 0 {
seek(bytes: byteOffset)
}
// Start filling the ring buffer
startFillingRingBuffer()
// Start playback
BASS_ChannelPlay(controller.outStream, false)
isPlaying = true
// Notify listeners that playback has started
NotificationCenter.postOnMainThread(name: Notifications.songStarted)
song.lastPlayed = Date()
if let nextSong = PlayQueue.si.nextSong, nextSong.isFullyCached || nextSong.isPartiallyCached {
prepareNextStream()
}
} else if !song.isFullyCached && song.localFileSize < minSizeToFail {
log.debug("failed to create stream for: \(song.title)")
if SavedSettings.si.isOfflineMode {
moveToNextSong()
log.debug("offline so moving to next song")
} else if !song.fileExists {
log.debug("file doesn't exist somehow, so restarting playback")
// File was removed, so start again normally
CacheManager.si.remove(song: song)
PlayQueue.si.startSong()
} else {
log.debug("retrying stream in 2 seconds")
// Failed to create the stream, retrying
startSongRetryTimer?.cancel()
startSongRetryTimer = DispatchSource.makeTimerSource(queue: .main)
startSongRetryTimer?.setEventHandler {
self.start(song: song, byteOffset: byteOffset)
}
startSongRetryTimer?.schedule(deadline: .now() + 2.0)
startSongRetryTimer?.resume()
}
} else {
CacheManager.si.remove(song: song)
PlayQueue.si.startSong()
}
}
fileprivate func prepareStream(forSong song: Song) -> BassStream? {
log.debug("preparing stream for song: \(song)")
guard song.fileExists, let bassStream = BassStream(song: song) else {
if song.fileExists {
log.debug("couldn't create bass stream")
} else {
log.debug("file doesn't exist")
}
return nil
}
BASS_SetDevice(deviceNumber)
func createStream(softwareDecoding: Bool = false) -> HSTREAM {
var flags = BASS_STREAM_DECODE | BASS_SAMPLE_FLOAT
if softwareDecoding {
flags = flags | BASS_SAMPLE_SOFTWARE
}
return BASS_StreamCreateFileUser(UInt32(STREAMFILE_NOBUFFER), UInt32(flags), &fileProcs, bridge(obj: bassStream))
}
// Try and create the stream
var fileStream = createStream()
// Check if the stream failed because of a BASS_Init error and init if needed
if fileStream == 0 && BASS_ErrorGetCode() == BASS_ERROR_INIT {
log.debug("bass not initialized, calling initializeOutput")
initializeOutput()
fileStream = createStream()
}
// If the stream failed, try with softrware decoding
if fileStream == 0 {
Bass.printBassError()
log.debug("failed to create stream, trying again with software decoding")
fileStream = createStream(softwareDecoding: true)
}
if fileStream > 0 {
// Add the stream free callback
BASS_ChannelSetSync(fileStream, UInt32(BASS_SYNC_END|BASS_SYNC_MIXTIME), 0, endSyncProc, bridge(obj: bassStream))
// Ask BASS how many channels are on this stream
var info = BASS_CHANNELINFO()
BASS_ChannelGetInfo(fileStream, &info)
bassStream.channelCount = Int(info.chans)
bassStream.sampleRate = Int(info.freq)
// Stream successfully created
bassStream.stream = fileStream
bassStream.player = self
return bassStream
}
Bass.printBassError()
log.debug("failed to create stream")
return nil
}
fileprivate var nextSongRetryTimer: DispatchSourceTimer?
fileprivate func prepareNextStream() {
if controller.nextBassStream == nil, let nextSong = PlayQueue.si.nextSong {
log.debug("prepareNextStream called for: \(nextSong.title)")
DispatchQueue.utility.async {
if let nextStream = self.prepareStream(forSong: nextSong) {
log.debug("prepareStream succeeded for: \(nextSong.title)")
self.controller.add(bassStream: nextStream)
} else {
log.debug("prepareStream failed for: \(nextSong.title)")
self.nextSongRetryTimer?.cancel()
self.nextSongRetryTimer = DispatchSource.makeTimerSource(queue: .main)
self.nextSongRetryTimer?.setEventHandler {
self.prepareNextStream()
}
self.nextSongRetryTimer?.schedule(deadline: .now() + 2.0)
self.nextSongRetryTimer?.resume()
self.controller.currentBassStream?.isNextSongStreamFailed = true
}
}
}
}
fileprivate func nextSongStreamFailed() {
log.debug("next song stream failed")
// The song ended, and we tried to make the next stream but it failed
if let song = PlayQueue.si.currentSong {
log.debug("song: \(song)")
if let handler = StreamQueue.si.streamHandler, song == StreamQueue.si.song {
log.debug("handler and song exist")
if handler.isReadyForPlayback {
// If the song is downloading and it already informed the player to play (i.e. the playlist will stop if we don't force a retry), then retry
log.debug("song is ready for playback, asynchronously calling startSong")
DispatchQueue.main.async {
self.prepareNextStream()
//self.start(song: song)
//PlayQueue.si.startSong()
}
}
} else if song.isFullyCached {
log.debug("song is fully cached, asynchronously calling startSong")
DispatchQueue.main.async {
self.start(song: song)
//PlayQueue.si.startSong()
}
} else {
log.debug("calling start on StreamQueue")
StreamQueue.si.start()
}
}
}
fileprivate func moveToNextSong() {
if PlayQueue.si.nextSong != nil {
log.debug("playing next song")
PlayQueue.si.playNextSong()
} else {
log.debug("calling cleanup")
cleanupOutput()
}
}
fileprivate var lastProgressSaveDate = Date.distantPast
fileprivate let progressSaveInterval = 10.0
fileprivate func bassGetOutputData(buffer: UnsafeMutableRawPointer?, length: UInt32) -> UInt32 {
guard let currentBassStream = controller.currentBassStream, let buffer = buffer else {
return 0
}
let bytesRead = ringBuffer.drain(into: buffer, length: Int(length))
totalBytesDrained += bytesRead
if currentBassStream.isEnded {
currentBassStream.bufferSpaceTilSongEnd -= bytesRead
if currentBassStream.bufferSpaceTilSongEnd <= 0 {
songEnded(bassStream: currentBassStream)
currentBassStream.isEndedCalled = true
}
}
let currentSong = currentBassStream.song
if bytesRead == 0 && BASS_ChannelIsActive(currentBassStream.stream) == UInt32(BASS_ACTIVE_STOPPED) && (currentSong.isFullyCached || currentSong.isTempCached) {
isPlaying = false
if !currentBassStream.isEndedCalled {
// Somehow songEnded: was never called
songEnded(bassStream: currentBassStream)
currentBassStream.isEndedCalled = true
}
NotificationCenter.postOnMainThread(name: Notifications.songEnded)
DispatchQueue.main.async {
self.cleanupOutput()
}
// Start the next song if for some reason this one isn't ready
PlayQueue.si.startSong()
return BASS_STREAMPROC_END
}
let now = Date()
if now.timeIntervalSince(lastProgressSaveDate) > progressSaveInterval {
SavedSettings.si.seekTime = progress
lastProgressSaveDate = now
}
return UInt32(bytesRead)
}
// NOTE: this is called AFTER endSyncProc, so the next song is already actually decoding into the ring buffer
fileprivate func songEnded(bassStream: BassStream) {
BASS_SetDevice(deviceNumber)
autoreleasepool {
self.previousSongForProgress = bassStream.song
self.totalBytesDrained = 0
bassStream.isEndedCalled = true
log.debug("song ended: \(bassStream.song)")
// Remove the stream from the queue
self.controller.remove(bassStream: bassStream)
// Send song end notification
NotificationCenter.postOnMainThread(name: Notifications.songEnded)
if self.isPlaying {
self.startByteOffset = 0
// Send song start notification
NotificationCenter.postOnMainThread(name: Notifications.songStarted)
// Mark the last played time in the database for cache cleanup
self.controller.currentBassStream?.song.lastPlayed = Date()
}
prepareNextStream()
// if bassStream.isNextSongStreamFailed {
// nextSongStreamFailed()
// }
}
}
}
// MARK: - BASS Callback Functions -
fileprivate func streamProc(handle: HSYNC, buffer: UnsafeMutableRawPointer?, length: UInt32, userInfo: UnsafeMutableRawPointer?) -> UInt32 {
var bytesRead: UInt32 = 0
if let userInfo = userInfo {
autoreleasepool {
let player: GaplessPlayer = bridge(ptr: userInfo)
bytesRead = player.bassGetOutputData(buffer: buffer, length: length)
}
}
return bytesRead
}
// MARK: File Procs
fileprivate var fileProcs = BASS_FILEPROCS(close: closeProc, length: lengthProc, read: readProc, seek: seekProc)
fileprivate func closeProc(userInfo: UnsafeMutableRawPointer?) {
guard let userInfo = userInfo else {
return
}
autoreleasepool {
// Get the user info object
let bassStream: BassStream = bridge(ptr: userInfo)
log.debug("close proc called for: \(bassStream.song.title)")
// Tell the read wait loop to break in case it's waiting
bassStream.shouldBreakWaitLoop = true
bassStream.shouldBreakWaitLoopForever = true
do {
try ObjC.catchException({bassStream.fileHandle.closeFile()})
} catch {
printError(error)
}
}
}
fileprivate func lengthProc(userInfo: UnsafeMutableRawPointer?) -> UInt64 {
guard let userInfo = userInfo else {
return 0
}
var length: Int64 = 0
autoreleasepool {
let bassStream: BassStream = bridge(ptr: userInfo)
if bassStream.song.isFullyCached || bassStream.isTempCached {
// Return actual file size on disk
log.debug("using song.localFileSize")
length = bassStream.song.localFileSize
} else {
// Return server reported file size
log.debug("using bassStream.song.size")
length = bassStream.song.size
}
log.debug("length proc called for: \(bassStream.song.title) len: \(length)")
}
return UInt64(length)
}
fileprivate func readProc(buffer: UnsafeMutableRawPointer?, length: UInt32, userInfo: UnsafeMutableRawPointer?) -> UInt32 {
guard let buffer = buffer, let userInfo = userInfo else {
return 0
}
let bufferPointer = UnsafeMutableBufferPointer(start: buffer.assumingMemoryBound(to: UInt8.self), count: Int(length))
var bytesRead: UInt32 = 0
autoreleasepool {
let bassStream: BassStream = bridge(ptr: userInfo)
// Read from the file
var readData = Data()
do {
try ObjC.catchException {
readData = bassStream.fileHandle.readData(ofLength: Int(length))
}
} catch {
// NOTE: Turned this off for now as it's giving NSFileHandleOperationException logs during normal operation
//printError(error)
}
bytesRead = UInt32(readData.count)
if bytesRead > 0 {
// Copy the data to the buffer
bytesRead = UInt32(readData.copyBytes(to: bufferPointer))
}
if bytesRead < length && bassStream.isSongStarted && !bassStream.wasFileJustUnderrun {
bassStream.isFileUnderrun = true
}
bassStream.wasFileJustUnderrun = false
}
return bytesRead
}
fileprivate func seekProc(offset: UInt64, userInfo: UnsafeMutableRawPointer?) -> ObjCBool {
guard let userInfo = userInfo else {
return false
}
var success = false
autoreleasepool {
// Seek to the requested offset (returns false if data not downloaded that far)
let bassStream: BassStream = bridge(ptr: userInfo)
// First check the file size to make sure we don't try and skip past the end of the file
let localFileSize = bassStream.song.localFileSize
if localFileSize >= 0 && UInt64(localFileSize) >= offset {
// File size is valid, so assume success unless the seek operation throws an exception
success = true
do {
try ObjC.catchException {
bassStream.fileHandle.seek(toFileOffset: offset)
}
} catch {
success = false
}
}
log.debug("seekProc called for: \(bassStream.song.title) success: \(success) localFileSize: \(localFileSize)")
}
return ObjCBool(success)
}
// MARK: Sync Procs
fileprivate func slideSyncProc(handle: HSYNC, channel: UInt32, data: UInt32, userInfo: UnsafeMutableRawPointer?) {
guard let userInfo = userInfo else {
return
}
BASS_SetDevice(deviceNumber)
autoreleasepool {
let player: GaplessPlayer = bridge(ptr: userInfo)
var volumeLevel: Float = 0
let success = BASS_ChannelGetAttribute(player.controller.outStream, UInt32(BASS_ATTRIB_VOL), &volumeLevel)
if success && volumeLevel == 0.0 {
BASS_ChannelSlideAttribute(player.controller.outStream, UInt32(BASS_ATTRIB_VOL), 1, 200)
}
}
}
fileprivate func endSyncProc(handle: HSYNC, channel: UInt32, data: UInt32, userInfo: UnsafeMutableRawPointer?) {
guard let userInfo = userInfo else {
return
}
// Make sure we're using the right device
BASS_SetDevice(deviceNumber)
autoreleasepool {
let bassStream: BassStream = bridge(ptr: userInfo)
if let player = bassStream.player {
log.debug("endSyncProc called for: \(bassStream.song.title)")
// Mark as ended and set the buffer space til end for the UI
bassStream.bufferSpaceTilSongEnd = player.ringBuffer.filledSpace
bassStream.isEnded = true
if let nextStream = player.controller.nextBassStream {
BASS_Mixer_StreamAddChannel(player.controller.mixerStream, nextStream.stream, UInt32(BASS_MIXER_NORAMPIN))
}
}
}
}
| gpl-3.0 | 129570b03aef80370c76fa076a1748a2 | 40.617085 | 210 | 0.547224 | 5.698225 | false | false | false | false |
edx/edx-app-ios | Source/WhatsNewViewController.swift | 1 | 10879 | //
// WhatsNewViewController.swift
// edX
//
// Created by Saeed Bashir on 5/2/17.
// Copyright © 2017 edX. All rights reserved.
//
import Foundation
class WhatsNewViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, InterfaceOrientationOverriding {
private let containerView: UIView = UIView()
private let closeButton = UIButton(type: .system)
private let headerLabel = UILabel()
private let pageController: UIPageViewController
private let doneButton = UIButton(type: .system)
private let closeImageSize: CGFloat = 16
private let topSpace: CGFloat = 22
private var pagesViewed: Int = 0 // This varibale will only be used for analytics
private var currentPageIndex: Int = 0 // This varibale will only be used for analytics
private var headerStyle : OEXTextStyle {
return OEXTextStyle(weight: .semiBold, size: .large, color: OEXStyles.shared().neutralWhiteT())
}
private var doneButtonStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .large, color: OEXStyles.shared().accentAColor())
}
typealias Environment = OEXStylesProvider & OEXInterfaceProvider & OEXAnalyticsProvider
private let environment : Environment
private let dataModel: WhatsNewDataModel
private var titleString: String
init(environment: Environment, dataModel: WhatsNewDataModel? = nil, title: String? = nil) {
self.environment = environment
if let dataModel = dataModel {
self.dataModel = dataModel
}
else {
self.dataModel = WhatsNewDataModel(environment: environment as? RouterEnvironment, version: Bundle.main.oex_shortVersionString())
}
titleString = title ?? Strings.WhatsNew.headerText
pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
environment.interface?.saveAppVersionOnWhatsNewAppear()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static func canShowWhatsNew(environment: RouterEnvironment?) -> Bool {
let appVersion = Version(version: Bundle.main.oex_shortVersionString())
let savedAppVersion = Version(version: environment?.interface?.getSavedAppVersionForWhatsNew() ?? "")
let validDiff = appVersion.isNMinorVersionsDiff(otherVersion: savedAppVersion, minorVersionDiff: 1)
return (validDiff && environment?.config.isWhatsNewEnabled ?? false)
}
override func viewDidLoad() {
super.viewDidLoad()
configurePageViewController()
configureViews()
setConstraints()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
logScreenEvent()
}
private func configurePageViewController() {
pageController.setViewControllers([initialItem()], direction: .forward, animated: false, completion: nil)
pageController.delegate = self
pageController.dataSource = self
addChild(pageController)
containerView.addSubview(pageController.view)
pageController.didMove(toParent: self)
}
private func configureViews() {
view.backgroundColor = environment.styles.primaryBaseColor()
doneButton.setAttributedTitle(doneButtonStyle.attributedString(withText: Strings.WhatsNew.done), for: .normal)
doneButton.accessibilityIdentifier = "WhatsNewViewController:done-button"
headerLabel.accessibilityLabel = Strings.Accessibility.Whatsnew.headerLabel
headerLabel.accessibilityIdentifier = "WhatsNewViewController:header-label"
closeButton.accessibilityLabel = Strings.Accessibility.Whatsnew.closeLabel
closeButton.accessibilityHint = Strings.Accessibility.closeHint
closeButton.accessibilityIdentifier = "WhatsNewViewController:close-button"
containerView.accessibilityIdentifier = "WhatsNewViewController:container-view"
view.addSubview(containerView)
containerView.addSubview(headerLabel)
containerView.addSubview(closeButton)
containerView.addSubview(doneButton)
showDoneButtonAtLastScreen()
headerLabel.attributedText = headerStyle.attributedString(withText: titleString)
closeButton.setImage(Icon.Close.imageWithFontSize(size: closeImageSize), for: UIControl.State())
closeButton.tintColor = OEXStyles.shared().neutralWhiteT()
closeButton.oex_addAction({[weak self] _ in
self?.logCloseEvent()
self?.dismiss(animated: true, completion: nil)
}, for: .touchUpInside)
doneButton.oex_addAction({ [weak self] _ in
self?.logDoneEvent()
self?.dismiss(animated: true, completion: nil)
}, for: .touchUpInside)
}
private func setConstraints() {
containerView.snp.makeConstraints { make in
make.edges.equalTo(safeEdges)
}
headerLabel.snp.makeConstraints { make in
make.top.equalTo(containerView).offset(topSpace)
make.centerX.equalTo(containerView)
}
closeButton.snp.makeConstraints { make in
make.top.equalTo(containerView).offset(topSpace)
make.trailing.equalTo(containerView).inset(topSpace)
make.height.equalTo(closeImageSize)
make.width.equalTo(closeImageSize)
}
pageController.view.snp.makeConstraints { make in
make.top.equalTo(headerLabel.snp.bottom).offset(StandardVerticalMargin)
make.bottom.equalTo(containerView)
make.trailing.equalTo(containerView)
make.leading.equalTo(containerView)
}
doneButton.snp.makeConstraints { make in
make.bottom.equalTo(containerView).offset(-StandardVerticalMargin / 2)
make.trailing.equalTo(containerView).offset(-StandardHorizontalMargin)
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle(barStyle : nil)
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func contentController(withItem item: WhatsNew?, direction: UIPageViewController.NavigationDirection)-> UIViewController {
// UIPageController DataSource methods calling is different in voice over and in normal flow.
// In VO UIPageController didn't required viewControllerAfter but it does in normal flow.
// TODO: revisit this functionality when UIPageController behaves same in all cases.
switch direction {
case .forward:
let totalScreens = dataModel.fields?.count ?? 0
(pagesViewed >= totalScreens) ? (pagesViewed = totalScreens + 1) : (pagesViewed += 1)
default:
break
}
UIAccessibility.isVoiceOverRunning ? (doneButton.isHidden = !(item?.isLast ?? false)) : (doneButton.isHidden = true)
let controller = WhatsNewContentController(environment: environment)
controller.whatsNew = item
return controller
}
private func initialItem()-> UIViewController {
return contentController(withItem: dataModel.fields?.first, direction: .forward)
}
private func showDoneButtonAtLastScreen() {
let totalScreens = dataModel.fields?.count ?? 0
doneButton.isHidden = currentPageIndex != totalScreens - 1
}
//MARK:- Analytics
private func logScreenEvent() {
let params = [key_app_version : Bundle.main.oex_shortVersionString()]
environment.analytics.trackScreen(withName: AnalyticsScreenName.WhatsNew.rawValue, courseID: nil, value: nil, additionalInfo: params)
}
private func logCloseEvent() {
(pagesViewed == 1) ? (pagesViewed = pagesViewed) : (pagesViewed -= 1)
let params = [key_app_version : Bundle.main.oex_shortVersionString(), "total_viewed": pagesViewed, "currently_viewed": currentPageIndex + 1, "total_screens": dataModel.fields?.count ?? 0] as [String : Any]
environment.analytics.trackEvent(whatsNewEvent(name: AnalyticsEventName.WhatsNewClose.rawValue, displayName: "WhatsNew: Close"), forComponent: nil, withInfo: params)
}
private func logDoneEvent() {
let params = [key_app_version : Bundle.main.oex_shortVersionString(), "total_screens": dataModel.fields?.count ?? 0] as [String : Any]
environment.analytics.trackEvent(whatsNewEvent(name: AnalyticsEventName.WhatsNewDone.rawValue, displayName: "WhatsNew: Done"), forComponent: nil, withInfo: params)
}
private func whatsNewEvent(name: String, displayName: String) -> OEXAnalyticsEvent {
let event = OEXAnalyticsEvent()
event.name = name
event.displayName = displayName
event.category = AnalyticsCategory.WhatsNew.rawValue
return event
}
//MARK:- UIPageViewControllerDelegate & UIPageViewControllerDataSource methods
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let controller = viewController as? WhatsNewContentController {
if let item = dataModel.prevItem(currentItem: controller.whatsNew) {
return contentController(withItem: item, direction: .reverse)
}
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let controller = viewController as? WhatsNewContentController {
if let item = dataModel.nextItem(currentItem: controller.whatsNew) {
return contentController(withItem: item, direction: .forward)
}
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let controller = pageViewController.viewControllers?.last as? WhatsNewContentController, finished == true {
currentPageIndex = dataModel.itemIndex(item: controller.whatsNew)
}
showDoneButtonAtLastScreen()
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return dataModel.fields?.count ?? 0
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
| apache-2.0 | ec21eb5a92854882318e235e7ce665f1 | 43.219512 | 213 | 0.689097 | 5.480101 | false | false | false | false |
davecom/SwiftGraph | Sources/SwiftGraph/Sort.swift | 2 | 2851 | //
// Sort.swift
// SwiftGraph
//
// Copyright (c) 2016-2019 David Kopec
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Functions for sorting a `Graph`
// MARK: Extension to `Graph` for toplogical sorting
public extension Graph {
// Based on Introduction to Algorithms, 3rd Edition, Cormen et. al.,
// The MIT Press, 2009, pg 604-614
// and revised pseudocode of the same from Wikipedia
// https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
/// Topologically sorts a `Graph` O(n)
///
/// - returns: the sorted vertices, or nil if the graph cannot be sorted due to not being a DAG
func topologicalSort() -> [V]? {
var sortedVertices = [V]()
let rangeOfVertices = 0..<vertexCount
let tsNodes = rangeOfVertices.map { TSNode(index: $0, color: .white) }
var notDAG = false
// Determine vertex neighbors in advance, so we have to do it once for each node.
let neighbors: [Set<Int>] = rangeOfVertices.map({ index in
Set(edges[index].map({ $0.v }))
})
func visit(_ node: TSNode) {
guard node.color != .gray else {
notDAG = true
return
}
if node.color == .white {
node.color = .gray
for inode in tsNodes where neighbors[node.index].contains(inode.index) {
visit(inode)
}
node.color = .black
sortedVertices.insert(vertices[node.index], at: 0)
}
}
for node in tsNodes where node.color == .white {
visit(node)
}
if notDAG {
return nil
}
return sortedVertices
}
/// Is the `Graph` a directed-acyclic graph (DAG)? O(n)
/// Finds the answer based on the result of a topological sort.
var isDAG: Bool {
guard let _ = topologicalSort() else { return false }
return true
}
}
// MARK: Utility structures for topological sorting
fileprivate enum TSColor { case black, gray, white }
fileprivate class TSNode {
fileprivate let index: Int
fileprivate var color: TSColor
init(index: Int, color: TSColor) {
self.index = index
self.color = color
}
}
| apache-2.0 | 5d4aebbfa6eeecb9873179237de20378 | 31.397727 | 99 | 0.599439 | 4.18649 | false | false | false | false |
lorentey/swift | test/ModuleInterface/conformances.swift | 8 | 9905 | // RUN: %target-swift-frontend-typecheck -emit-module-interface-path %t.swiftinterface %s
// RUN: %FileCheck %s < %t.swiftinterface
// RUN: %FileCheck -check-prefix CHECK-END %s < %t.swiftinterface
// RUN: %FileCheck -check-prefix NEGATIVE %s < %t.swiftinterface
// NEGATIVE-NOT: BAD
// CHECK-LABEL: public protocol SimpleProto {
public protocol SimpleProto {
// CHECK: associatedtype Element
associatedtype Element
// CHECK: associatedtype Inferred
associatedtype Inferred
func inference(_: Inferred)
} // CHECK: {{^}$}}
// CHECK-LABEL: public struct SimpleImpl<Element> : conformances.SimpleProto {
public struct SimpleImpl<Element>: SimpleProto {
// NEGATIVE-NOT: typealias Element =
// CHECK: public func inference(_: Swift.Int){{$}}
public func inference(_: Int) {}
// CHECK: public typealias Inferred = Swift.Int
} // CHECK: {{^}$}}
public protocol PublicProto {}
private protocol PrivateProto {}
// CHECK: public struct A1 : conformances.PublicProto {
// NEGATIVE-NOT: extension conformances.A1
public struct A1: PublicProto, PrivateProto {}
// CHECK: public struct A2 : conformances.PublicProto {
// NEGATIVE-NOT: extension conformances.A2
public struct A2: PrivateProto, PublicProto {}
// CHECK: public struct A3 {
// CHECK-END: extension conformances.A3 : conformances.PublicProto {}
public struct A3: PublicProto & PrivateProto {}
// CHECK: public struct A4 {
// CHECK-END: extension conformances.A4 : conformances.PublicProto {}
public struct A4: PrivateProto & PublicProto {}
public protocol PublicBaseProto {}
private protocol PrivateSubProto: PublicBaseProto {}
// CHECK: public struct B1 {
// CHECK-END: extension conformances.B1 : conformances.PublicBaseProto {}
public struct B1: PrivateSubProto {}
// CHECK: public struct B2 : conformances.PublicBaseProto {
// NEGATIVE-NOT: extension conformances.B2
public struct B2: PublicBaseProto, PrivateSubProto {}
// CHECK: public struct B3 {
// CHECK-END: extension conformances.B3 : conformances.PublicBaseProto {}
public struct B3: PublicBaseProto & PrivateSubProto {}
// CHECK: public struct B4 : conformances.PublicBaseProto {
// NEGATIVE-NOT: extension B4 {
// NEGATIVE-NOT: extension conformances.B4
public struct B4: PublicBaseProto {}
extension B4: PrivateSubProto {}
// CHECK: public struct B5 {
// CHECK: extension B5 : conformances.PublicBaseProto {
// NEGATIVE-NOT: extension conformances.B5
public struct B5: PrivateSubProto {}
extension B5: PublicBaseProto {}
// CHECK: public struct B6 {
// NEGATIVE-NOT: extension B6 {
// CHECK: extension B6 : conformances.PublicBaseProto {
// NEGATIVE-NOT: extension conformances.B6
public struct B6 {}
extension B6: PrivateSubProto {}
extension B6: PublicBaseProto {}
// CHECK: public struct B7 {
// CHECK: extension B7 : conformances.PublicBaseProto {
// NEGATIVE-NOT: extension B7 {
// NEGATIVE-NOT: extension conformances.B7
public struct B7 {}
extension B7: PublicBaseProto {}
extension B7: PrivateSubProto {}
// CHECK-LABEL: public struct OuterGeneric<T> {
public struct OuterGeneric<T> {
// CHECK-NEXT: public struct Inner {
public struct Inner: PrivateSubProto {}
// CHECK-NEXT: {{^ }$}}
}
// CHECK-NEXT: {{^}$}}
public protocol ConditionallyConformed {}
public protocol ConditionallyConformedAgain {}
// CHECK-END: @available(*, unavailable)
// CHECK-END-NEXT: extension conformances.OuterGeneric : conformances.ConditionallyConformed, conformances.ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
extension OuterGeneric: ConditionallyConformed where T: PrivateProto {}
extension OuterGeneric: ConditionallyConformedAgain where T == PrivateProto {}
// CHECK-END: extension conformances.OuterGeneric.Inner : conformances.PublicBaseProto {}
// CHECK-END: @available(*, unavailable)
// CHECK-END-NEXT: extension conformances.OuterGeneric.Inner : conformances.ConditionallyConformed, conformances.ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
extension OuterGeneric.Inner: ConditionallyConformed where T: PrivateProto {}
extension OuterGeneric.Inner: ConditionallyConformedAgain where T == PrivateProto {}
private protocol AnotherPrivateSubProto: PublicBaseProto {}
// CHECK: public struct C1 {
// CHECK-END: extension conformances.C1 : conformances.PublicBaseProto {}
public struct C1: PrivateSubProto, AnotherPrivateSubProto {}
// CHECK: public struct C2 {
// CHECK-END: extension conformances.C2 : conformances.PublicBaseProto {}
public struct C2: PrivateSubProto & AnotherPrivateSubProto {}
// CHECK: public struct C3 {
// NEGATIVE-NOT: extension C3 {
// CHECK-END: extension conformances.C3 : conformances.PublicBaseProto {}
public struct C3: PrivateSubProto {}
extension C3: AnotherPrivateSubProto {}
public protocol PublicSubProto: PublicBaseProto {}
public protocol APublicSubProto: PublicBaseProto {}
// CHECK: public struct D1 : conformances.PublicSubProto {
// NEGATIVE-NOT: extension conformances.D1
public struct D1: PublicSubProto, PrivateSubProto {}
// CHECK: public struct D2 : conformances.PublicSubProto {
// NEGATIVE-NOT: extension conformances.D2
public struct D2: PrivateSubProto, PublicSubProto {}
// CHECK: public struct D3 {
// CHECK-END: extension conformances.D3 : conformances.PublicBaseProto {}
// CHECK-END: extension conformances.D3 : conformances.PublicSubProto {}
public struct D3: PrivateSubProto & PublicSubProto {}
// CHECK: public struct D4 {
// CHECK-END: extension conformances.D4 : conformances.APublicSubProto {}
// CHECK-END: extension conformances.D4 : conformances.PublicBaseProto {}
public struct D4: APublicSubProto & PrivateSubProto {}
// CHECK: public struct D5 {
// CHECK: extension D5 : conformances.PublicSubProto {
// NEGATIVE-NOT: extension conformances.D5
public struct D5: PrivateSubProto {}
extension D5: PublicSubProto {}
// CHECK: public struct D6 : conformances.PublicSubProto {
// NEGATIVE-NOT: extension D6 {
// NEGATIVE-NOT: extension conformances.D6
public struct D6: PublicSubProto {}
extension D6: PrivateSubProto {}
private typealias PrivateProtoAlias = PublicProto
// CHECK: public struct E1 {
// CHECK-END: extension conformances.E1 : conformances.PublicProto {}
public struct E1: PrivateProtoAlias {}
private typealias PrivateSubProtoAlias = PrivateSubProto
// CHECK: public struct F1 {
// CHECK-END: extension conformances.F1 : conformances.PublicBaseProto {}
public struct F1: PrivateSubProtoAlias {}
private protocol ClassConstrainedProto: PublicProto, AnyObject {}
public class G1: ClassConstrainedProto {}
// CHECK: public class G1 {
// CHECK-END: extension conformances.G1 : conformances.PublicProto {}
public class Base {}
private protocol BaseConstrainedProto: Base, PublicProto {}
public class H1: Base, ClassConstrainedProto {}
// CHECK: public class H1 : conformances.Base {
// CHECK-END: extension conformances.H1 : conformances.PublicProto {}
public struct MultiGeneric<T, U, V> {}
extension MultiGeneric: PublicProto where U: PrivateProto {}
// CHECK: public struct MultiGeneric<T, U, V> {
// CHECK-END: @available(*, unavailable)
// CHECK-END-NEXT: extension conformances.MultiGeneric : conformances.PublicProto where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
internal struct InternalImpl_BAD: PrivateSubProto {}
internal struct InternalImplConstrained_BAD<T> {}
extension InternalImplConstrained_BAD: PublicProto where T: PublicProto {}
internal struct InternalImplConstrained2_BAD<T> {}
extension InternalImplConstrained2_BAD: PublicProto where T: PrivateProto {}
public struct WrapperForInternal {
internal struct InternalImpl_BAD: PrivateSubProto {}
internal struct InternalImplConstrained_BAD<T> {}
internal struct InternalImplConstrained2_BAD<T> {}
}
extension WrapperForInternal.InternalImplConstrained_BAD: PublicProto where T: PublicProto {}
extension WrapperForInternal.InternalImplConstrained2_BAD: PublicProto where T: PrivateProto {}
internal protocol ExtraHashable: Hashable {}
extension Bool: ExtraHashable {}
@available(iOS, unavailable)
@available(macOS, unavailable)
public struct CoolTVType: PrivateSubProto {}
// CHECK: public struct CoolTVType {
// CHECK-END: @available(iOS, unavailable)
// CHECK-END-NEXT: @available(OSX, unavailable)
// CHECK-END-NEXT: extension conformances.CoolTVType : conformances.PublicBaseProto {}
@available(macOS 10.99, *)
public struct VeryNewMacType: PrivateSubProto {}
// CHECK: public struct VeryNewMacType {
// CHECK-END: @available(OSX 10.99, *)
// CHECK-END-NEXT: extension conformances.VeryNewMacType : conformances.PublicBaseProto {}
public struct VeryNewMacProto {}
@available(macOS 10.98, *)
extension VeryNewMacProto: PrivateSubProto {}
// CHECK: public struct VeryNewMacProto {
// CHECK-END: @available(OSX 10.98, *)
// CHECK-END-NEXT: extension conformances.VeryNewMacProto : conformances.PublicBaseProto {}
public struct PrivateProtoConformer {}
extension PrivateProtoConformer : PrivateProto {
public var member: Int { return 0 }
}
// CHECK: public struct PrivateProtoConformer {
// CHECK: extension PrivateProtoConformer {
// CHECK-NEXT: public var member: Swift.Int {
// CHECK-NEXT: get
// CHECK-NEXT: }
// CHECK-NEXT: {{^}$}}
// NEGATIVE-NOT: extension conformances.PrivateProtoConformer
// NEGATIVE-NOT: extension {{(Swift.)?}}Bool{{.+}}Hashable
// NEGATIVE-NOT: extension {{(Swift.)?}}Bool{{.+}}Equatable
@available(macOS 10.97, iOS 22, *)
@available(tvOS, unavailable)
@available(swift 4.2.123)
public struct NestedAvailabilityOuter {
@available(iOS 23, *)
public struct Inner: PrivateSubProto {}
}
// CHECK-END: @available(swift 4.2.123)
// CHECK-END-NEXT: @available(OSX 10.97, iOS 23, *)
// CHECK-END-NEXT: @available(tvOS, unavailable)
// CHECK-END-NEXT: extension conformances.NestedAvailabilityOuter.Inner : conformances.PublicBaseProto {}
// CHECK-END: @usableFromInline
// CHECK-END-NEXT: internal protocol _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
| apache-2.0 | 1cc4bd29251b881b61c720702f47e8b8 | 39.264228 | 199 | 0.768905 | 4.332896 | false | false | false | false |
jacobwhite/firefox-ios | Sync/KeyBundle.swift | 2 | 11448 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import FxA
import Account
import SwiftyJSON
private let KeyLength = 32
open class KeyBundle: Hashable {
let encKey: Data
let hmacKey: Data
open class func fromKSync(_ kSync: Data) -> KeyBundle {
return KeyBundle(encKey: kSync.subdata(in: 0..<KeyLength),
hmacKey: kSync.subdata(in: KeyLength..<(2 * KeyLength)))
}
open class func random() -> KeyBundle {
// Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which
// on iOS is populated by the OS from kernel-level sources of entropy.
// That should mean that we don't need to seed or initialize anything before calling
// this. That is probably not true on (some versions of) OS X.
return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32))
}
open class var invalid: KeyBundle {
return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")!
}
public init?(encKeyB64: String, hmacKeyB64: String) {
guard let e = Bytes.decodeBase64(encKeyB64),
let h = Bytes.decodeBase64(hmacKeyB64) else {
return nil
}
self.encKey = e
self.hmacKey = h
}
public init(encKey: Data, hmacKey: Data) {
self.encKey = encKey
self.hmacKey = hmacKey
}
fileprivate func _hmac(_ ciphertext: Data) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) {
let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CCHmac(hmacAlgorithm, hmacKey.getBytes(), hmacKey.count, ciphertext.getBytes(), ciphertext.count, result)
return (result, digestLen)
}
open func hmac(_ ciphertext: Data) -> Data {
let (result, digestLen) = _hmac(ciphertext)
let data = NSMutableData(bytes: result, length: digestLen)
result.deinitialize()
result.deallocate(capacity: digestLen)
return data as Data
}
/**
* Returns a hex string for the HMAC.
*/
open func hmacString(_ ciphertext: Data) -> String {
let (result, digestLen) = _hmac(ciphertext)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
result.deallocate(capacity: digestLen)
return String(hash)
}
open func encrypt(_ cleartext: Data, iv: Data?=nil) -> (ciphertext: Data, iv: Data)? {
let iv = iv ?? Bytes.generateRandomBytes(16)
let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt))
let byteCount = cleartext.count + kCCBlockSizeAES128
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = Data(bytes: b, count: Int(copied))
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return (d, iv)
}
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return nil
}
// You *must* verify HMAC before calling this.
open func decrypt(_ ciphertext: Data, iv: Data) -> String? {
let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt))
let byteCount = ciphertext.count + kCCBlockSizeAES128
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = Data(bytes: b, count: Int(copied))
let s = String(data: d, encoding: .utf8)
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return s
}
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return nil
}
fileprivate func crypt(_ input: Data, iv: Data, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutableRawPointer, count: Int) {
let resultSize = input.count + kCCBlockSizeAES128
var copied: Int = 0
let result = UnsafeMutableRawPointer.allocate(bytes: resultSize, alignedTo: MemoryLayout<Void>.size)
let success: CCCryptorStatus =
CCCrypt(op,
CCHmacAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
encKey.getBytes(),
kCCKeySizeAES256,
iv.getBytes(),
input.getBytes(),
input.count,
result,
resultSize,
&copied
)
return (success, result, copied)
}
open func verify(hmac: Data, ciphertextB64: Data) -> Bool {
let expectedHMAC = hmac
let computedHMAC = self.hmac(ciphertextB64)
return (expectedHMAC == computedHMAC)
}
/**
* Swift can't do functional factories. I would like to have one of the following
* approaches be viable:
*
* 1. Derive the constructor from the consumer of the factory.
* 2. Accept a type as input.
*
* Neither of these are viable, so we instead pass an explicit constructor closure.
*
* Most of these approaches produce either odd compiler errors, or -- worse --
* compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159).
*
* For this reason, be careful trying to simplify or improve this code.
*/
open func factory<T: CleartextPayloadJSON>(_ f: @escaping (JSON) -> T) -> (String) -> T? {
return { (payload: String) -> T? in
let potential = EncryptedJSON(json: payload, keyBundle: self)
if !potential.isValid() {
return nil
}
let cleartext = potential.cleartext
if cleartext == nil {
return nil
}
return f(cleartext!)
}
}
// TODO: how much do we want to move this into EncryptedJSON?
open func serializer<T: CleartextPayloadJSON>(_ f: @escaping (T) -> JSON) -> (Record<T>) -> JSON? {
return { (record: Record<T>) -> JSON? in
let json = f(record.payload)
if json.isNull() {
// This should never happen, but if it does, we don't want to leak this
// record to the server!
return nil
}
// Get the most basic kind of encoding: no pretty printing.
// This can throw; if so, we return nil.
// `rawData` simply calls JSONSerialization.dataWithJSONObject:options:error, which
// guarantees UTF-8 encoded output.
guard let bytes: Data = try? json.rawData(options: []) else { return nil }
// Given a valid non-null JSON object, we don't ever expect a round-trip to fail.
assert(!JSON(bytes).isNull())
// We pass a null IV, which means "generate me a new one".
// We then include the generated IV in the resulting record.
if let (ciphertext, iv) = self.encrypt(bytes, iv: nil) {
// So we have the encrypted payload. Now let's build the envelope around it.
let ciphertext = ciphertext.base64EncodedString
// The HMAC is computed over the base64 string. As bytes. Yes, I know.
if let encodedCiphertextBytes = ciphertext.data(using: .ascii, allowLossyConversion: false) {
let hmac = self.hmacString(encodedCiphertextBytes)
let iv = iv.base64EncodedString
// The payload is stringified JSON. Yes, I know.
let payload: Any = JSON(["ciphertext": ciphertext, "IV": iv, "hmac": hmac]).stringValue()! as Any
let obj = ["id": record.id,
"sortindex": record.sortindex,
// This is how SwiftyJSON wants us to express a null that we want to
// serialize. Yes, this is gross.
"ttl": record.ttl ?? NSNull(),
"payload": payload]
return JSON(obj)
}
}
return nil
}
}
open func asPair() -> [String] {
return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString]
}
open var hashValue: Int {
return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue
}
public static func ==(lhs: KeyBundle, rhs: KeyBundle) -> Bool {
return lhs.encKey == rhs.encKey && lhs.hmacKey == rhs.hmacKey
}
}
open class Keys: Equatable {
let valid: Bool
let defaultBundle: KeyBundle
var collectionKeys: [String: KeyBundle] = [String: KeyBundle]()
public init(defaultBundle: KeyBundle) {
self.defaultBundle = defaultBundle
self.valid = true
}
public init(payload: KeysPayload?) {
if let payload = payload, payload.isValid(),
let keys = payload.defaultKeys {
self.defaultBundle = keys
self.collectionKeys = payload.collectionKeys
self.valid = true
return
}
self.defaultBundle = KeyBundle.invalid
self.valid = false
}
public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) {
let f: (JSON) -> KeysPayload = { KeysPayload($0) }
let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f))
self.init(payload: keysRecord?.payload)
}
open class func random() -> Keys {
return Keys(defaultBundle: KeyBundle.random())
}
open func forCollection(_ collection: String) -> KeyBundle {
if let bundle = collectionKeys[collection] {
return bundle
}
return defaultBundle
}
open func encrypter<T>(_ collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> {
return RecordEncrypter(bundle: forCollection(collection), encoder: encoder)
}
open func asPayload() -> KeysPayload {
let json: JSON = JSON([
"id": "keys",
"collection": "crypto",
"default": self.defaultBundle.asPair(),
"collections": mapValues(self.collectionKeys, f: { $0.asPair() })
])
return KeysPayload(json)
}
public static func ==(lhs: Keys, rhs: Keys) -> Bool {
return lhs.valid == rhs.valid &&
lhs.defaultBundle == rhs.defaultBundle &&
lhs.collectionKeys == rhs.collectionKeys
}
}
/**
* Yup, these are basically typed tuples.
*/
public struct RecordEncoder<T: CleartextPayloadJSON> {
let decode: (JSON) -> T
let encode: (T) -> JSON
}
public struct RecordEncrypter<T: CleartextPayloadJSON> {
let serializer: (Record<T>) -> JSON?
let factory: (String) -> T?
init(bundle: KeyBundle, encoder: RecordEncoder<T>) {
self.serializer = bundle.serializer(encoder.encode)
self.factory = bundle.factory(encoder.decode)
}
init(serializer: @escaping (Record<T>) -> JSON?, factory: @escaping (String) -> T?) {
self.serializer = serializer
self.factory = factory
}
}
| mpl-2.0 | c8a4e7bbba4c318b183530d4888b42b7 | 36.048544 | 144 | 0.598445 | 4.657445 | false | false | false | false |
southfox/jfwindguru | JFWindguru/Classes/Model/Color.swift | 1 | 626 | //
// Color.swift
// Pods
//
// Created by javierfuchs on 7/27/17.
//
//
import Foundation
public struct Color {
var alpha: Float = 0
var red: Float = 0
var green: Float = 0
var blue: Float = 0
public init?(a: Float = 0, r: Float = 0, g: Float = 0, b: Float = 0) {
alpha = a
red = r
green = g
blue = b
}
init(dictionary: [String: AnyObject?]) {
// TODO
}
public var description : String {
var aux : String = "\(type(of:self)): "
aux += "(\(alpha),\(red),\(green),\(blue))"
return aux
}
}
| mit | 626fe3f21abbb1e0705066def43bd6a6 | 16.885714 | 74 | 0.472843 | 3.556818 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/dynamic_value/main.swift | 2 | 1447 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
class SomeClass {
var x : Int
init() {
x = 33
}
}
class SomeOtherClass : SomeClass {
var y : Int
override init () {
y = 0xFF
super.init()
x = 66
}
}
class YetAnotherClass : SomeOtherClass {
var z : Int
override init() {
z = 0xBEEF
super.init()
x = 99
y = 0xDEAD
}
}
class AWrapperClass {
var aWrappedObject : SomeClass
init() {
aWrappedObject = YetAnotherClass()
}
}
class Base <A> {
var v : Int
init(_ x : A) {
v = 0x1ACABA1A
}
}
class Derived <A> : Base<A> {
var q : Int
override init (_ x : A) {
q = 0xDEADBEEF
super.init(x)
}
}
func app() -> () {
var aWrapper = AWrapperClass()
var anItem : SomeClass = aWrapper.aWrappedObject
var aBase : Base<Int> = Derived(3)
print("a fooBar is a cute object, too bad there is no such thing as a fooBar in this app") // Set a breakpoint here
print("this line is pretty much useless, just used to step and see if we survive a step") // Set a breakpoint here
}
app()
| apache-2.0 | fa9c005856625fa5a8be53686c9ffca3 | 18.293333 | 116 | 0.61161 | 3.259009 | false | false | false | false |
2794129697/-----mx | CoolXuePlayer/LoginViewController.swift | 1 | 9201 | //
// LoginViewController.swift
// CoolXuePlayer
//
// Created by lion-mac on 15/6/4.
// Copyright (c) 2015年 lion-mac. All rights reserved.
//
import UIKit
import Foundation
class LoginViewController: UIViewController,UIAlertViewDelegate,UITextFieldDelegate{
var qqLogin:QQLogin!
var qqUserInfo:QQUserInfo!
@IBOutlet weak var userIdTextField: UITextField!
@IBOutlet weak var pwdTextField: UITextField!
var alertView:UIAlertView!
override func viewDidLoad() {
super.viewDidLoad()
}
func showAlertView(tag _tag:Int,title:String,message:String,delegate:UIAlertViewDelegate,cancelButtonTitle:String){
if alertView == nil {
alertView = UIAlertView()
}
alertView.title = title
alertView.message = message
alertView.delegate = self
alertView.addButtonWithTitle(cancelButtonTitle)
alertView.tag = _tag
alertView.show()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.loginBnClicked("")
self.userIdTextField.resignFirstResponder()
self.pwdTextField.resignFirstResponder()
return true
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
//println("buttonIndex=\(buttonIndex)")
if alertView.tag == 0 {
}else if alertView.tag == 1 {
self.navigationController?.popViewControllerAnimated(true)
}
}
@IBAction func loginBnClicked(sender: AnyObject) {
LoginTool.loginType = LoginType.None
var userid = self.userIdTextField.text
var upwd = self.pwdTextField.text
// if userid.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
// self.showAlertView(tag: 0,title: "提示", message: "用户名不能为空!", delegate: self, cancelButtonTitle: "确定")
// return
// }
// if upwd.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
// self.showAlertView(tag: 0,title: "提示", message: "密码不能为空!", delegate: self, cancelButtonTitle: "确定")
// return
// }
userid = "[email protected]"
upwd = "123456"
var url = "http://www.icoolxue.com/account/login"
var bodyParam:Dictionary = ["username":userid,"password":upwd]
HttpManagement.requestttt(url, method: "POST",bodyParam: bodyParam,headParam:nil) { (repsone:NSHTTPURLResponse,data:NSData) -> Void in
var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary
println(bdict)
var code:Int = bdict["code"] as! Int
var userAccount:NSUserDefaults = NSUserDefaults.standardUserDefaults()
if HttpManagement.HttpResponseCodeCheck(code, viewController: self){
userAccount.setObject(true, forKey: "is_login")
userAccount.setObject(userid,forKey: "uid")
userAccount.setObject(upwd,forKey: "upwd")
LoginTool.isLogin = true
LoginTool.isNeedUserLogin = false
self.showAlertView(tag:1,title: "提示", message: "登录成功!", delegate: self, cancelButtonTitle: "确定")
}else{
userAccount.removeObjectForKey("uid")
userAccount.removeObjectForKey("upwd")
self.showAlertView(tag:0,title: "提示", message: "登录失败!", delegate: self, cancelButtonTitle: "确定")
}
}
// var url = "http://www.icoolxue.com/account/login"
// var param:Dictionary = ["username":"[email protected]","password":"123456"]
// HttpManagement.httpTask.POST(url, parameters: param) { (response:HTTPResponse) -> Void in
// if response.statusCode == 200 {
// //var str = NSString(data: response.responseObject as!NSData, encoding:NSUTF8StringEncoding)
// var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(response.responseObject as! NSData, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary
// println(bdict)
// var code:Int = bdict["code"] as! Int
// if HttpManagement.HttpResponseCodeCheck(code, viewController: self){
// var alert:UIAlertView = UIAlertView(title: "提示", message: "登录成功!", delegate: self, cancelButtonTitle: "确定")
// alert.show()
// }
//
// }
// }
}
//QQ登录
@IBAction func bnQQLoginClicked(sender: UIButton) {
if self.qqLogin == nil {
self.qqLogin = QQLogin()
}
LoginTool.loginType = LoginType.QQ
println("accessToken=====>\(self.qqLogin.tencentOAuth.accessToken)")
println("expirationDate=====>\(self.qqLogin.tencentOAuth.expirationDate)")
println("authorizeState=====>\(TencentOAuth.authorizeState)")
println("authMode=====>\(self.qqLogin.tencentOAuth.authMode)")
//qq授权
self.qqLogin.authorize(self.qqAuthorizeCallBack)
}
//授权回调
func qqAuthorizeCallBack(cancelled:Bool,loginSucceed:Bool){
println("\nqqAuthorizeCallBack")
if loginSucceed {
if self.qqLogin.tencentOAuth.accessToken != nil{
D3Notice.showText("登录成功",time:D3Notice.longTime,autoClear:true)
println("accessToken=\(self.qqLogin.tencentOAuth.accessToken)")//D49FC381ECFDEDA8B72DC8776BC44974
println("openId=\(self.qqLogin.tencentOAuth.openId)")//FD70E2CF311CCE980467453A4A26FAF4
println("expirationDate=\(self.qqLogin.tencentOAuth.expirationDate)")//2015-08-13 07:03:49 +0000
//自己服务登录
self.qqServerLogin(self.qqLogin.tencentOAuth.openId,accessToken: self.qqLogin.tencentOAuth.accessToken)
self.qqLogin.getUserInfo(self.qqGetUserInfoResponseCallBack)
}else{
println("登录不成功 没有获取accesstoken");
}
}else if cancelled {
println("QQ用户取消登录")
D3Notice.showText("取消登录",time:D3Notice.longTime,autoClear:true)
}else{
println("QQ登录失败")
D3Notice.showText("登录失败",time:D3Notice.longTime,autoClear:true)
}
}
//获取QQ用户信息回调
func qqGetUserInfoResponseCallBack(response: APIResponse!){
println("\ngetUserInfoResponseCallBack")
self.qqUserInfo = QQUserInfo(dictQQUser: response.jsonResponse)
println("self.qqUserInfo.nickname=\(self.qqUserInfo.nickname)")
}
func qqServerLogin(openId:String,accessToken:String){
var url = "http://www.icoolxue.com/qq/login"
var bodyParam:Dictionary = ["openId":openId,"accessToken":accessToken]
HttpManagement.requestttt(url, method: "POST",bodyParam: bodyParam,headParam:nil) { (repsone:NSHTTPURLResponse,data:NSData) -> Void in
var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary
println(bdict)
var code:Int = bdict["code"] as! Int
var userAccount:NSUserDefaults = NSUserDefaults.standardUserDefaults()
if HttpManagement.HttpResponseCodeCheck(code, viewController: self){
userAccount.setObject(true, forKey: "is_login")
userAccount.setObject(self.qqLogin.tencentOAuth.openId,forKey: "openId")
userAccount.setObject(self.qqLogin.tencentOAuth.accessToken,forKey: "accessToken")
LoginTool.isLogin = true
LoginTool.isNeedUserLogin = false
self.showAlertView(tag:1,title: "提示", message: "登录成功!", delegate: self, cancelButtonTitle: "确定")
}else{
userAccount.removeObjectForKey("openId")
userAccount.removeObjectForKey("accessToken")
self.showAlertView(tag:0,title: "提示", message: "登录失败!", delegate: self, cancelButtonTitle: "确定")
}
}
}
//新浪微博登录
@IBAction func bnSinaLoginClicked(sender: AnyObject) {
LoginTool.loginType = LoginType.Sina
var request: WBAuthorizeRequest! = WBAuthorizeRequest.request() as! WBAuthorizeRequest
request.redirectURI = "https://api.weibo.com/oauth2/default.html"
request.scope = "all"
WeiboSDK.sendRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| lgpl-3.0 | 515234da4ee65124b5b6c7329d501397 | 44.871795 | 191 | 0.640917 | 4.501761 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/DiscouragedOptionalCollectionRule.swift | 1 | 6881 | import Foundation
import SourceKittenFramework
public struct DiscouragedOptionalCollectionRule: ASTRule, OptInRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "discouraged_optional_collection",
name: "Discouraged Optional Collection",
description: "Prefer empty collection over optional collection.",
kind: .idiomatic,
nonTriggeringExamples: DiscouragedOptionalCollectionExamples.nonTriggeringExamples,
triggeringExamples: DiscouragedOptionalCollectionExamples.triggeringExamples
)
public func validate(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
let offsets = variableViolations(file: file, kind: kind, dictionary: dictionary) +
functionViolations(file: file, kind: kind, dictionary: dictionary)
return offsets.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0))
}
}
// MARK: - Private
private func variableViolations(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [Int] {
guard
SwiftDeclarationKind.variableKinds.contains(kind),
let offset = dictionary.offset,
let typeName = dictionary.typeName else { return [] }
return typeName.optionalCollectionRanges().map { _ in offset }
}
private func functionViolations(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [Int] {
guard
SwiftDeclarationKind.functionKinds.contains(kind),
let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
let length = dictionary.length,
let offset = dictionary.offset,
case let start = nameOffset + nameLength,
case let end = dictionary.bodyOffset ?? offset + length,
case let contents = file.contents.bridge(),
let range = contents.byteRangeToNSRange(start: start, length: end - start),
let match = file.match(pattern: "->\\s*(.*?)\\{", excludingSyntaxKinds: excludingKinds, range: range).first
else { return [] }
return contents.substring(with: match).optionalCollectionRanges().map { _ in nameOffset }
}
private let excludingKinds = SyntaxKind.allKinds.subtracting([.typeidentifier])
}
private extension String {
/// Ranges of optional collections within the bounds of the string.
///
/// Example: [String: [Int]?]
///
/// [ S t r i n g : [ I n t ] ? ]
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/// ^ ^
/// = [9, 14]
/// = [9, 15), mathematical interval, w/ lower and upper bounds.
///
/// Example: [String: [Int]?]?
///
/// [ S t r i n g : [ I n t ] ? ] ?
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/// ^ ^ ^ ^
/// = [0, 16], [9, 14]
/// = [0, 17), [9, 15), mathematical interval, w/ lower and upper bounds.
///
/// Example: var x = Set<Int>?
///
/// v a r x = S e t < I n t > ?
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/// ^ ^
/// = [8, 16]
/// = [8, 17), mathematical interval, w/ lower and upper bounds.
///
/// - Returns: An array of ranges.
func optionalCollectionRanges() -> [Range<String.Index>] {
let squareBrackets = balancedRanges(from: "[", to: "]").compactMap { range -> Range<String.Index>? in
guard
range.upperBound < endIndex,
let finalIndex = index(range.upperBound, offsetBy: 1, limitedBy: endIndex),
self[range.upperBound] == "?" else { return nil }
return Range(range.lowerBound..<finalIndex)
}
let angleBrackets = balancedRanges(from: "<", to: ">").compactMap { range -> Range<String.Index>? in
guard
range.upperBound < endIndex,
let initialIndex = index(range.lowerBound, offsetBy: -3, limitedBy: startIndex),
let finalIndex = index(range.upperBound, offsetBy: 1, limitedBy: endIndex),
self[initialIndex..<range.lowerBound] == "Set",
self[range.upperBound] == "?" else { return nil }
return Range(initialIndex..<finalIndex)
}
return squareBrackets + angleBrackets
}
/// Indices of character within the bounds of the string.
///
/// Example:
/// a m a n h a
/// 0 1 2 3 4 5
/// ^ ^ ^
/// = [0, 2, 5]
///
/// - Parameter character: The character to look for.
/// - Returns: Array of indices.
private func indices(of character: Character) -> [String.Index] {
return indices.compactMap { self[$0] == character ? $0 : nil }
}
/// Ranges of balanced substrings.
///
/// Example: ((1+2)*(3+4))
///
/// ( ( 1 + 2 ) * ( 3 + 4 ) )
/// 0 1 2 3 4 5 6 7 8 9 10 11 12
/// ^ ^ ^ ^ ^ ^
/// = [0, 12], [1, 5], [7, 11]
/// = [0, 13), [1, 6), [7, 12), mathematical interval, w/ lower and upper bounds.
///
/// - Parameters:
/// - prefix: The prefix to look for.
/// - suffix: The suffix to look for.
/// - Returns: Array of ranges of balanced substrings
private func balancedRanges(from prefix: Character, to suffix: Character) -> [Range<String.Index>] {
return indices(of: prefix).compactMap { prefixIndex in
var pairCount = 0
var currentIndex = prefixIndex
var foundCharacter = false
while currentIndex < endIndex {
let character = self[currentIndex]
currentIndex = index(after: currentIndex)
if character == prefix { pairCount += 1 }
if character == suffix { pairCount -= 1 }
if pairCount != 0 { foundCharacter = true }
if pairCount == 0 && foundCharacter { break }
}
return pairCount == 0 && foundCharacter ? Range(prefixIndex..<currentIndex) : nil
}
}
}
| mit | 5610bf20e69bf03bc56980c3b779cbaa | 40.451807 | 119 | 0.535097 | 4.497386 | false | false | false | false |
sharath-cliqz/browser-ios | Extensions/Today/TodayViewController.swift | 2 | 12842 | /* 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
import NotificationCenter
import Shared
import SnapKit
private let log = Logger.browserLogger
struct TodayUX {
// Cliqz: changed privateBrowsingColor to white
static let privateBrowsingColor = UIColor.white //UIColor(colorString: "CE6EFC")
static let backgroundHightlightColor = UIColor(white: 216.0/255.0, alpha: 44.0/255.0)
static let linkTextSize: CGFloat = 10.0
static let labelTextSize: CGFloat = 14.0
static let imageButtonTextSize: CGFloat = 14.0
static let copyLinkButtonHeight: CGFloat = 44
static let verticalWidgetMargin: CGFloat = 10
static let horizontalWidgetMargin: CGFloat = 10
static var defaultWidgetTextMargin: CGFloat = 22
static let buttonSpacerMultipleOfScreen = 0.4
}
@objc (TodayViewController)
class TodayViewController: UIViewController, NCWidgetProviding {
fileprivate lazy var newTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewTab), forControlEvents: .touchUpInside)
//Cliqz: Changed the localization string
imageButton.labelText = NSLocalizedString("New Tab", tableName: "Cliqz", comment: "Widget item for a new tab")
let button = imageButton.button
button.setImage(UIImage(named: "new_tab_button_normal"), for: UIControlState())
#if !CLIQZ
button.setImage(UIImage(named: "new_tab_button_highlight"), for: .highlighted)
#endif
let label = imageButton.label
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
imageButton.sizeToFit()
return imageButton
}()
fileprivate lazy var newPrivateTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewPrivateTab), forControlEvents: .touchUpInside)
// Cliqz: Changed Button title to ours
imageButton.labelText = NSLocalizedString("New Private Tab", tableName: "Cliqz", comment: "New private tab title")
let button = imageButton.button
button.setImage(UIImage(named: "new_private_tab_button_normal"), for: UIControlState())
#if !CLIQZ
button.setImage(UIImage(named: "new_private_tab_button_highlight"), for: .highlighted)
#endif
let label = imageButton.label
label.textColor = TodayUX.privateBrowsingColor
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
return imageButton
}()
fileprivate lazy var openCopiedLinkButton: ButtonWithSublabel = {
let button = ButtonWithSublabel()
button.setTitle(NSLocalizedString("TodayWidget.GoToCopiedLinkLabel", tableName: "Today", value: "Go to copied link", comment: "Go to link on clipboard"), for: UIControlState())
button.addTarget(self, action: #selector(onPressOpenClibpoard), for: .touchUpInside)
// We need to set the background image/color for .Normal, so the whole button is tappable.
button.setBackgroundColor(UIColor.clear, forState: UIControlState())
button.setBackgroundColor(TodayUX.backgroundHightlightColor, forState: .highlighted)
button.setImage(UIImage(named: "copy_link_icon"), for: UIControlState())
button.label.font = UIFont.systemFont(ofSize: TodayUX.labelTextSize)
button.subtitleLabel.font = UIFont.systemFont(ofSize: TodayUX.linkTextSize)
return button
}()
fileprivate lazy var buttonSpacer: UIView = UIView()
fileprivate var copiedURL: URL? {
if let string = UIPasteboard.general.string,
let url = URL(string: string), url.isWebPage() {
return url
} else {
return nil
}
}
fileprivate var hasCopiedURL: Bool {
return copiedURL != nil
}
fileprivate var scheme: String {
#if CLIQZ
// Cliqz: return correct scheme so that today's widget redirect to Cliqz app not firefox app
return "cliqzbeta"
#else
guard let string = Bundle.main.object(forInfoDictionaryKey: "MozInternalURLScheme") as? String else {
// Something went wrong/weird, but we should fallback to the public one.
return "firefox"
}
return string
#endif
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(buttonSpacer)
// New tab button and label.
// Cliqz: Updated constraints to center the buttons
view.addSubview(newTabButton)
newTabButton.snp_makeConstraints { make in
make.centerY.equalTo(buttonSpacer).offset(5)
make.centerX.equalTo(buttonSpacer.snp_left).offset(-6)
}
// New private tab button and label.
view.addSubview(newPrivateTabButton)
newPrivateTabButton.snp_makeConstraints { make in
make.centerY.equalTo(newTabButton.snp_centerY)
make.centerX.equalTo(buttonSpacer.snp_right)
}
newTabButton.label.snp_makeConstraints { make in
make.leading.greaterThanOrEqualTo(view)
}
newPrivateTabButton.label.snp_makeConstraints { make in
make.trailing.lessThanOrEqualTo(view)
make.left.greaterThanOrEqualTo(newTabButton.label.snp_right).priorityHigh()
}
buttonSpacer.snp_makeConstraints { make in
make.width.equalTo(view.snp_width).multipliedBy(TodayUX.buttonSpacerMultipleOfScreen)
make.centerX.equalTo(view.snp_centerX)
make.top.equalTo(view.snp_top).offset(TodayUX.verticalWidgetMargin)
make.bottom.equalTo(newPrivateTabButton.label.snp_bottom).priorityLow()
}
view.addSubview(openCopiedLinkButton)
openCopiedLinkButton.snp_makeConstraints { make in
make.top.equalTo(buttonSpacer.snp_bottom).offset(TodayUX.verticalWidgetMargin)
make.width.equalTo(view.snp_width)
make.centerX.equalTo(view.snp_centerX)
make.height.equalTo(TodayUX.copyLinkButtonHeight)
}
view.snp_remakeConstraints { make in
var extraHeight = TodayUX.verticalWidgetMargin
if hasCopiedURL {
extraHeight += TodayUX.copyLinkButtonHeight + TodayUX.verticalWidgetMargin
}
make.height.equalTo(buttonSpacer.snp_height).offset(extraHeight).priorityHigh()
}
#if CLIQZ
// Cliqz: Hide private tab option from today's widget
openCopiedLinkButton.isHidden = true
#endif
}
override func viewDidLayoutSubviews() {
let preferredWidth: CGFloat = view.frame.size.width / CGFloat(buttonSpacer.subviews.count + 1)
newPrivateTabButton.label.preferredMaxLayoutWidth = preferredWidth
newTabButton.label.preferredMaxLayoutWidth = preferredWidth
}
func updateCopiedLink() {
if let url = self.copiedURL {
self.openCopiedLinkButton.isHidden = false
self.openCopiedLinkButton.subtitleLabel.isHidden = SystemUtils.isDeviceLocked()
self.openCopiedLinkButton.subtitleLabel.text = url.absoluteString
self.openCopiedLinkButton.remakeConstraints()
} else {
self.openCopiedLinkButton.isHidden = true
}
self.view.setNeedsLayout()
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
TodayUX.defaultWidgetTextMargin = defaultMarginInsets.left
return UIEdgeInsetsMake(0, 0, TodayUX.verticalWidgetMargin, 0)
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
DispatchQueue.main.async {
// updates need to be made on the main thread
#if !CLIQZ
self.updateCopiedLink()
#endif
// and we need to call the completion handler in every branch.
completionHandler(NCUpdateResult.newData)
}
completionHandler(NCUpdateResult.newData)
}
// MARK: Button behaviour
@objc func onPressNewTab(_ view: UIView) {
openContainingApp("")
}
@objc func onPressNewPrivateTab(_ view: UIView) {
openContainingApp("?private=true")
}
fileprivate func openContainingApp(_ urlSuffix: String = "") {
let urlString = "\(scheme)://\(urlSuffix)"
self.extensionContext?.open(URL(string: urlString)!) { success in
// log.info("Extension opened containing app: \(success)")
}
}
@objc func onPressOpenClibpoard(_ view: UIView) {
if let urlString = UIPasteboard.general.string,
let _ = URL(string: urlString) {
let encodedString =
urlString.escape()
openContainingApp("?url=\(encodedString)")
}
}
}
extension UIButton {
func setBackgroundColor(_ color: UIColor, forState state: UIControlState) {
let colorView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
colorView.backgroundColor = color
UIGraphicsBeginImageContext(colorView.bounds.size)
if let context = UIGraphicsGetCurrentContext() {
colorView.layer.render(in: context)
}
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: state)
}
}
class ImageButtonWithLabel: UIView {
lazy var button = UIButton()
lazy var label = UILabel()
var labelText: String? {
set {
label.text = newValue
label.sizeToFit()
}
get {
return label.text
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(frame: CGRect.zero)
performLayout()
}
func performLayout() {
addSubview(button)
addSubview(label)
button.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.equalTo(self)
make.centerX.equalTo(self)
}
snp_makeConstraints { make in
make.width.equalTo(button)
make.height.equalTo(button)
}
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
label.snp_makeConstraints { make in
make.centerX.equalTo(button.snp_centerX)
make.top.equalTo(button.snp_bottom).offset(TodayUX.verticalWidgetMargin / 2)
}
}
func addTarget(_ target: AnyObject?, action: Selector, forControlEvents events: UIControlEvents) {
button.addTarget(target, action: action, for: events)
}
}
class ButtonWithSublabel: UIButton {
lazy var subtitleLabel: UILabel = UILabel()
lazy var label: UILabel = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
fileprivate func performLayout() {
self.snp_removeConstraints()
let titleLabel = self.label
titleLabel.textColor = UIColor.white
self.titleLabel?.removeFromSuperview()
addSubview(titleLabel)
let imageView = self.imageView!
let subtitleLabel = self.subtitleLabel
subtitleLabel.textColor = UIColor.white
self.addSubview(subtitleLabel)
imageView.snp_remakeConstraints { make in
make.centerY.equalTo(self.snp_centerY)
make.right.equalTo(titleLabel.snp_left).offset(-TodayUX.horizontalWidgetMargin)
}
subtitleLabel.lineBreakMode = .byTruncatingTail
subtitleLabel.snp_makeConstraints { make in
make.left.equalTo(titleLabel.snp_left)
make.top.equalTo(titleLabel.snp_bottom).offset(TodayUX.verticalWidgetMargin / 2)
make.right.lessThanOrEqualTo(self.snp_right).offset(-TodayUX.horizontalWidgetMargin)
}
remakeConstraints()
}
func remakeConstraints() {
self.label.snp_remakeConstraints { make in
make.top.equalTo(self.snp_top).offset(TodayUX.verticalWidgetMargin / 2)
make.left.equalTo(self.snp_left).offset(TodayUX.defaultWidgetTextMargin).priorityHigh()
}
}
override func setTitle(_ text: String?, for state: UIControlState) {
self.label.text = text
super.setTitle(text, for: state)
}
}
| mpl-2.0 | ea6692994dfb35ed8d2947839984c012 | 33.896739 | 184 | 0.66594 | 4.754535 | false | false | false | false |
finn-no/Finjinon | Sources/PhotoCaptureViewController/CaptureManager.swift | 1 | 14920 | //
// Copyright (c) 2017 FINN.no AS. All rights reserved.
//
import UIKit
import AVFoundation
enum CaptureManagerViewfinderMode {
case fullScreen
case window
}
protocol CaptureManagerDelegate: AnyObject {
func captureManager(_ manager: CaptureManager, didCaptureImageData data: Data?, withMetadata metadata: NSDictionary?)
func captureManager(_ manager: CaptureManager, didDetectLightingCondition: LightingCondition)
func captureManager(_ manager: CaptureManager, didFailWithError error: NSError)
}
extension CaptureManagerDelegate {
func captureManager(_ manager: CaptureManager, didFailWithError error: NSError) {}
}
class CaptureManager: NSObject {
weak var delegate: CaptureManagerDelegate?
let previewLayer: AVCaptureVideoPreviewLayer
let viewfinderMode: CaptureManagerViewfinderMode
var flashMode: AVCaptureDevice.FlashMode = .auto
var hasFlash: Bool {
return cameraDevice?.hasFlash ?? false && cameraDevice?.isFlashAvailable ?? false
}
var supportedFlashModes: [AVCaptureDevice.FlashMode] {
var modes: [AVCaptureDevice.FlashMode] = []
for mode in [AVCaptureDevice.FlashMode.off, AVCaptureDevice.FlashMode.auto, AVCaptureDevice.FlashMode.on] {
#if !targetEnvironment(simulator)
if cameraOutput.supportedFlashModes.contains(mode) {
modes.append(mode)
}
#endif
}
return modes
}
private let session = AVCaptureSession()
private let captureQueue = DispatchQueue(label: "no.finn.finjinon-captures", attributes: [])
private var cameraDevice: AVCaptureDevice?
private var cameraOutput: AVCapturePhotoOutput
private var cameraSettings: AVCapturePhotoSettings?
private var orientation = AVCaptureVideoOrientation.portrait
private var lastVideoCaptureTime = CMTime()
private let lowLightService = LowLightService()
private var didCaptureImageCompletion: ((Data, NSDictionary) -> Void)?
/// Array of vision requests
override init() {
session.sessionPreset = AVCaptureSession.Preset.photo
var viewfinderMode: CaptureManagerViewfinderMode {
let screenBounds = UIScreen.main.nativeBounds
let ratio = screenBounds.height / screenBounds.width
return ratio <= 1.5 ? .fullScreen : .window
}
self.viewfinderMode = viewfinderMode
previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.videoGravity = self.viewfinderMode == .fullScreen ? AVLayerVideoGravity.resizeAspectFill : AVLayerVideoGravity.resize
cameraOutput = AVCapturePhotoOutput()
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(changedOrientationNotification(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
changedOrientationNotification(nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - API
func authorizationStatus() -> AVAuthorizationStatus {
return AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
}
// Prepares the capture session, possibly asking the user for camera access.
func prepare(_ completion: @escaping (NSError?) -> Void) {
switch authorizationStatus() {
case .authorized:
configure(completion)
case .notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { granted in
if granted {
self.configure(completion)
} else {
DispatchQueue.main.async {
completion(self.accessDeniedError(FinjinonCameraAccessErrorDeniedInitialRequestCode))
}
}
})
case .denied, .restricted:
completion(accessDeniedError())
@unknown default:
return
}
}
func stop(_ completion: (() -> Void)?) {
captureQueue.async { [weak self] in
guard let self = self else { return }
if self.session.isRunning {
self.session.stopRunning()
}
completion?()
}
}
@available(*, deprecated, message: "Conform to the CaptureManagerDelegate and handle it in captureManager(_ manager: CaptureManager, didCaptureImage data: Data?, withMetadata metadata: NSDictionary?)")
func captureImage(_ completion: @escaping (Data, NSDictionary) -> Void) {
didCaptureImageCompletion = completion
captureImage()
}
func captureImage() {
captureQueue.async { [weak self] in
guard let self = self else { return }
guard let connection = self.cameraOutput.connection(with: .video) else { return }
connection.videoOrientation = self.orientation
self.cameraSettings = self.createCapturePhotoSettingsObject()
guard let cameraSettings = self.cameraSettings else { return }
#if !targetEnvironment(simulator)
if !self.cameraOutput.supportedFlashModes.contains(cameraSettings.flashMode) {
cameraSettings.flashMode = .off
}
#endif
self.cameraOutput.capturePhoto(with: cameraSettings, delegate: self)
}
}
func lockFocusAtPointOfInterest(_ pointInLayer: CGPoint) {
let pointInCamera = previewLayer.captureDevicePointConverted(fromLayerPoint: pointInLayer)
lockCurrentCameraDeviceForConfiguration { cameraDevice in
if let cameraDevice = self.cameraDevice, cameraDevice.isFocusPointOfInterestSupported {
cameraDevice.focusPointOfInterest = pointInCamera
cameraDevice.focusMode = .autoFocus
}
}
}
func changeFlashMode(_ newMode: AVCaptureDevice.FlashMode, completion: @escaping () -> Void) {
flashMode = newMode
cameraSettings = createCapturePhotoSettingsObject()
DispatchQueue.main.async(execute: completion)
}
// Next available flash mode, or nil if flash is unsupported
func nextAvailableFlashMode() -> AVCaptureDevice.FlashMode? {
if !hasFlash {
return nil
}
// Find the next available mode, or wrap around
var nextIndex = 0
if let idx = supportedFlashModes.firstIndex(of: flashMode) {
nextIndex = idx + 1
}
let startIndex = min(nextIndex, supportedFlashModes.count)
let next = supportedFlashModes[startIndex ..< supportedFlashModes.count].first ?? supportedFlashModes.first
if let nextFlashMode = next { flashMode = nextFlashMode }
return next
}
// Orientation change function required because we've locked the interface in portrait
// and DeviceOrientation does not map 1:1 with AVCaptureVideoOrientation
@objc func changedOrientationNotification(_: Notification?) {
let currentDeviceOrientation = UIDevice.current.orientation
switch currentDeviceOrientation {
case .faceDown, .faceUp, .unknown:
break
case .landscapeLeft, .landscapeRight, .portrait, .portraitUpsideDown:
orientation = AVCaptureVideoOrientation(rawValue: currentDeviceOrientation.rawValue) ?? .portrait
@unknown default:
return
}
}
}
// MARK: - Private methods
private extension CaptureManager {
func createCapturePhotoSettingsObject() -> AVCapturePhotoSettings {
var newCameraSettings: AVCapturePhotoSettings
if let currentCameraSettings = cameraSettings {
newCameraSettings = AVCapturePhotoSettings(from: currentCameraSettings)
newCameraSettings.flashMode = flashMode
} else {
newCameraSettings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecJPEG, AVVideoCompressionPropertiesKey: [AVVideoQualityKey: 0.9]])
newCameraSettings.flashMode = flashMode
}
return newCameraSettings
}
func accessDeniedError(_ code: Int = FinjinonCameraAccessErrorDeniedCode) -> NSError {
let info = [NSLocalizedDescriptionKey: "finjinon.cameraAccessDenied".localized()]
return NSError(domain: FinjinonCameraAccessErrorDomain, code: code, userInfo: info)
}
func lockCurrentCameraDeviceForConfiguration(_ configurator: @escaping (AVCaptureDevice?) -> Void) {
captureQueue.async { [weak self] in
guard let self = self else { return }
do {
try self.cameraDevice?.lockForConfiguration()
} catch let error as NSError {
self.delegate?.captureManager(self, didFailWithError: error)
} catch {
fatalError()
}
configurator(self.cameraDevice)
self.cameraDevice?.unlockForConfiguration()
}
}
func configure(_ completion: @escaping (NSError?) -> Void) {
captureQueue.async { [weak self] in
guard let self = self else { return }
self.cameraDevice = self.cameraDeviceWithPosition(.back)
var error: NSError?
do {
let input = try AVCaptureDeviceInput(device: self.cameraDevice!)
if self.session.canAddInput(input) {
self.session.addInput(input)
} else {
NSLog("Failed to add input \(input) to session \(self.session)")
}
} catch let error1 as NSError {
error = error1
self.delegate?.captureManager(self, didFailWithError: error1)
}
if self.session.canAddOutput(self.cameraOutput) {
self.session.addOutput(self.cameraOutput)
}
let videoOutput = self.makeVideoDataOutput()
if self.session.canAddOutput(videoOutput) {
self.session.addOutput(videoOutput)
}
if let cameraDevice = self.cameraDevice {
if cameraDevice.isFocusModeSupported(.continuousAutoFocus) {
do {
try cameraDevice.lockForConfiguration()
} catch let error1 as NSError {
error = error1
self.delegate?.captureManager(self, didFailWithError: error1)
}
cameraDevice.focusMode = .continuousAutoFocus
if cameraDevice.isSmoothAutoFocusSupported {
cameraDevice.isSmoothAutoFocusEnabled = true
}
cameraDevice.unlockForConfiguration()
}
}
self.session.startRunning()
DispatchQueue.main.async {
completion(error)
}
}
}
func cameraDeviceWithPosition(_ position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let deviceTypes: [AVCaptureDevice.DeviceType]
if #available(iOS 11.2, *) {
deviceTypes = [.builtInTrueDepthCamera, .builtInDualCamera, .builtInWideAngleCamera]
} else {
deviceTypes = [.builtInWideAngleCamera]
}
let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: .video, position: .unspecified)
let availableCameraDevices = discoverySession.devices
guard availableCameraDevices.isEmpty == false else {
print("Error no camera devices found")
return nil
}
for device in availableCameraDevices {
if device.position == position {
return device
}
}
return AVCaptureDevice.default(for: AVMediaType.video)
}
func makeVideoDataOutput() -> AVCaptureVideoDataOutput {
let output = AVCaptureVideoDataOutput()
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]
output.alwaysDiscardsLateVideoFrames = true
output.setSampleBufferDelegate(self, queue: DispatchQueue(label: "no.finn.finjinon-sample-buffer"))
return output
}
}
// MARK: - AVCapturePhotoCaptureDelegate
extension CaptureManager: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
// We either call the delegate or the completion block not both.
if didCaptureImageCompletion != nil && delegate != nil {
didCaptureImageCompletion = nil
}
guard error == nil else {
if let error = error { delegate?.captureManager(self, didFailWithError: error as NSError) }
return
}
if let sampleBuffer = photoSampleBuffer, let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: nil) {
if let metadata = CMCopyDictionaryOfAttachments(allocator: nil, target: sampleBuffer, attachmentMode: CMAttachmentMode(kCMAttachmentMode_ShouldPropagate)) as NSDictionary? {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if let completion = self.didCaptureImageCompletion {
completion(data, metadata)
} else {
self.delegate?.captureManager(self, didCaptureImageData: data, withMetadata: metadata)
}
}
} else {
if let error = error { delegate?.captureManager(self, didFailWithError: error as NSError) }
}
} else {
if let error = error { delegate?.captureManager(self, didFailWithError: error as NSError) }
}
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension CaptureManager: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
let fps: Int32 = 1 // Create pixel buffer and call the delegate 1 time per second
guard (time - lastVideoCaptureTime) >= CMTime.init(value: 1, timescale: fps) else {
return
}
lastVideoCaptureTime = time
if let lightningCondition = lowLightService.getLightningCondition(from: sampleBuffer) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.captureManager(self, didDetectLightingCondition: lightningCondition)
}
}
}
}
| mit | 19c537329239528095d66cc1648eef5e | 38.786667 | 292 | 0.649866 | 5.554728 | false | false | false | false |
loisie123/Cuisine-Project | Cuisine/TodayMealsViewController.swift | 1 | 3620 | //
// TodayMealsViewController.swift
// Cuisine
//
// Created by Lois van Vliet on 13-01-17.
// Copyright © 2017 Lois van Vliet. All rights reserved.
//
import UIKit
import Firebase
class TodayMealsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableViewImage: UITableView!
@IBOutlet weak var nameDay: UILabel!
var ref: FIRDatabaseReference?
var databaseHandle: FIRDatabaseHandle?
var day = String()
let types = ["Soup", "Sandwich", "Hot dish"]
var listAllNames = [[String]]()
var listCategoryname = [String]()
var listOfMeals = [meals]()
override func viewDidLoad() {
getMeals()
super.viewDidLoad()
nameDay.text = day
print(day)
ref = FIRDatabase.database().reference()
self.tableViewImage.reloadData()
}
//MARK:- Get meals from firebase
func getMeals(){
let ref = FIRDatabase.database().reference()
ref.child("cormet").child("different days").child(day).queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in
(self.listAllNames, self.listOfMeals) = self.getMealInformation(snapshot: snapshot, categories: self.types, kindOfCategorie: "type")
self.tableViewImage.reloadData()
})
}
//MARK:- Tableview with sections
func numberOfSections(in tableView: UITableView) -> Int {
return listAllNames.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listAllNames[section].count-1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return listAllNames[section][0]
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25))
returnedView = makeSectionHeader(returnedView: returnedView, section: section, listAllNames: self.listAllNames)
return returnedView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let mealcell = tableView.dequeueReusableCell(withIdentifier: "mealCell", for: indexPath) as! MealsTodayTableViewCell
for meal in listOfMeals{
if meal.name == listAllNames[indexPath.section][indexPath.row+1]{
mealcell.nameMeal.text = meal.name
mealcell.priceMeal.text = "€ \(meal.price!)"
mealcell.numberOfLikes.text = " \(meal.likes!) likes"
mealcell.day = day
mealcell.typeMealLiked = meal.typeOFMEal
if meal.likes != 0 {
for person in meal.peopleWhoLike{
if person == FIRAuth.auth()!.currentUser!.uid{
mealcell.unlikeButton.isHidden = false
mealcell.likeButton.isHidden = true
}
}
} else{
mealcell.unlikeButton.isHidden = true
mealcell.likeButton.isHidden = false
}
}
}
return mealcell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
| mit | 56abec8085b1432d2440f8b88e100481 | 30.181034 | 144 | 0.583356 | 5.072931 | false | false | false | false |
oz-swu/studyIOS | studyIOS/studyIOS/Classes/Home/Model/CategoryModel.swift | 1 | 617 | //
// CategoryModel.swift
// studyIOS
//
// Created by musou on 30/06/2017.
// Copyright © 2017 musou. All rights reserved.
//
import UIKit
class CategoryModel: NSObject {
var cate1Id : String = "";
var cate2Id : String = "";
var cate2Name : String = "";
var shortName : String = "";
var pic : String = "";
var icon : String = "";
var smallIcon : String = "";
var count : Int = 0;
init(_ dict : [String : NSObject]) {
super.init();
setValuesForKeys(dict);
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | 233f1e9fa4c8442f0fc81838bc666e97 | 20.241379 | 73 | 0.564935 | 3.826087 | false | false | false | false |
LeonardoCardoso/Clipboarded | Clipboarded/Helpers/Extensions/UIImageExtension.swift | 1 | 2144 | //
// RBResizer.swift
// Locker
//
// Created by Hampton Catlin on 6/20/14.
// Copyright (c) 2014 rarebit. All rights reserved.
// Updated by Justin Winter on 11/29/15.
//
import UIKit
extension UIImage {
func RBSquareImageTo(size: CGSize) -> UIImage? {
return self.size.width == self.size.height ? self.RBSquareImage(targetSize: size) : self.RBResizeImage(targetSize: size)
}
func RBSquareImage(targetSize: CGSize) -> UIImage? {
let originalWidth = self.size.width
let originalHeight = self.size.height
let edge: CGFloat = targetSize.width
let posX = (originalWidth - edge) / 2.0
let posY = (originalHeight - edge) / 2.0
let cropSquare = CGRect(x: posX, y: posY, width: edge, height: edge)
let imageRef = self.cgImage!.cropping(to: cropSquare);
return UIImage(cgImage: imageRef!, scale: UIScreen.main.scale, orientation: self.imageOrientation)
}
func RBResizeImage(targetSize: CGSize) -> UIImage {
let size = self.size
let widthRatio = targetSize.width / self.size.width
let heightRatio = targetSize.height / self.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| mit | c70a4ae056e25a0d0aa252e3d42f457c | 34.147541 | 128 | 0.625466 | 4.494759 | false | false | false | false |
yrchen/edx-app-ios | Source/DiscussionNewPostViewController.swift | 1 | 12797 | //
// DiscussionNewPostViewController.swift
// edX
//
// Created by Tang, Jeff on 6/1/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
struct DiscussionNewThread {
let courseID: String
let topicID: String
let type: PostThreadType
let title: String
let rawBody: String
}
public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate {
public class Environment: NSObject {
private let courseDataManager : CourseDataManager
private let networkManager : NetworkManager?
private weak var router: OEXRouter?
public init(courseDataManager : CourseDataManager, networkManager : NetworkManager?, router: OEXRouter?) {
self.courseDataManager = courseDataManager
self.networkManager = networkManager
self.router = router
}
}
private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text
private let environment: Environment
private let growingTextController = GrowingTextViewController()
private let insetsController = ContentInsetsController()
@IBOutlet private var scrollView: UIScrollView!
@IBOutlet private var backgroundView: UIView!
@IBOutlet private var contentTextView: OEXPlaceholderTextView!
@IBOutlet private var titleTextField: UITextField!
@IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl!
@IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private var topicButton: UIButton!
@IBOutlet private var postButton: SpinnerButton!
private let loadController = LoadStateViewController()
private let courseID: String
private let topics = BackedStream<[DiscussionTopic]>()
private var selectedTopic: DiscussionTopic?
private var optionsViewController: MenuOptionsViewController?
private var selectedThreadType: PostThreadType = .Discussion {
didSet {
switch selectedThreadType {
case .Discussion:
self.contentTextView.placeholder = Strings.courseDashboardDiscussion
postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion)
case .Question:
self.contentTextView.placeholder = Strings.question
postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle, withTitle: Strings.postQuestion)
}
}
}
public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) {
self.environment = environment
self.courseID = courseID
super.init(nibName: "DiscussionNewPostViewController", bundle: nil)
let stream = environment.courseDataManager.discussionManagerForCourseWithID(courseID).topics
topics.backWithStream(stream.map {
return DiscussionTopic.linearizeTopics($0)
}
)
self.selectedTopic = selectedTopic ?? self.firstSelectableTopic
}
private var firstSelectableTopic : DiscussionTopic? {
let selectablePredicate = { (topic : DiscussionTopic) -> Bool in
topic.isSelectable
}
guard let topics = self.topics.value, selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else {
return nil
}
return topics[selectableTopicIndex]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBAction func postTapped(sender: AnyObject) {
postButton.enabled = false
postButton.showProgress = true
// create new thread (post)
if let topic = selectedTopic, topicID = topic.id {
let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType ?? .Discussion, title: titleTextField.text ?? "", rawBody: contentTextView.text)
let apiRequest = DiscussionAPI.createNewThread(newThread)
environment.networkManager?.taskForRequest(apiRequest) {[weak self] result in
self?.dismissViewControllerAnimated(true, completion: nil)
self?.postButton.enabled = true
self?.postButton.showProgress = false
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = Strings.post
let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: nil)
cancelItem.oex_setAction { [weak self]() -> Void in
self?.dismissViewControllerAnimated(true, completion: nil)
}
self.navigationItem.leftBarButtonItem = cancelItem
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets
contentTextView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes
contentTextView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight()
contentTextView.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle)
contentTextView.delegate = self
self.view.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
let segmentOptions : [(title : String, value : PostThreadType)] = [
(title : Strings.discussion, value : .Discussion),
(title : Strings.question, value : .Question),
]
let options = segmentOptions.withItemIndexes()
for option in options {
discussionQuestionSegmentedControl.setTitle(option.value.title, forSegmentAtIndex: option.index)
}
discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in
if let segmentedControl = control as? UISegmentedControl {
let index = segmentedControl.selectedSegmentIndex
let threadType = segmentOptions[index].value
self?.selectedThreadType = threadType
}
else {
assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum")
}
}, forEvents: UIControlEvents.ValueChanged)
titleTextField.placeholder = Strings.title
titleTextField.defaultTextAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes
if let topic = selectedTopic, name = topic.name {
let title = Strings.topic(topic: name)
topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(title), forState: .Normal)
}
let insets = OEXStyles.sharedStyles().standardTextViewInsets
topicButton.titleEdgeInsets = UIEdgeInsetsMake(0, insets.left, 0, insets.right)
topicButton.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle)
topicButton.localizedHorizontalContentAlignment = .Leading
let dropdownLabel = UILabel()
let style = OEXTextStyle(weight : .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark())
dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(style)
topicButton.addSubview(dropdownLabel)
dropdownLabel.snp_makeConstraints { (make) -> Void in
make.trailing.equalTo(topicButton).offset(-insets.right)
make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0)
}
topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in
self?.showTopicPicker()
}, forEvents: UIControlEvents.TouchUpInside)
postButton.enabled = false
titleTextField.oex_addAction({[weak self] _ in
self?.validatePostButton()
}, forEvents: .EditingChanged)
let tapGesture = UITapGestureRecognizer()
tapGesture.addAction {[weak self] _ in
self?.contentTextView.resignFirstResponder()
self?.titleTextField.resignFirstResponder()
}
self.backgroundView.addGestureRecognizer(tapGesture)
self.growingTextController.setupWithScrollView(scrollView, textView: contentTextView, bottomView: postButton)
self.insetsController.setupInController(self, scrollView: scrollView)
// Force setting it to call didSet which is only called out of initialization context
self.selectedThreadType = .Discussion
loadController.setupInController(self, contentView: self.scrollView)
updateLoadState()
}
private func updateLoadState() {
if let _ = self.topics.value {
loadController.state = LoadState.Loaded
}
else {
loadController.state = LoadState.Failed(error: nil, icon: nil, message: Strings.failedToLoadTopics, attributedMessage: nil, accessibilityMessage: nil)
return
}
}
func showTopicPicker() {
if self.optionsViewController != nil {
return
}
self.optionsViewController = MenuOptionsViewController()
self.optionsViewController?.menuHeight = min((CGFloat)(self.view.frame.height - self.topicButton.frame.minY - self.topicButton.frame.height), MenuOptionsViewController.menuItemHeight * (CGFloat)(topics.value?.count ?? 0))
self.optionsViewController?.menuWidth = self.topicButton.frame.size.width
self.optionsViewController?.delegate = self
guard let courseTopics = topics.value else {
//Don't need to configure an empty state here because it's handled in viewDidLoad()
return
}
self.optionsViewController?.options = courseTopics.map {
return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "")
}
self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex()
self.view.addSubview(self.optionsViewController!.view)
self.optionsViewController!.view.snp_makeConstraints { (make) -> Void in
make.trailing.equalTo(self.topicButton)
make.leading.equalTo(self.topicButton)
make.top.equalTo(self.topicButton.snp_bottom).offset(-3)
make.bottom.equalTo(self.view.snp_bottom)
}
self.optionsViewController?.view.alpha = 0.0
UIView.animateWithDuration(0.3) {
self.optionsViewController?.view.alpha = 1.0
}
}
private func selectedTopicIndex() -> Int? {
guard let selected = selectedTopic else {
return 0
}
return self.topics.value?.firstIndexMatching {
return $0.id == selected.id
}
}
public func viewTapped(sender: UITapGestureRecognizer) {
contentTextView.resignFirstResponder()
titleTextField.resignFirstResponder()
}
public func textViewDidChange(textView: UITextView) {
validatePostButton()
growingTextController.handleTextChange()
}
public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool {
return self.topics.value?[index].isSelectable ?? false
}
private func validatePostButton() {
self.postButton.enabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil
}
func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) {
selectedTopic = self.topics.value?[index]
if let topic = selectedTopic, name = topic.name where topic.id != nil {
topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(Strings.topic(topic: name)), forState: .Normal)
UIView.animateWithDuration(0.3, animations: {
self.optionsViewController?.view.alpha = 0.0
}, completion: {(finished: Bool) in
self.optionsViewController?.view.removeFromSuperview()
self.optionsViewController = nil
})
}
}
public override func viewDidLayoutSubviews() {
self.insetsController.updateInsets()
growingTextController.scrollToVisible()
}
}
| apache-2.0 | 53256267026864c8076a99a7bd94f5f0 | 40.548701 | 229 | 0.662421 | 5.59554 | false | false | false | false |
konanxu/WeiBoWithSwift | WeiBo/WeiBo/Classes/Home/View/StatusFooterView.swift | 1 | 2439 | //
// StatusFooterView.swift
// WeiBo
//
// Created by Konan on 16/3/22.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
class StatusFooterView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
private func setUpUI(){
addSubview(leftBtn)
addSubview(centerBtn)
addSubview(rightBtn)
leftBtn.snp_makeConstraints { (make) -> Void in
make.left.equalTo(leftBtn.superview!)
make.width.equalTo(kWidth / 3)
make.height.equalTo(kHeight)
make.top.equalTo(leftBtn.superview!)
}
centerBtn.snp_makeConstraints { (make) -> Void in
make.left.equalTo(leftBtn.snp_right)
make.width.equalTo(kWidth / 3)
make.height.equalTo(kHeight)
make.top.equalTo(leftBtn.superview!)
}
rightBtn.snp_makeConstraints { (make) -> Void in
make.left.equalTo(centerBtn.snp_right)
make.width.equalTo(kWidth / 3)
make.height.equalTo(kHeight)
make.top.equalTo(leftBtn.superview!)
}
}
private lazy var leftBtn:UIButton = {
return self.getBtn("timeline_icon_retweet", btnTitleName: "转发")
}()
private lazy var centerBtn:UIButton = {
return self.getBtn("timeline_icon_comment", btnTitleName: "评论")
}()
private lazy var rightBtn:UIButton = {
return self.getBtn("timeline_icon_unlike", btnTitleName: "赞")
}()
private func getBtn(btnImageName:String,btnTitleName:String) ->UIButton {
let btn = UIButton()
btn.setImage(UIImage(named:btnImageName), forState: UIControlState.Normal)
btn.setTitle(btnTitleName, forState: UIControlState.Normal)
btn.titleLabel?.font = UIFont.systemFontOfSize(10)
btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
btn.setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "timeline_card_bottom_line_highlighted"), forState: UIControlState.Highlighted)
return btn
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | ed347cc8294fc66763610f006f2efb8b | 33.169014 | 125 | 0.628607 | 4.241259 | false | false | false | false |
Draveness/RbSwift | RbSwift/Hash/Hash+Transform.swift | 1 | 7750 | //
// Hash+Transform.swift
// RbSwift
//
// Created by Draveness on 06/04/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
// MARK: - Transform
public extension Hash {
/// Returns a new hash containing the contents of `otherHash` and the contents of hsh.
/// If no block is specified, the value for entries with duplicate keys will be that
/// of `otherHash`.
///
/// let h1 = ["a": 100, "b": 200]
/// let h2 = ["b": 254, "c": 300]
///
/// h1.merge(h2) #=> ["a": 100, "b": 254, "c": 300]))
///
/// Otherwise the value for each duplicate key is determined by calling
/// the block with the key, its value in hsh and its value in `otherHash`.
///
/// h1.merge(h2) { (key, oldval, newval) in
/// newval - oldval
/// } #=> ["a": 100, "b": 54, "c": 300]
///
/// h1 #=> ["a": 100, "b": 200]
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: A new hash containing the contents of both hash.
func merge(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
var map = Hash<Key, Value>()
for (k, v) in self {
map[k] = v
}
for (key, value) in otherHash {
if let oldValue = map[key],
let closure = closure {
map[key] = closure(key, oldValue, value)
} else {
map[key] = value
}
}
return map
}
/// An alias to `Hash#merge(otherHash:)` methods.
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: A new hash containing the contents of both hash.
func update(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
return merge(otherHash, closure: closure)
}
/// A mutating version of `Hash#merge(otherHash:closure:)`
///
/// let h1 = ["a": 100, "b": 200]
/// let h2 = ["b": 254, "c": 300]
///
/// h1.merge(h2) #=> ["a": 100, "b": 254, "c": 300]))
/// h1 #=> ["a": 100, "b": 254, "c": 300]))
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: Self
@discardableResult
mutating func merged(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
self = self.merge(otherHash, closure: closure)
return self
}
/// An alias to `Hash#merged(otherHash:)` methods.
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: Self
@discardableResult
mutating func updated(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
return merged(otherHash, closure: closure)
}
/// Removes all key-value pairs from hsh.
///
/// var hash = ["a": 100]
/// hash.clear() #=> [:]
/// hash #=> [:]
///
/// - Returns: Self with empty hash.
@discardableResult
mutating func clear() -> Hash<Key, Value> {
self = [:]
return self
}
/// An alias to `Hash#removeValue(forKey:)`.
///
/// var hash = ["a": 100, "b": 200]
/// hash.delete("a") #=> 100
/// hash #=> ["b": 200]
///
/// - Parameter key: A key of hash.
/// - Returns: Corresponding value or nil.
@discardableResult
mutating func delete(_ key: Key) -> Value? {
return self.removeValue(forKey: key)
}
/// Replaces the contents of hsh with the contents of otherHash.
///
/// var hash = ["a": 100, "b": 200]
/// hash.replace(["c": 300]) #=> ["c": 300]
/// hash #=> ["c": 300]
///
/// - Parameter otherHash: Another hash instance.
/// - Returns: Self
@discardableResult
mutating func replace(_ otherHash: Hash<Key, Value>) -> Hash<Key, Value> {
self = otherHash
return self
}
/// Associates the value given by value with the key given by key.
///
/// var hash = ["a": 4]
/// hash.store("b", 5) #=> 5
/// hash #=> ["a": 4, "b": 5]
///
/// - Parameters:
/// - key: A key
/// - value: A value
/// - Returns: The passing value
@discardableResult
mutating func store(_ key: Key, _ value: Value) -> Value {
self[key] = value
return value
}
/// Removes a key-value pair from hsh and returns it as the two-item
/// array ( key, value ), or nil if the hash is empty.
///
/// var hash = ["a": 4]
/// hash.shift() #=> ("b", 5)
/// hash.shift() #=> nil
///
/// - Returns: A key-value pair
@discardableResult
mutating func shift() -> (Key, Value)? {
if let key = self.keys.first {
return (key, delete(key)!)
}
return nil
}
/// Return a new with the results of running block once for every value.
/// This method does not change the keys.
///
/// let hash = ["a": 1, "b": 2, "c": 3]
/// hash.transformValues { $0 * $0 + 1 } #=> ["a": 2, "b": 5, "c": 10]
/// hash.transformValues { $0.to_s } #=> ["a": "1", "b": "2", "c": "3"]
///
/// - Parameter closure: An closure accepts a value return an new value.
/// - Returns: An new hash with key-value pair
func transformValues<T>(_ closure: @escaping (Value) -> T) -> [Key: T] {
var results: [Key: T] = [:]
for (key, value) in self {
results[key] = closure(value)
}
return results
}
/// Return a new with the results of running block once for every value.
/// This method does not change the keys. The mutates version of
/// `Hash#transformedValues(closure:)` can only accepts a closure with
/// `(Value) -> Value` type.
///
/// var hash = ["a": 1, "b": 2, "c": 3]
/// hash.transformedValues {
/// $0 * $0 + 1
/// } #=> ["a": 2, "b": 5, "c": 10]
/// hash #=> ["a": 2, "b": 5, "c": 10]
///
/// - Parameter closure: An closure accepts a value return an new value.
/// - Returns: Self
@discardableResult
mutating func transformedValues(_ closure: @escaping (Value) -> Value) -> [Key: Value] {
var results: [Key: Value] = [:]
for (key, value) in self {
results[key] = closure(value)
}
self = results
return self
}
}
public extension Hash where Value: Hashable {
/// Returns a new hash created by using hsh’s values as keys, and the keys as values.
///
/// let hash1 = ["a": 100, "b": 200]
/// hash1.invert #=> [100: "a", 200: "b"]
///
/// let hash2 = ["cat": "feline", "dog": "canine", "cow": "bovine"]
/// hash2.invert.invert #=> ["cat": "feline", "dog": "canine", "cow": "bovine"]
///
/// If a key with the same value already exists in the hsh, then the random one will be used.
///
/// let hash3 = ["cat": 1, "dog": 1]
/// hash3.invert #=> [1: "dog"] or [1: "cat"]
///
var invert: [Value: Key] {
var results: [Value: Key] = [:]
for (key, value) in self {
results[value] = key
}
return results
}
}
| mit | 6db3db660ae8192a37006a54fbcf3c79 | 33.584821 | 126 | 0.507035 | 3.591562 | false | false | false | false |
oskarpearson/rileylink_ios | NightscoutUploadKit/NightscoutUploader.swift | 1 | 20686 | //
// NightscoutUploader.swift
// RileyLink
//
// Created by Pete Schwamb on 3/9/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import UIKit
import MinimedKit
import Crypto
public enum UploadError: Error {
case httpError(status: Int, body: String)
case missingTimezone
case invalidResponse(reason: String)
case unauthorized
}
private let defaultNightscoutEntriesPath = "/api/v1/entries"
private let defaultNightscoutTreatmentPath = "/api/v1/treatments"
private let defaultNightscoutDeviceStatusPath = "/api/v1/devicestatus"
private let defaultNightscoutAuthTestPath = "/api/v1/experiments/test"
public class NightscoutUploader {
enum DexcomSensorError: Int {
case sensorNotActive = 1
case sensorNotCalibrated = 5
case badRF = 12
}
public var siteURL: URL
public var apiSecret: String
private(set) var entries = [NightscoutEntry]()
private(set) var deviceStatuses = [[String: Any]]()
private(set) var treatmentsQueue = [NightscoutTreatment]()
private(set) var lastMeterMessageRxTime: Date?
public private(set) var observingPumpEventsSince: Date!
private(set) var lastStoredTreatmentTimestamp: Date? {
get {
return UserDefaults.standard.lastStoredTreatmentTimestamp
}
set {
UserDefaults.standard.lastStoredTreatmentTimestamp = newValue
}
}
public var errorHandler: ((_ error: Error, _ context: String) -> Void)?
private var dataAccessQueue: DispatchQueue = DispatchQueue(label: "com.rileylink.NightscoutUploadKit.dataAccessQueue", attributes: [])
public func reset() {
observingPumpEventsSince = Date(timeIntervalSinceNow: TimeInterval(hours: -24))
lastStoredTreatmentTimestamp = nil
}
public init(siteURL: URL, APISecret: String) {
self.siteURL = siteURL
self.apiSecret = APISecret
observingPumpEventsSince = lastStoredTreatmentTimestamp ?? Date(timeIntervalSinceNow: TimeInterval(hours: -24))
}
// MARK: - Processing data from pump
/**
Enqueues pump history events for upload, with automatic retry management.
- parameter events: An array of timestamped history events. Only types with known Nightscout mappings will be uploaded.
- parameter source: The device identifier to display in Nightscout
- parameter pumpModel: The pump model info associated with the events
*/
public func processPumpEvents(_ events: [TimestampedHistoryEvent], source: String, pumpModel: PumpModel) {
// Find valid event times
let newestEventTime = events.last?.date
// Find the oldest event that might still be updated.
var oldestUpdatingEventDate: Date?
for event in events {
switch event.pumpEvent {
case let bolus as BolusNormalPumpEvent:
let deliveryFinishDate = event.date.addingTimeInterval(bolus.duration)
if newestEventTime == nil || deliveryFinishDate.compare(newestEventTime!) == .orderedDescending {
// This event might still be updated.
oldestUpdatingEventDate = event.date
break
}
default:
continue
}
}
if oldestUpdatingEventDate != nil {
observingPumpEventsSince = oldestUpdatingEventDate!
} else if newestEventTime != nil {
observingPumpEventsSince = newestEventTime!
}
for treatment in NightscoutPumpEvents.translate(events, eventSource: source) {
treatmentsQueue.append(treatment)
}
self.flushAll()
}
/**
Enqueues pump glucose events for upload, with automatic retry management.
- parameter events: An array of timestamped glucose events. Only sensor glucose data will be uploaded.
- parameter source: The device identifier to display in Nightscout
*/
public func processGlucoseEvents(_ events: [TimestampedGlucoseEvent], source: String) -> Date? {
for event in events {
if let entry = NightscoutEntry(event: event, device: source) {
entries.append(entry)
}
}
var timestamp: Date? = nil
if let lastEntry = entries.last {
timestamp = lastEntry.timestamp
}
self.flushAll()
return timestamp
}
/**
Attempts to upload pump history events.
This method will not retry if the network task failed.
- parameter pumpEvents: An array of timestamped history events. Only types with known Nightscout mappings will be uploaded.
- parameter source: The device identifier to display in Nightscout
- parameter pumpModel: The pump model info associated with the events
- parameter completionHandler: A closure to execute when the task completes. It has a single argument for any error that might have occurred during the upload.
*/
public func upload(_ pumpEvents: [TimestampedHistoryEvent], forSource source: String, from pumpModel: PumpModel, completionHandler: @escaping (Error?) -> Void) {
let treatments = NightscoutPumpEvents.translate(pumpEvents, eventSource: source).map { $0.dictionaryRepresentation }
postToNS(treatments, endpoint: defaultNightscoutTreatmentPath) { (result) in
switch result {
case .success( _):
completionHandler(nil)
case .failure(let error):
completionHandler(error)
}
}
}
/// Attempts to upload nightscout treatment objects.
/// This method will not retry if the network task failed.
///
/// - parameter treatments: An array of nightscout treatments.
/// - parameter completionHandler: A closure to execute when the task completes. It has a single argument for any error that might have occurred during the upload.
public func upload(_ treatments: [NightscoutTreatment], completionHandler: @escaping (Either<[String],Error>) -> Void) {
postToNS(treatments.map { $0.dictionaryRepresentation }, endpoint: defaultNightscoutTreatmentPath, completion: completionHandler)
}
/// Attempts to modify nightscout treatments. This method will not retry if the network task failed.
///
/// - parameter treatments: An array of nightscout treatments. The id attribute must be set, identifying the treatment to update.
/// - parameter completionHandler: A closure to execute when the task completes. It has a single argument for any error that might have occurred during the modify.
public func modifyTreatments(_ treatments:[NightscoutTreatment], completionHandler: @escaping (Error?) -> Void) {
dataAccessQueue.async {
let modifyGroup = DispatchGroup()
var errors = [Error]()
for treatment in treatments {
modifyGroup.enter()
self.putToNS( treatment.dictionaryRepresentation, endpoint: defaultNightscoutTreatmentPath ) { (error) in
if let error = error {
errors.append(error)
}
modifyGroup.leave()
}
}
_ = modifyGroup.wait(timeout: DispatchTime.distantFuture)
completionHandler(errors.first)
}
}
/// Attempts to delete treatments from nightscout. This method will not retry if the network task failed.
///
/// - parameter id: An array of nightscout treatment ids
/// - parameter completionHandler: A closure to execute when the task completes. It has a single argument for any error that might have occurred during the deletion.
public func deleteTreatmentsById(_ ids:[String], completionHandler: @escaping (Error?) -> Void) {
dataAccessQueue.async {
let deleteGroup = DispatchGroup()
var errors = [Error]()
for id in ids {
deleteGroup.enter()
self.deleteFromNS(id, endpoint: defaultNightscoutTreatmentPath) { (error) in
if let error = error {
errors.append(error)
}
deleteGroup.leave()
}
}
_ = deleteGroup.wait(timeout: DispatchTime.distantFuture)
completionHandler(errors.first)
}
}
public func uploadDeviceStatus(_ status: DeviceStatus) {
deviceStatuses.append(status.dictionaryRepresentation)
flushAll()
}
// Entries [ { sgv: 375,
// date: 1432421525000,
// dateString: '2015-05-23T22:52:05.000Z',
// trend: 1,
// direction: 'DoubleUp',
// device: 'share2',
// type: 'sgv' } ]
public func uploadSGVFromMySentryPumpStatus(_ status: MySentryPumpStatusMessageBody, device: String) {
var recordSGV = true
let glucose: Int = {
switch status.glucose {
case .active(glucose: let glucose):
return glucose
case .highBG:
return 401
case .weakSignal:
return DexcomSensorError.badRF.rawValue
case .meterBGNow, .calError:
return DexcomSensorError.sensorNotCalibrated.rawValue
case .lost, .missing, .ended, .unknown, .off, .warmup:
recordSGV = false
return DexcomSensorError.sensorNotActive.rawValue
}
}()
// Create SGV entry from this mysentry packet
if (recordSGV) {
guard let sensorDateComponents = status.glucoseDateComponents, let sensorDate = sensorDateComponents.date else {
return
}
let previousSGV: Int?
let previousSGVNotActive: Bool?
switch status.previousGlucose {
case .active(glucose: let previousGlucose):
previousSGV = previousGlucose
previousSGVNotActive = nil
default:
previousSGV = nil
previousSGVNotActive = true
}
let direction: String = {
switch status.glucoseTrend {
case .up:
return "SingleUp"
case .upUp:
return "DoubleUp"
case .down:
return "SingleDown"
case .downDown:
return "DoubleDown"
case .flat:
return "Flat"
}
}()
let entry = NightscoutEntry(glucose: glucose, timestamp: sensorDate, device: device, glucoseType: .Sensor, previousSGV: previousSGV, previousSGVNotActive: previousSGVNotActive, direction: direction)
entries.append(entry)
}
flushAll()
}
public func handleMeterMessage(_ msg: MeterMessage) {
// TODO: Should only accept meter messages from specified meter ids.
// Need to add an interface to allow user to specify linked meters.
if msg.ackFlag {
return
}
let date = Date()
// Skip duplicates
if lastMeterMessageRxTime == nil || lastMeterMessageRxTime!.timeIntervalSinceNow.minutes < -3 {
let entry = NightscoutEntry(glucose: msg.glucose, timestamp: date, device: "Contour Next Link", glucoseType: .Meter)
entries.append(entry)
lastMeterMessageRxTime = date
}
}
// MARK: - Uploading
func flushAll() {
flushDeviceStatuses()
flushEntries()
flushTreatments()
}
func deleteFromNS(_ id: String, endpoint:String, completion: @escaping (Error?) -> Void) {
let resource = "\(endpoint)/\(id)"
callNS(nil, endpoint: resource, method: "DELETE") { (result) in
switch result {
case .success( _):
completion(nil)
case .failure(let error):
completion(error)
}
}
}
func putToNS(_ json: Any, endpoint:String, completion: @escaping (Error?) -> Void) {
callNS(json, endpoint: endpoint, method: "PUT") { (result) in
switch result {
case .success( _):
completion(nil)
case .failure(let error):
completion(error)
}
}
}
func postToNS(_ json: [Any], endpoint:String, completion: @escaping (Either<[String],Error>) -> Void) {
if json.count == 0 {
completion(.success([]))
return
}
callNS(json, endpoint: endpoint, method: "POST") { (result) in
switch result {
case .success(let json):
guard let insertedEntries = json as? [[String: Any]] else {
completion(.failure(UploadError.invalidResponse(reason: "Expected array of objects in JSON response")))
return
}
let ids = insertedEntries.map({ (entry: [String: Any]) -> String in
if let id = entry["_id"] as? String {
return id
} else {
// Upload still succeeded; likely that this is an old version of NS
// Instead of failing (which would cause retries later, we just mark
// This entry has having an id of 'NA', which will let us consider it
// uploaded.
//throw UploadError.invalidResponse(reason: "Invalid/missing id in response.")
return "NA"
}
})
completion(.success(ids))
case .failure(let error):
completion(.failure(error))
}
}
}
func callNS(_ json: Any?, endpoint:String, method:String, completion: @escaping (Either<Any,Error>) -> Void) {
let uploadURL = siteURL.appendingPathComponent(endpoint)
var request = URLRequest(url: uploadURL)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(apiSecret.sha1, forHTTPHeaderField: "api-secret")
do {
if let json = json {
let sendData = try JSONSerialization.data(withJSONObject: json, options: [])
let task = URLSession.shared.uploadTask(with: request, from: sendData, completionHandler: { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(UploadError.invalidResponse(reason: "Response is not HTTPURLResponse")))
return
}
if httpResponse.statusCode != 200 {
let error = UploadError.httpError(status: httpResponse.statusCode, body:String(data: data!, encoding: String.Encoding.utf8)!)
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(UploadError.invalidResponse(reason: "No data in response")))
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
completion(.success(json))
} catch {
completion(.failure(error))
return
}
})
task.resume()
} else {
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(UploadError.invalidResponse(reason: "Response is not HTTPURLResponse")))
return
}
if httpResponse.statusCode != 200 {
let error = UploadError.httpError(status: httpResponse.statusCode, body:String(data: data!, encoding: String.Encoding.utf8)!)
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(UploadError.invalidResponse(reason: "No data in response")))
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
completion(.success(json))
} catch {
completion(.failure(error))
return
}
})
task.resume()
}
} catch let error {
completion(.failure(error))
}
}
func flushDeviceStatuses() {
let inFlight = deviceStatuses
deviceStatuses = []
postToNS(inFlight as [Any], endpoint: defaultNightscoutDeviceStatusPath) { (result) in
switch result {
case .failure(let error):
self.errorHandler?(error, "Uploading device status")
// Requeue
self.deviceStatuses.append(contentsOf: inFlight)
case .success(_):
break
}
}
}
func flushEntries() {
let inFlight = entries
entries = []
postToNS(inFlight.map({$0.dictionaryRepresentation}), endpoint: defaultNightscoutEntriesPath) { (result) in
switch result {
case .failure(let error):
self.errorHandler?(error, "Uploading nightscout entries")
// Requeue
self.entries.append(contentsOf: inFlight)
case .success(_):
break
}
}
}
func flushTreatments() {
let inFlight = treatmentsQueue
treatmentsQueue = []
postToNS(inFlight.map({$0.dictionaryRepresentation}), endpoint: defaultNightscoutTreatmentPath) { (result) in
switch result {
case .failure(let error):
self.errorHandler?(error, "Uploading nightscout treatment records")
// Requeue
self.treatmentsQueue.append(contentsOf: inFlight)
case .success(_):
if let last = inFlight.last {
self.lastStoredTreatmentTimestamp = last.timestamp
}
}
}
}
public func checkAuth(_ completion: @escaping (Error?) -> Void) {
let testURL = siteURL.appendingPathComponent(defaultNightscoutAuthTestPath)
var request = URLRequest(url: testURL)
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.setValue(apiSecret.sha1, forHTTPHeaderField:"api-secret")
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let error = error {
completion(error)
return
}
if let httpResponse = response as? HTTPURLResponse ,
httpResponse.statusCode != 200 {
if httpResponse.statusCode == 401 {
completion(UploadError.unauthorized)
} else {
let error = UploadError.httpError(status: httpResponse.statusCode, body:String(data: data!, encoding: String.Encoding.utf8)!)
completion(error)
}
} else {
completion(nil)
}
})
task.resume()
}
}
| mit | 74e3cd28893f3f9bacda5a9cddb9d2ba | 37.80863 | 210 | 0.567368 | 5.360197 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/Blueprints-master/Example-iOS/Common/Protocols/RouterProtocol.swift | 1 | 4616 | import UIKit
protocol RouterProtocol {
associatedtype StoryboardIdentifier: RawRepresentable
associatedtype ViewControllerType: UIViewController
var viewController: ViewControllerType? { get set }
func present<T: UIViewController>(storyboard: StoryboardIdentifier, identifier: String?, animated: Bool, modalPresentationStyle: UIModalPresentationStyle?, configure: ((T) -> Void)?, completion: ((T) -> Void)?)
func show<T: UIViewController>(storyboard: StoryboardIdentifier, identifier: String?, configure: ((T) -> Void)?)
func showDetailViewController<T: UIViewController>(storyboard: StoryboardIdentifier, identifier: String?, configure: ((T) -> Void)?)
}
extension RouterProtocol where StoryboardIdentifier.RawValue == String {
/**
Presents the intial view controller of the specified storyboard modally.
- parameter storyboard: Storyboard name.
- parameter identifier: View controller name.
- parameter configure: Configure the view controller before it is loaded.
- parameter completion: Completion the view controller after it is loaded.
*/
func present<T: UIViewController>(storyboard: StoryboardIdentifier, identifier: String? = nil, animated: Bool = true, modalPresentationStyle: UIModalPresentationStyle? = nil, configure: ((T) -> Void)? = nil, completion: ((T) -> Void)? = nil) {
let storyboard = UIStoryboard(name: storyboard.rawValue)
guard let destinationController = (identifier != nil
? storyboard.instantiateViewController(withIdentifier: identifier!)
: storyboard.instantiateInitialViewController()) as? T
else { return assertionFailure("Invalid controller for storyboard \(storyboard).") }
if let modalPresentationStyle = modalPresentationStyle {
destinationController.modalPresentationStyle = modalPresentationStyle
}
configure?(destinationController)
viewController?.present(destinationController, animated: animated) {
completion?(destinationController)
}
}
/**
Present the intial view controller of the specified storyboard in the primary context.
Set the initial view controller in the target storyboard or specify the identifier.
- parameter storyboard: Storyboard name.
- parameter identifier: View controller name.
- parameter configure: Configure the view controller before it is loaded.
*/
func show<T: UIViewController>(storyboard: StoryboardIdentifier, identifier: String? = nil, configure: ((T) -> Void)? = nil) {
let storyboard = UIStoryboard(name: storyboard.rawValue)
guard let destinationController = (identifier != nil
? storyboard.instantiateViewController(withIdentifier: identifier!)
: storyboard.instantiateInitialViewController()) as? T
else { return assertionFailure("Invalid controller for storyboard \(storyboard).") }
configure?(destinationController)
viewController?.show(destinationController, sender: self)
}
/**
Present the intial view controller of the specified storyboard in the secondary (or detail) context.
Set the initial view controller in the target storyboard or specify the identifier.
- parameter storyboard: Storyboard name.
- parameter identifier: View controller name.
- parameter configure: Configure the view controller before it is loaded.
*/
func showDetailViewController<T: UIViewController>(storyboard: StoryboardIdentifier, identifier: String? = nil, configure: ((T) -> Void)? = nil) {
let storyboard = UIStoryboard(name: storyboard.rawValue)
guard let destinationController = (identifier != nil
? storyboard.instantiateViewController(withIdentifier: identifier!)
: storyboard.instantiateInitialViewController()) as? T
else { return assertionFailure("Invalid controller for storyboard \(storyboard).") }
configure?(destinationController)
viewController?.showDetailViewController(destinationController, sender: self)
}
}
extension UIStoryboard {
/**
Creates and returns a storyboard object for the specified storyboard resource file in the main bundle of the current application.
- parameter name: The name of the storyboard resource file without the filename extension.
- returns: A storyboard object for the specified file. If no storyboard resource file matching name exists, an exception is thrown.
*/
convenience init(name: String) {
self.init(name: name, bundle: nil)
}
}
| mit | 684b65088076c8f5321e3e5e1d9ab0d4 | 46.56701 | 247 | 0.719766 | 5.803774 | false | true | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestSeries.swift | 1 | 1555 | //
// SoulvanaSeries.swift
// Pods
//
// Created by Evandro Harrison Hoffmann on 7/23/18.
//
import Foundation
public struct QuestSeries : Codable, Equatable {
public let id: String?
public let coverAsset: QuestAsset?
public let media: [QuestMedia]?
public let favouriteMedia: [QuestMedia]?
public let featuredMedia: [QuestMedia]?
public let latestMedia: [QuestMedia]?
public let publishedAt: String?
public let slug: String?
public let subtitle: String?
public let title: String?
public let authors: [QuestAuthor]?
}
// MARK: - JSON Key
public struct SingleQuestSeriesDataKey: Codable {
public let data: SingleQuestSeriesKey
}
public struct SingleQuestSeriesKey: Codable {
public let series: QuestSeries
}
// MARK: - Equatable
extension QuestSeries {
static public func ==(lhs: QuestSeries, rhs: QuestSeries) -> Bool {
if lhs.id != rhs.id {
return false
}
if lhs.coverAsset != rhs.coverAsset {
return false
}
if lhs.title != rhs.title {
return false
}
if lhs.subtitle != rhs.subtitle {
return false
}
if lhs.publishedAt != rhs.publishedAt {
return false
}
if lhs.slug != rhs.slug {
return false
}
if lhs.media != rhs.media {
return false
}
if lhs.authors != rhs.authors {
return false
}
return true
}
}
| mit | 9371a335f914f95e132edf0309ab00e1 | 20.30137 | 71 | 0.576206 | 4.367978 | false | false | false | false |
pauljohanneskraft/Algorithms-and-Data-structures | AlgorithmsDataStructures/Classes/Lists/DoublyLinkedList.swift | 1 | 4767 | //
// DoublyLinkedList.swift
// Algorithms&DataStructures
//
// Created by Paul Kraft on 09.08.16.
// Copyright © 2016 pauljohanneskraft. All rights reserved.
//
// swiftlint:disable trailing_whitespace
public struct DoublyLinkedList<Element>: InternalList {
mutating public func pushBack(_ element: Element) {
guard let root = root else {
self.root = DoublyLinkedItem(data: element)
return
}
root.pushBack(element)
assert(invariant, "Invariant conflict. \(self)")
}
public mutating func popBack() -> Element? {
if root?.next == nil {
let tmp = root?.data
root = nil
assert(invariant, "Invariant conflict. \(self)")
return tmp
}
let v = root?.popBack()
assert(invariant, "Invariant conflict. \(self)")
return v
}
public subscript(index: Int) -> Element? {
get {
guard index >= 0 else { return nil }
var current = root
for _ in 0..<index { current = current?.next }
assert(invariant, "Invariant conflict. \(self)")
return current?.data
}
set {
guard newValue != nil else { return }
guard root != nil else {
precondition(index == 0, "Index out of bounds. \(index) > 0.")
root = DoublyLinkedItem(data: newValue!)
assert(invariant, "Invariant conflict. \(self)")
return
}
if index == 0 {
root = DoublyLinkedItem(data: newValue!, next: root?.next)
root?.next?.prev = root
assert(invariant, "Invariant conflict. \(self)")
return
}
var current = root
var index = index - 1
while index > 0 {
current = current?.next
precondition(current != nil, "Index out of bounds.")
index -= 1
}
let c = current!
c.next = DoublyLinkedItem(data: newValue!, prev: c, next: c.next?.next)
c.next!.next?.prev = c.next
assert(invariant, "Invariant conflict. \(self)")
}
}
public mutating func insert(_ data: Element, at index: Int) throws {
guard root != nil else {
guard index == 0 else {
throw ListError.indexOutOfRange
}
root = DoublyLinkedItem(data: data)
assert(invariant, "Invariant conflict. \(self)")
return
}
var current = root
var index = index - 1
while index > 0 {
current = current?.next
index -= 1
}
guard current != nil else { throw ListError.indexOutOfRange }
current!.next = DoublyLinkedItem(data: data, prev: current, next: current?.next)
assert(invariant, "Invariant conflict. \(self)")
}
public mutating func remove(at index: Int) throws -> Element {
assert(invariant, "Invariant conflict. \(self)")
guard index >= 0 else { throw ListError.indexOutOfRange }
if index == 0 {
let tmp = root!.data
self.root = root?.next
return tmp
}
var current = root
var index = index - 1
while index > 0 {
current = current?.next
index -= 1
}
guard current != nil else { throw ListError.indexOutOfRange }
let next = current?.next
let tmp = current!.next!.data
current!.next = next?.next
assert(invariant, "Invariant conflict. \(self)")
return tmp
}
internal var root: DoublyLinkedItem<Element>?
public init() { root = nil }
public init(arrayLiteral: Element...) {
self.init()
self.array = arrayLiteral
}
public var array: [Element] {
get {
guard root != nil else { return [] }
return root!.array
}
set {
assert(invariant, "Invariant conflict. \(self)")
guard newValue.count > 0 else { return }
self.root = DoublyLinkedItem(data: newValue.first!)
for e in newValue.dropFirst() {
self.root!.pushBack(e)
}
assert(invariant, "Invariant conflict. \(self)")
}
}
public var description: String {
return "[\(root != nil ? root!.description: "")]"
}
public var count: Int {
if root != nil { return root!.count }
return 0
}
private var invariant: Bool {
var current = root
repeat {
guard current?.next == nil || (current?.next?.prev === current) else { return false }
current = current?.next
} while current != nil
return true
}
}
internal final class DoublyLinkedItem<Element>: ListItem, CustomStringConvertible {
let data: Element
var next: DoublyLinkedItem?
var prev: DoublyLinkedItem?
convenience init(data: Element) {
self.init(data: data, prev: nil, next: nil)
}
init(data: Element, prev: DoublyLinkedItem? = nil, next: DoublyLinkedItem? = nil) {
self.data = data
self.next = next
self.prev = prev
}
func pushBack(_ newData: Element) {
guard let next = next else {
self.next = DoublyLinkedItem(data: newData, prev: self)
return
}
next.pushBack(newData)
}
var description: String {
if next == nil { return "\(data)" }
return "\(data) <-> \(next!)"
}
}
| mit | d8b29f07db4e6c66388b29bde394cc67 | 23.441026 | 88 | 0.62841 | 3.543494 | false | false | false | false |
manuelCarlos/Swift-Playgrounds | Map.playground/Contents.swift | 1 | 8062 |
import UIKit
/*:
## A Dive into `map` and how we got there.
Lets take a look at the signature of map:
- Note: `public func map<T>(@noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]`
Just by Looking at the signature we could say map is a function that takes one paramater (a function or closure ) and returns an array.
The signature can be found in Swift's standard library as part of the SequenceType, CollectionType Protocols and the `Optional` type, meaning that any type that comform to one of those protocols, or a Optional can use map, e.g. Arrays, Sets, Dictionaries which conform to CollectionType.
This explains why something like this is not possible:
*/
// 12.map({ $0 })
/*:
Before we look at how map can be used in practice, lets try to understand the reason why map exists at all and how it got this signature.\
Lets start by pretending `map` doesn't exist and work on some simple tasks with arrays.
- a function that takes an array of Int and adds 1 to each element
*/
func changeI( _ array: [Int] ) -> [Int] {
var result: [Int] = []
for i in array{
result.append(i + 1)
}
return result
}
//using it
let oneMore = changeI([1,2,3,4])
/*:
- a function that takes an array of objects and changes one of its properties
*/
class A { var x: Int = 0 }
let classes = [A(), A(), A()]
func changeA(_ list: [A]) -> [A]{
var result: [A] = []
for a in list{
a.x = a.x + 1
result.append( a )
}
return result
}
let c = changeA(classes)
/*:
Notice how both function iterate through the array in the same way, and only the operation that is done in each element is different? Well, then we could create a more generic function that takes the array and the particular transformation it needs to perform to each element, as arguments\
Lets try that with an array of Int:
*/
func changeX(_ array: [Int], transform: (Int) -> Int ) -> [Int]{
var result: [Int] = []
for a in array{
result.append( transform(a) )
}
return result
}
/*:
Now we supply a closure of type Int -> Int for the transform parameter, something like { a in a + 1} will do:
*/
var plusOne: (Int) -> Int = { a in a + 1}
let x = changeX([1,2,3], transform: plusOne )
x
/*:
This works fine when we want to tranform each element `Int` into another `Int` but what if the transformation we need turns an `Int` into some other type?. We make the function generic to do that. This way we can transform the `Int` into wathever type we need. The `T` in angle brackets is a placeholder for any type:
*/
func changeXG < T > (_ array: [Int], transform: (Int) -> T ) -> [T]{
var result: [T] = []
for a in array{
result.append( transform(a) )
}
return result
}
/*:
Now we supply a closure of, say type Int -> String for the transform parameter like { a in "\(a)"} and get back a very different array from the one we started with. We get an Array of strings:
*/
let stringList = changeXG([1,2,3], transform: {a in "\(a)" })
stringList
/*:
This is great but we are still tied to using arrays of `Int`. We can improve that by adding another generic type `E` in our function declaration that will be a placeholder for the type od elements that the array sufferring the transformation is holding, like so:
*/
func myMap < E , T > (_ array: [E], transform: (E) -> T ) -> [T]{
var result: [T] = []
for a in array{
result.append( transform(a) )
}
return result
}
/*:
Lets see how it works for an array of class objeects.\
We can use a transform closure to create an array holding the values of the x property from each A instance:
*/
let xList = myMap(classes, transform: { a in a.x + 1 } )
xList
/*:
Or we can create an array of the same objects while still transforming its properties:
*/
var f : (A) -> A = { a in a.x = a.x + 1 ; return a } // f is just a helper closure
let newClasses = myMap(classes, transform: { a in f(a) } )
/*:
- Note: Notice that because the `classes` constant holds reference types their instances reflect the changes made in our function.
*/
newClasses // the
classes
/*:
Since `myMap` can now be used with an array of any type why not adding it to `Array` as an extension. Then we can use it on all array instances we create.
Extending `Array` means our function implementation should be changed to be akin to a method. We can drop the first parameter because we have a way to refer it with `self`. Here's how it could look:
*/
extension Array {
public func myMap < T > (_ transform: (Element) -> T ) -> [T]{
var result: [T] = []
for a in self{
result.append( transform(a) )
}
return result
}
}
/*:
`Element` is the default typealias used by `Array` to refer to one of its elements.\
We can use the same approach to add our function to `CollectionType` and make it acessible to arrays, sets, dictionaries:
*/
extension Collection{
public func myMap < T > (_ transform: (Self.Iterator.Element) -> T ) -> [T]{
var result: [T] = []
for a in self{
result.append( transform(a) )
}
return result
}
}
/*:
We ended up with a function with this signature:\
`public func myMap < T > (transform: (Self.Generator.Element) -> T ) -> [T]`\
which is of course the very basic signatue of `map`:
`public func map < T > (@noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]`\
*/
/*:
- Note:
@noescape is an attribute in Swift that are used to communicate to the user of the function that the argument will not outlive the lifetime of the call. If the function dispatches to a different thread, an argument may be captured so that it exist at a later time when its needed. The @noescape attribute is a sign that this will not happen for this function.\
The `throws` keyword in the signature tells that the `transform` function may throw an error. The `rethrows` keyword lets the compiler know that if the closure that is passed to map can't ever throw an error, then the whole function can’t throw either.
----
### Using `Map` with Optionals
*/
/*:
It's interesting that we can easilly compose different map operations that will be executed sequentially. A call to map always returns an `Optional`. Map applies the closure to the content of the optional *only* if the optional has a value, otherwise it just returns nil.
*/
let optionalInt :Int? = 12
let optionalIntMapped = optionalInt.map({$0 * 2})
let composed = optionalIntMapped.map({$0 * 2}).map({ $0 / 2})
/*:
We can use this property to avoid force unwrapping an optional or as quick replacement for `if let` or `guard`.\
Withou map you could write:
*/
let date: Date? = nil
let formatted: String? = date == nil ? nil : DateFormatter().string(from: date!)
/*:
But with map it's simpler:
*/
let formatted2: String? = date.map( DateFormatter().string(from:) )
/*:
----
### Using `Map` on CollectionTypes
- **The typical use case**
*/
let list: [ Int ] = [1,2,4]
let mappedList = list.map({$0 * 2})
/*:
- **Finding the index of an element in an array if it exists**
*/
let items = [10,2,3,4]
func find(_ element: Int) -> Int? {
return items.index(where: { $0 == element }).map({$0})
}
find(2)
/*:
- **Using Lazy Sequences**
*/
// Example Without the use of ```lazy``` keyword
//let array = [Int](1...10)
//let incArray = array.map({ a in print(" -> \(a)"); a + 1 })
/*:
> Looking in the playground debug area, you'll see all 100 prints
*/
// With lazy
/*:
Using ```lazy``` the transform closure is only apply when the values are accessed, and not when the call to map appears, and only apply to the values being accessed, not all the one thousand values of the entire array.
*/
let thousand = [Int](1...1000)
let new = thousand.lazy.map({ a in print(" lazy map - \(a)"); a + 1 })
/*:
> No prints on the debug area until you try acessing the values in ```new```
*/
new[2]
| mit | 677986259d91ad52b20d6af279d6cf9c | 28.962825 | 361 | 0.661911 | 3.683729 | false | false | false | false |
yaobanglin/viossvc | viossvc/Scenes/Chat/CustomView/CustomTextView.swift | 2 | 6639 | //
// CustomTextView.swift
// viossvc
//
// Created by abx’s mac on 2016/12/5.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
class CustomTextView: UITextView {
private var placeHolder : String = ""
private var placeHolderFont : UIFont?
private var getPlaceHolderFont : UIFont {
return (placeHolderFont == nil ? font : placeHolderFont)!
}
private var placeHolderTextColor : UIColor = UIColor.lightGrayColor()
private var isClearPlaceHolder = false
var overrideNextResponder : UIResponder?
override func nextResponder() -> UIResponder? {
if overrideNextResponder != nil{
return overrideNextResponder
}else {
return super.nextResponder()
}
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if overrideNextResponder != nil {
return false
}else {
return super.canPerformAction(action, withSender: sender)
}
}
//#pragma mark - Setters
func setPlaceHolder(placeHolder : String) {
if placeHolder != self.placeHolder {
let maxChars = Int(CustomTextView.maxCharactersPerLine())
var place : NSString = placeHolder
if(placeHolder.length() > maxChars) {
place = place.substringToIndex(maxChars - 8)
place = place.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).stringByAppendingString("...")
}
self.placeHolder = place as String
isClearPlaceHolder = false;
self.setNeedsDisplay();
}
}
func settingFont(textFont fontT : CGFloat, placeHolderFont : CGFloat ) {
self.font = UIFont.systemFontOfSize(fontT)
self.placeHolderFont = UIFont.systemFontOfSize(placeHolderFont)
self.setNeedsDisplay();
}
func settingPlaceHolderTextColor(placeHolderTextColor : UIColor) {
if self.placeHolderTextColor != placeHolderTextColor {
self.placeHolderTextColor = placeHolderTextColor
setNeedsDisplay()
}
}
func settingScrollIndicatorInsets( insets :UIEdgeInsets) {
var insetVar = insets
scrollIndicatorInsets = insetVar
insetVar.left -= 5
textContainerInset = insetVar
setNeedsDisplay()
}
func settingtTextContainerInset(insets :UIEdgeInsets) {
textContainerInset = insets
setNeedsDisplay()
}
//#pragma mark - Message text view
func numberOfLinesOfText() -> UInt {
return CustomTextView.numberOfLinesForMessage(self.text)
}
class func numberOfLinesForMessage(text : String) -> UInt {
return (UInt(text.length()) / CustomTextView.maxCharactersPerLine()) + 1
}
class func maxCharactersPerLine() -> UInt {
return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone ? 33 : 109
}
override var text: String! {
didSet {
setNeedsDisplay()
}
}
override var attributedText: NSAttributedString! {
didSet {
setNeedsDisplay()
}
}
override var contentInset: UIEdgeInsets {
didSet {
setNeedsDisplay()
}
}
override var font: UIFont? {
didSet {
setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet {
setNeedsDisplay()
}
}
//#pragma mark - Notifications
func didReceiveTextDidChangeNotification(notification :NSNotification ) {
setNeedsDisplay()
}
func setup() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CustomTextView.didReceiveTextDidChangeNotification(_:)), name: UITextViewTextDidChangeNotification, object: self)
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
self.layoutManager.allowsNonContiguousLayout = false;
self.scrollEnabled = true;
self.scrollsToTop = false;
// self.scrollIndicatorInsets = UIEdgeInsetsMake(13,10, 13, 10);
self.userInteractionEnabled = true;
self.keyboardAppearance = UIKeyboardAppearance.Default;
self.keyboardType = UIKeyboardType.Default;
// self.textContainerInset = UIEdgeInsetsMake(12, 0, 13, 0); // 调整光标位置 默认是(8 0 8 0) 调小需要微调 不建议输入条这么小
self.textAlignment = NSTextAlignment.Left;
}
// override init(frame: CGRect, textContainer: NSTextContainer?) {
// super.init(frame: frame, textContainer: textContainer)
// setup()
// }
//
// required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidChangeNotification, object: self)
}
func placeHolderTop(y : CGFloat) -> CGFloat {
var height = y + self.scrollIndicatorInsets.top
height += (self.font!.lineHeight - getPlaceHolderFont.lineHeight) / 2.0;
return height
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
if(self.text.length() == 0 && placeHolder.length() != 0) {
rect.origin.y
let placeHolderRect = CGRectMake(self.scrollIndicatorInsets.left,placeHolderTop(rect.origin.y) ,rect.size.width - 2 * self.scrollIndicatorInsets.left,rect.size.height);
placeHolderTextColor.set()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
paragraphStyle.alignment = self.textAlignment;
let string : NSString = self.placeHolder
string.drawInRect(placeHolderRect, withAttributes: [NSFontAttributeName : getPlaceHolderFont, NSForegroundColorAttributeName : placeHolderTextColor ,NSParagraphStyleAttributeName : paragraphStyle])
isClearPlaceHolder = false
}else if (isClearPlaceHolder == false){
isClearPlaceHolder = true
CGContextClearRect(UIGraphicsGetCurrentContext(), CGRectZero);
}
}
}
| apache-2.0 | 4ad49b3f691e6059b81f65252c77b781 | 29.331797 | 209 | 0.62124 | 5.545072 | false | false | false | false |
tardieu/swift | test/attr/attr_inlineable.swift | 1 | 8311 | // RUN: %target-typecheck-verify-swift -swift-version 4
@_inlineable struct TestInlineableStruct {}
// expected-error@-1 {{@_inlineable cannot be applied to this declaration}}
private func privateFunction() {}
// expected-note@-1 5{{global function 'privateFunction()' is not '@_versioned' or public}}
fileprivate func fileprivateFunction() {}
// expected-note@-1 5{{global function 'fileprivateFunction()' is not '@_versioned' or public}}
func internalFunction() {}
// expected-note@-1 5{{global function 'internalFunction()' is not '@_versioned' or public}}
@_versioned func versionedFunction() {}
public func publicFunction() {}
func internalIntFunction() -> Int {}
// expected-note@-1 2{{global function 'internalIntFunction()' is not '@_versioned' or public}}
private struct PrivateStruct {}
// expected-note@-1 3{{struct 'PrivateStruct' is not '@_versioned' or public}}
struct InternalStruct {}
// expected-note@-1 4{{struct 'InternalStruct' is not '@_versioned' or public}}
@_versioned struct VersionedStruct {
@_versioned init() {}
}
public struct PublicStruct {
public init() {}
}
public struct Struct {
@_transparent
public func publicTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a '@_transparent' function}}
fileprivateFunction()
// expected-error@-1 {{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a '@_transparent' function}}
privateFunction()
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a '@_transparent' function}}
}
@_inlineable
public func publicInlineableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@_inlineable' function}}
let _: PublicStruct
let _: VersionedStruct
let _: InternalStruct
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@_inlineable' function}}
let _: PrivateStruct
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@_inlineable' function}}
let _ = PublicStruct.self
let _ = VersionedStruct.self
let _ = InternalStruct.self
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@_inlineable' function}}
let _ = PrivateStruct.self
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@_inlineable' function}}
let _ = PublicStruct()
let _ = VersionedStruct()
let _ = InternalStruct()
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@_inlineable' function}}
let _ = PrivateStruct()
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@_inlineable' function}}
}
@inline(__always)
public func publicInlineAlwaysMethod(x: Any) {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inline(__always)' function}}
switch x {
case is InternalStruct:
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inline(__always)' function}}
_ = ()
}
}
private func privateMethod() {}
// expected-note@-1 {{instance method 'privateMethod()' is not '@_versioned' or public}}
@_transparent
@_versioned
func versionedTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
privateMethod()
// expected-error@-1 {{instance method 'privateMethod()' is private and cannot be referenced from a '@_transparent' function}}
}
@_inlineable
@_versioned
func versionedInlineableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@_inlineable' function}}
}
@inline(__always)
@_versioned
func versionedInlineAlwaysMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inline(__always)' function}}
}
@_transparent
func internalTransparentMethod() {
struct Nested {}
// OK
}
@_inlineable
func internalInlineableMethod() {
struct Nested {}
// OK
}
@inline(__always)
func internalInlineAlwaysMethod() {
struct Nested {}
// OK
}
}
func internalFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// OK
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// OK
fileprivateFunction()
// OK
privateFunction()
// OK
return 0
}(),
y: Int = internalIntFunction()) {}
@_versioned func versionedFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}}
// FIXME: Some errors below are diagnosed twice
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 2{{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
fileprivateFunction()
// expected-error@-1 2{{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a default argument value}}
privateFunction()
// expected-error@-1 2{{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
return 0
}(),
y: Int = internalIntFunction()) {}
// expected-error@-1 {{global function 'internalIntFunction()' is internal and cannot be referenced from a default argument value}}
public func publicFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}}
// FIXME: Some errors below are diagnosed twice
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 2{{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
fileprivateFunction()
// expected-error@-1 2{{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a default argument value}}
privateFunction()
// expected-error@-1 2{{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
return 0
}(),
y: Int = internalIntFunction()) {}
// expected-error@-1 {{global function 'internalIntFunction()' is internal and cannot be referenced from a default argument value}}
// Make sure protocol extension members can reference protocol requirements
// (which do not inherit the @_versioned attribute).
@_versioned
protocol VersionedProtocol {
associatedtype T
func requirement() -> T
}
extension VersionedProtocol {
func internalMethod() {}
// expected-note@-1 {{instance method 'internalMethod()' is not '@_versioned' or public}}
@_inlineable
@_versioned
func versionedMethod() -> T {
internalMethod()
// expected-error@-1 {{instance method 'internalMethod()' is internal and cannot be referenced from an '@_inlineable' function}}
return requirement()
}
}
enum InternalEnum {
// expected-note@-1 2{{enum 'InternalEnum' is not '@_versioned' or public}}
case apple
case orange
}
@_inlineable public func usesInternalEnum() {
_ = InternalEnum.apple
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@_inlineable' function}}
let _: InternalEnum = .orange
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@_inlineable' function}}
}
@_versioned enum VersionedEnum {
case apple
case orange
// FIXME: Should this be banned?
case pear(InternalEnum)
case persimmon(String)
}
@_inlineable public func usesVersionedEnum() {
_ = VersionedEnum.apple
let _: VersionedEnum = .orange
_ = VersionedEnum.persimmon
}
| apache-2.0 | c05c08ce74583b612fc673d36f7da660 | 32.922449 | 141 | 0.684394 | 4.719478 | false | false | false | false |
duliodenis/cs193p-Winter-2017 | assignments/Assignment_1_Calculator/Calculator/Calculator/CalculatorBrain.swift | 1 | 2991 | //
// CalculatorBrain.swift
// Calculator
//
// Created by Dulio Denis on 2/19/17.
// Copyright © 2017 ddApps. All rights reserved.
//
import Foundation
struct CalculatorBrain {
// optional on initialization = not set
private var accumulator: Double?
// private enum specifying operation types
// with an associated value
private enum Operation {
case constant(Double)
case unary((Double) -> Double)
case binary((Double,Double) -> Double)
case equals
}
// private extensible dictionary of operations with closures
private var operations: Dictionary<String,Operation> = [
"π" : Operation.constant(Double.pi),
"e" : Operation.constant(M_E),
"√" : Operation.unary(sqrt),
"cos" : Operation.unary(cos),
"±" : Operation.unary({ -$0 }),
"×" : Operation.binary({ $0 * $1 }),
"÷" : Operation.binary({ $0 / $1 }),
"+" : Operation.binary({ $0 + $1 }),
"−" : Operation.binary({ $0 - $1 }),
"=" : Operation.equals
]
mutating func performOperation(_ symbol: String) {
if let operation = operations[symbol] {
switch operation {
case .constant(let value):
accumulator = value
case .unary(let f):
if accumulator != nil {
accumulator = f(accumulator!)
}
case .binary(let f):
if accumulator != nil {
pendingBinaryOperation = PendingBinaryOperation(function: f, firstOperand: accumulator!)
accumulator = nil
}
case .equals:
performPendingBinaryOperation()
}
}
}
// Private mutating func for performing pending binary operations
mutating func performPendingBinaryOperation() {
if pendingBinaryOperation != nil && accumulator != nil {
accumulator = pendingBinaryOperation!.perform(with: accumulator!)
pendingBinaryOperation = nil
}
}
// Private optional Pending Binary Operation
private var pendingBinaryOperation: PendingBinaryOperation?
// embedded private struct to support binary operations
// with a constant function and pending first operand
// doesn't need mutating since its just returning a value
private struct PendingBinaryOperation {
let function: (Double, Double) -> Double
let firstOperand: Double
func perform(with secondOperand: Double) -> Double {
return function(firstOperand, secondOperand)
}
}
// mark method as mutating in order to assign to property
mutating func setOperand(_ operand: Double) {
accumulator = operand
}
// return an optional since the accumulator can be not set
var result: Double? {
get {
return accumulator
}
}
}
| mit | 4b49532544f793308244028ed0e97b78 | 30.723404 | 108 | 0.581489 | 5.150259 | false | false | false | false |
johndpope/ClangWrapper.Swift | ClangWrapper/TokenKind.swift | 1 | 1413 | //
// TokenKind.swift
// ClangWrapper
//
// Created by Hoon H. on 2015/01/21.
// Copyright (c) 2015 Eonil. All rights reserved.
//
/**
* \brief Describes a kind of token.
*/
public enum TokenKind: UInt32 {
/**
* \brief A token that contains some kind of punctuation.
*/
case Punctuation
/**
* \brief A language keyword.
*/
case Keyword
/**
* \brief An identifier (that is not a keyword).
*/
case Identifier
/**
* \brief A numeric, string, or character literal.
*/
case Literal
/**
* \brief A comment.
*/
case Comment
}
extension TokenKind {
static func fromRaw(raw r:CXTokenKind) -> TokenKind {
return self(raw: r)
}
/// Doesn't work well in Swift 1.2.
/// Use `fromRaw` instead of.
init(raw: CXTokenKind) {
switch raw.value {
case CXToken_Punctuation.value:
self = Punctuation
case CXToken_Keyword.value:
self = Keyword
case CXToken_Identifier.value:
self = Identifier
case CXToken_Literal.value:
self = Literal
case CXToken_Comment.value:
self = Comment
default:
fatalError("Unknown token-kind constant value: \(raw.value)")
}
}
var raw:CXTokenKind {
get {
switch self {
case .Punctuation:
return CXToken_Punctuation
case .Keyword:
return CXToken_Keyword
case .Identifier:
return CXToken_Identifier
case .Literal:
return CXToken_Literal
case .Comment:
return CXToken_Comment
}
}
}
}
| mit | 9b8bc9375a3cb8806a117559037c5d2c | 16.444444 | 64 | 0.65959 | 3.03871 | false | false | false | false |
milseman/swift | stdlib/private/StdlibUnittest/RaceTest.swift | 7 | 20553 | //===--- RaceTest.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This file implements support for race tests.
///
/// Race test harness executes the given operation in multiple threads over a
/// set of shared data, trying to ensure that executions overlap in time.
///
/// The name "race test" does not imply that the race actually happens in the
/// harness or in the operation being tested. The harness contains all the
/// necessary synchronization for its own data, and for publishing test data to
/// threads. But if the operation under test is, in fact, racy, it should be
/// easier to discover the bug in this environment.
///
/// Every execution of a race test is called a trial. During a single trial
/// the operation under test is executed multiple times in each thread over
/// different data items (`RaceData` instances). Different threads process
/// data in different order. Choosing an appropriate balance between the
/// number of threads and data items, the harness uses the birthday paradox to
/// increase the probability of "collisions" between threads.
///
/// After performing the operation under test, the thread should observe the
/// data in a test-dependent way to detect if presence of other concurrent
/// actions disturbed the result. The observation should be as short as
/// possible, and the results should be returned as `Observation`. Evaluation
/// (cross-checking) of observations is deferred until the end of the trial.
///
//===----------------------------------------------------------------------===//
import SwiftPrivate
import SwiftPrivateLibcExtras
import SwiftPrivatePthreadExtras
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
import Glibc
#endif
#if _runtime(_ObjC)
import ObjectiveC
#else
func autoreleasepool(invoking code: () -> Void) {
// Native runtime does not have autorelease pools. Execute the code
// directly.
code()
}
#endif
/// Race tests that need a fresh set of data for every trial should implement
/// this protocol.
///
/// All racing threads execute the same operation, `thread1`.
///
/// Types conforming to this protocol should be structs. (The type
/// should be a struct to reduce unnecessary reference counting during
/// the test.) The types should be stateless.
public protocol RaceTestWithPerTrialData {
/// Input for threads.
///
/// This type should be a class. (The harness will not pass struct instances
/// between threads correctly.)
associatedtype RaceData : AnyObject
/// Type of thread-local data.
///
/// Thread-local data is newly created for every trial.
associatedtype ThreadLocalData
/// Results of the observation made after performing an operation.
associatedtype Observation
init()
/// Creates a fresh instance of `RaceData`.
func makeRaceData() -> RaceData
/// Creates a fresh instance of `ThreadLocalData`.
func makeThreadLocalData() -> ThreadLocalData
/// Performs the operation under test and makes an observation.
func thread1(
_ raceData: RaceData, _ threadLocalData: inout ThreadLocalData) -> Observation
/// Evaluates the observations made by all threads for a particular instance
/// of `RaceData`.
func evaluateObservations(
_ observations: [Observation],
_ sink: (RaceTestObservationEvaluation) -> Void)
}
/// The result of evaluating observations.
///
/// Case payloads can carry test-specific data. Results will be grouped
/// according to it.
public enum RaceTestObservationEvaluation : Equatable, CustomStringConvertible {
/// Normal 'pass'.
case pass
/// An unusual 'pass'.
case passInteresting(String)
/// A failure.
case failure
case failureInteresting(String)
public var description: String {
switch self {
case .pass:
return "Pass"
case .passInteresting(let s):
return "Pass(\(s))"
case .failure:
return "Failure"
case .failureInteresting(let s):
return "Failure(\(s))"
}
}
}
public func == (
lhs: RaceTestObservationEvaluation, rhs: RaceTestObservationEvaluation
) -> Bool {
switch (lhs, rhs) {
case (.pass, .pass),
(.failure, .failure):
return true
case (.passInteresting(let s1), .passInteresting(let s2)):
return s1 == s2
default:
return false
}
}
/// An observation result that consists of one `UInt`.
public struct Observation1UInt : Equatable, CustomStringConvertible {
public var data1: UInt
public init(_ data1: UInt) {
self.data1 = data1
}
public var description: String {
return "(\(data1))"
}
}
public func == (lhs: Observation1UInt, rhs: Observation1UInt) -> Bool {
return lhs.data1 == rhs.data1
}
/// An observation result that consists of four `UInt`s.
public struct Observation4UInt : Equatable, CustomStringConvertible {
public var data1: UInt
public var data2: UInt
public var data3: UInt
public var data4: UInt
public init(_ data1: UInt, _ data2: UInt, _ data3: UInt, _ data4: UInt) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4))"
}
}
public func == (lhs: Observation4UInt, rhs: Observation4UInt) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4
}
/// An observation result that consists of three `Int`s.
public struct Observation3Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public init(_ data1: Int, _ data2: Int, _ data3: Int) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
}
public var description: String {
return "(\(data1), \(data2), \(data3))"
}
}
public func == (lhs: Observation3Int, rhs: Observation3Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3
}
/// An observation result that consists of four `Int`s.
public struct Observation4Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public var data4: Int
public init(_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4))"
}
}
public func == (lhs: Observation4Int, rhs: Observation4Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4
}
/// An observation result that consists of five `Int`s.
public struct Observation5Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public var data4: Int
public var data5: Int
public init(
_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int, _ data5: Int
) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
self.data5 = data5
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4), \(data5))"
}
}
public func == (lhs: Observation5Int, rhs: Observation5Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4 &&
lhs.data5 == rhs.data5
}
/// An observation result that consists of nine `Int`s.
public struct Observation9Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public var data4: Int
public var data5: Int
public var data6: Int
public var data7: Int
public var data8: Int
public var data9: Int
public init(
_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int,
_ data5: Int, _ data6: Int, _ data7: Int, _ data8: Int,
_ data9: Int
) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
self.data5 = data5
self.data6 = data6
self.data7 = data7
self.data8 = data8
self.data9 = data9
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4), \(data5), \(data6), \(data7), \(data8), \(data9))"
}
}
public func == (lhs: Observation9Int, rhs: Observation9Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4 &&
lhs.data5 == rhs.data5 &&
lhs.data6 == rhs.data6 &&
lhs.data7 == rhs.data7 &&
lhs.data8 == rhs.data8 &&
lhs.data9 == rhs.data9
}
/// A helper that is useful to implement
/// `RaceTestWithPerTrialData.evaluateObservations()` in race tests.
public func evaluateObservationsAllEqual<T : Equatable>(_ observations: [T])
-> RaceTestObservationEvaluation {
let first = observations.first!
for x in observations {
if x != first {
return .failure
}
}
return .pass
}
struct _RaceTestAggregatedEvaluations : CustomStringConvertible {
var passCount: Int = 0
var passInterestingCount = [String: Int]()
var failureCount: Int = 0
var failureInterestingCount = [String: Int]()
init() {}
mutating func addEvaluation(_ evaluation: RaceTestObservationEvaluation) {
switch evaluation {
case .pass:
passCount += 1
case .passInteresting(let s):
if passInterestingCount[s] == nil {
passInterestingCount[s] = 0
}
passInterestingCount[s] = passInterestingCount[s]! + 1
case .failure:
failureCount += 1
case .failureInteresting(let s):
if failureInterestingCount[s] == nil {
failureInterestingCount[s] = 0
}
failureInterestingCount[s] = failureInterestingCount[s]! + 1
}
}
var isFailed: Bool {
return failureCount != 0 || !failureInterestingCount.isEmpty
}
var description: String {
var result = ""
result += "Pass: \(passCount) times\n"
for desc in passInterestingCount.keys.sorted() {
let count = passInterestingCount[desc]!
result += "Pass \(desc): \(count) times\n"
}
result += "Failure: \(failureCount) times\n"
for desc in failureInterestingCount.keys.sorted() {
let count = failureInterestingCount[desc]!
result += "Failure \(desc): \(count) times\n"
}
return result
}
}
// FIXME: protect this class against false sharing.
class _RaceTestWorkerState<RT : RaceTestWithPerTrialData> {
// FIXME: protect every element of 'raceData' against false sharing.
var raceData: [RT.RaceData] = []
var raceDataShuffle: [Int] = []
var observations: [RT.Observation] = []
}
class _RaceTestSharedState<RT : RaceTestWithPerTrialData> {
var racingThreadCount: Int
var stopNow = _stdlib_AtomicInt(0)
var trialBarrier: _stdlib_Barrier
var trialSpinBarrier: _stdlib_AtomicInt = _stdlib_AtomicInt()
var raceData: [RT.RaceData] = []
var workerStates: [_RaceTestWorkerState<RT>] = []
var aggregatedEvaluations: _RaceTestAggregatedEvaluations =
_RaceTestAggregatedEvaluations()
init(racingThreadCount: Int) {
self.racingThreadCount = racingThreadCount
self.trialBarrier = _stdlib_Barrier(threadCount: racingThreadCount + 1)
self.workerStates.reserveCapacity(racingThreadCount)
for _ in 0..<racingThreadCount {
self.workerStates.append(_RaceTestWorkerState<RT>())
}
}
}
func _masterThreadStopWorkers<RT>( _ sharedState: _RaceTestSharedState<RT>) {
// Workers are proceeding to the first barrier in _workerThreadOneTrial.
sharedState.stopNow.store(1)
// Allow workers to proceed past that first barrier. They will then see
// stopNow==true and stop.
sharedState.trialBarrier.wait()
}
func _masterThreadOneTrial<RT>(_ sharedState: _RaceTestSharedState<RT>) {
let racingThreadCount = sharedState.racingThreadCount
let raceDataCount = racingThreadCount * racingThreadCount
let rt = RT()
sharedState.raceData.removeAll(keepingCapacity: true)
sharedState.raceData.append(contentsOf: (0..<raceDataCount).lazy.map { _ in
rt.makeRaceData()
})
let identityShuffle = Array(0..<sharedState.raceData.count)
sharedState.workerStates.removeAll(keepingCapacity: true)
sharedState.workerStates.append(contentsOf: (0..<racingThreadCount).lazy.map {
_ in
let workerState = _RaceTestWorkerState<RT>()
// Shuffle the data so that threads process it in different order.
let shuffle = randomShuffle(identityShuffle)
workerState.raceData = scatter(sharedState.raceData, shuffle)
workerState.raceDataShuffle = shuffle
workerState.observations = []
workerState.observations.reserveCapacity(sharedState.raceData.count)
return workerState
})
sharedState.trialSpinBarrier.store(0)
sharedState.trialBarrier.wait()
// Race happens.
sharedState.trialBarrier.wait()
// Collect and compare results.
for i in 0..<racingThreadCount {
let shuffle = sharedState.workerStates[i].raceDataShuffle
sharedState.workerStates[i].raceData =
gather(sharedState.workerStates[i].raceData, shuffle)
sharedState.workerStates[i].observations =
gather(sharedState.workerStates[i].observations, shuffle)
}
if true {
// FIXME: why doesn't the bracket syntax work?
// <rdar://problem/18305718> Array sugar syntax does not work when used
// with associated types
var observations: [RT.Observation] = []
observations.reserveCapacity(racingThreadCount)
for i in 0..<raceDataCount {
for j in 0..<racingThreadCount {
observations.append(sharedState.workerStates[j].observations[i])
}
let sink = { sharedState.aggregatedEvaluations.addEvaluation($0) }
rt.evaluateObservations(observations, sink)
observations.removeAll(keepingCapacity: true)
}
}
}
func _workerThreadOneTrial<RT>(
_ tid: Int, _ sharedState: _RaceTestSharedState<RT>
) -> Bool {
sharedState.trialBarrier.wait()
if sharedState.stopNow.load() == 1 {
return true
}
let racingThreadCount = sharedState.racingThreadCount
let workerState = sharedState.workerStates[tid]
let rt = RT()
var threadLocalData = rt.makeThreadLocalData()
do {
let trialSpinBarrier = sharedState.trialSpinBarrier
_ = trialSpinBarrier.fetchAndAdd(1)
while trialSpinBarrier.load() < racingThreadCount {}
}
// Perform racy operations.
// Warning: do not add any synchronization in this loop, including
// any implicit reference counting of shared data.
for raceData in workerState.raceData {
workerState.observations.append(rt.thread1(raceData, &threadLocalData))
}
sharedState.trialBarrier.wait()
return false
}
/// One-shot sleep in one thread, allowing interrupt by another.
class _InterruptibleSleep {
let writeEnd: CInt
let readEnd: CInt
var completed = false
init() {
(readEnd: readEnd, writeEnd: writeEnd, _) = _stdlib_pipe()
}
deinit {
close(readEnd)
close(writeEnd)
}
/// Sleep for durationInSeconds or until another
/// thread calls wake(), whichever comes first.
func sleep(durationInSeconds duration: Int) {
if completed {
return
}
var timeout = timeval(tv_sec: duration, tv_usec: 0)
var readFDs = _stdlib_fd_set()
var writeFDs = _stdlib_fd_set()
var errorFDs = _stdlib_fd_set()
readFDs.set(readEnd)
let ret = _stdlib_select(&readFDs, &writeFDs, &errorFDs, &timeout)
precondition(ret >= 0)
completed = true
}
/// Wake the thread in sleep().
func wake() {
if completed { return }
let buffer: [UInt8] = [1]
let ret = write(writeEnd, buffer, 1)
precondition(ret >= 0)
}
}
public func runRaceTest<RT : RaceTestWithPerTrialData>(
_: RT.Type,
trials: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil
) {
let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency())
let sharedState = _RaceTestSharedState<RT>(racingThreadCount: racingThreadCount)
// Alarm thread sets timeoutReached.
// Master thread sees timeoutReached and tells worker threads to stop.
let timeoutReached = _stdlib_AtomicInt(0)
let alarmTimer = _InterruptibleSleep()
let masterThreadBody = {
() -> Void in
for t in 0..<trials {
// Check for timeout.
// _masterThreadStopWorkers must run BEFORE the last _masterThreadOneTrial
// to make the thread coordination barriers work
// but we do want to run at least one trial even if the timeout occurs.
if timeoutReached.load() == 1 && t > 0 {
_masterThreadStopWorkers(sharedState)
break
}
autoreleasepool {
_masterThreadOneTrial(sharedState)
}
}
}
let racingThreadBody = {
(tid: Int) -> Void in
for _ in 0..<trials {
let stopNow = _workerThreadOneTrial(tid, sharedState)
if stopNow { break }
}
}
let alarmThreadBody = {
() -> Void in
guard let timeoutInSeconds = timeoutInSeconds
else { return }
alarmTimer.sleep(durationInSeconds: timeoutInSeconds)
_ = timeoutReached.fetchAndAdd(1)
}
var testTids = [pthread_t]()
var alarmTid: pthread_t
// Create the master thread.
do {
let (ret, tid) = _stdlib_pthread_create_block(
nil, masterThreadBody, ())
expectEqual(0, ret)
testTids.append(tid!)
}
// Create racing threads.
for i in 0..<racingThreadCount {
let (ret, tid) = _stdlib_pthread_create_block(
nil, racingThreadBody, i)
expectEqual(0, ret)
testTids.append(tid!)
}
// Create the alarm thread that enforces the timeout.
do {
let (ret, tid) = _stdlib_pthread_create_block(
nil, alarmThreadBody, ())
expectEqual(0, ret)
alarmTid = tid!
}
// Join all testing threads.
for tid in testTids {
let (ret, _) = _stdlib_pthread_join(tid, Void.self)
expectEqual(0, ret)
}
// Tell the alarm thread to stop if it hasn't already, then join it.
do {
alarmTimer.wake()
let (ret, _) = _stdlib_pthread_join(alarmTid, Void.self)
expectEqual(0, ret)
}
let aggregatedEvaluations = sharedState.aggregatedEvaluations
expectFalse(aggregatedEvaluations.isFailed)
print(aggregatedEvaluations)
}
internal func _divideRoundUp(_ lhs: Int, _ rhs: Int) -> Int {
return (lhs + rhs) / rhs
}
public func runRaceTest<RT : RaceTestWithPerTrialData>(
_ test: RT.Type,
operations: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil
) {
let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency())
// Each trial runs threads^2 operations.
let operationsPerTrial = racingThreadCount * racingThreadCount
let trials = _divideRoundUp(operations, operationsPerTrial)
runRaceTest(test, trials: trials, timeoutInSeconds: timeoutInSeconds,
threads: threads)
}
public func consumeCPU(units amountOfWork: Int) {
for _ in 0..<amountOfWork {
let scale = 16
for _ in 0..<scale {
_blackHole(42)
}
}
}
internal struct ClosureBasedRaceTest : RaceTestWithPerTrialData {
static var thread: () -> Void = {}
class RaceData {}
typealias ThreadLocalData = Void
typealias Observation = Void
func makeRaceData() -> RaceData { return RaceData() }
func makeThreadLocalData() -> Void { return Void() }
func thread1(
_ raceData: RaceData, _ threadLocalData: inout ThreadLocalData
) {
ClosureBasedRaceTest.thread()
}
func evaluateObservations(
_ observations: [Observation],
_ sink: (RaceTestObservationEvaluation) -> Void
) {}
}
public func runRaceTest(
trials: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil,
invoking body: @escaping () -> Void
) {
ClosureBasedRaceTest.thread = body
runRaceTest(ClosureBasedRaceTest.self, trials: trials,
timeoutInSeconds: timeoutInSeconds, threads: threads)
}
public func runRaceTest(
operations: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil,
invoking body: @escaping () -> Void
) {
ClosureBasedRaceTest.thread = body
runRaceTest(ClosureBasedRaceTest.self, operations: operations,
timeoutInSeconds: timeoutInSeconds, threads: threads)
}
| apache-2.0 | 6076b762ea9c611502936b263434d7de | 27.585535 | 103 | 0.67956 | 4.170657 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Metadata/Sources/MetadataKit/Models/HDWallet/DerivationComponent.swift | 1 | 1902 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import MetadataHDWalletKit
extension CharacterSet {
fileprivate static var integers: CharacterSet {
CharacterSet(charactersIn: "0123456789")
}
}
public enum DerivationComponent {
case hardened(UInt32)
case normal(UInt32)
public var description: String {
switch self {
case .normal(let index):
return "\(index)"
case .hardened(let index):
return "\(index)'"
}
}
public var isHardened: Bool {
switch self {
case .normal:
return false
case .hardened:
return true
}
}
var derivationNode: DerivationNode {
switch self {
case .normal(let value):
return .notHardened(value)
case .hardened(let value):
return .hardened(value)
}
}
init?(item: String) {
let hardened = item.hasSuffix("'")
let indexString = item.trimmingCharacters(in: CharacterSet.integers.inverted)
guard let index = UInt32(indexString) else {
return nil
}
guard hardened else {
self = .normal(index)
return
}
self = .hardened(index)
}
func from(_ component: MetadataHDWalletKit.DerivationNode) -> Self {
switch component {
case .hardened(let index):
return .hardened(index)
case .notHardened(let index):
return .normal(index)
}
}
}
extension Array where Element == DerivationComponent {
public func with(normal index: UInt32) -> Self {
self + [.normal(index)]
}
public func with(hardened index: UInt32) -> Self {
self + [.hardened(index)]
}
public var path: String {
"m/" + map(\.description).joined(separator: "/")
}
}
| lgpl-3.0 | 6a0daeb686c5e8df5d66b42cc043853d | 22.7625 | 85 | 0.571804 | 4.49409 | false | false | false | false |
laonawuli/life | Life WatchKit Extension/InterfaceController.swift | 1 | 2101 | //
// InterfaceController.swift
// Life WatchKit Extension
//
// Created by Xu ZHANG on 4/23/15.
// Copyright (c) 2015 Xu ZHANG. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet weak var labelTime: WKInterfaceLabel!
@IBOutlet weak var sliderStep: WKInterfaceSlider!
var time: Int!
var timer: NSTimer!
var isReverse: Bool = false
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
initTimers()
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
invalidateTimer()
super.didDeactivate()
}
private func initTimers() {
let birthDayComponents = NSDateComponents()
birthDayComponents.year = 1987
birthDayComponents.month = 7
birthDayComponents.day = 23
let birthDay = NSCalendar.currentCalendar().dateFromComponents(birthDayComponents)
let now = NSDate()
time = Int(NSDate.timeIntervalSinceDate(now)(birthDay!))
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("fire"), userInfo: nil, repeats: true)
timer.fire()
}
private func invalidateTimer() {
timer.invalidate()
}
func fire() {
time = time + 1
let remain = time % 10
if (isReverse) {
sliderStep.setValue(Float(9 - remain))
} else {
sliderStep.setValue(Float(remain))
}
if (remain == 9) {
isReverse = !isReverse
}
labelTime.setText("\(time)")
}
@IBAction func buttonRebootClicked() {
time = 0
}
@IBAction func buttonShutdownClicked() {
timer.invalidate()
}
}
| mit | 40c92cfec3b04b32315c09000bd916d3 | 24.938272 | 129 | 0.611138 | 4.966903 | false | false | false | false |
ReactiveKit/ReactiveAPI | Sources/HTTPMethod.swift | 1 | 1315 | //
// The MIT License (MIT)
//
// Copyright (c) 2017 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 enum HTTPMethod: String {
case get = "GET"
case put = "PUT"
case post = "POST"
case delete = "DELETE"
case head = "HEAD"
}
| mit | c5a2bb1c93a0f275c70daa055f78558f | 41.419355 | 81 | 0.731559 | 4.148265 | false | false | false | false |
austinzheng/swift | test/SILOptimizer/access_enforcement_selection.swift | 26 | 4307 | // RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -parse-as-library %s -Xllvm -debug-only=access-enforcement-selection 2>&1 | %FileCheck %s
// REQUIRES: asserts
// This is a source-level test because it helps bring up the entire -Onone pipeline with the access markers.
public func takesInout(_ i: inout Int) {
i = 42
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection10takesInoutyySizF
// CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
// Helper taking a basic, no-escape closure.
func takeClosure(_: ()->Int) {}
// Helper taking an escaping closure.
func takeClosureAndInout(_: inout Int, _: @escaping ()->Int) {}
// Helper taking an escaping closure.
func takeEscapingClosure(_: @escaping ()->Int) {}
// Generate an alloc_stack that escapes into a closure.
public func captureStack() -> Int {
// Use a `var` so `x` isn't treated as a literal.
var x = 3
takeClosure { return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection12captureStackSiyF
// Dynamic access for `return x`. Since the closure is non-escaping, using
// dynamic enforcement here is more conservative than it needs to be -- static
// is sufficient here.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection12captureStackSiyFSiyXEfU_
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// Generate an alloc_stack that does not escape into a closure.
public func nocaptureStack() -> Int {
var x = 3
takeClosure { return 5 }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14nocaptureStackSiyF
// Static access for `return x`.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
//
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14nocaptureStackSiyFSiyXEfU_
// Generate an alloc_stack that escapes into a closure while an access is
// in progress.
public func captureStackWithInoutInProgress() -> Int {
// Use a `var` so `x` isn't treated as a literal.
var x = 3
takeClosureAndInout(&x) { return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection31captureStackWithInoutInProgressSiyF
// Access for `return x`.
// CHECK-DAG: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
// Access for `&x`.
// CHECK-DAG: Dynamic Access: %{{.*}} = begin_access [modify] [dynamic] %{{.*}} : $*Int
//
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection31captureStackWithInoutInProgressSiyF
// CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
// Generate an alloc_box that escapes into a closure.
// FIXME: `x` is eventually promoted to an alloc_stack even though it has dynamic enforcement.
// We should ensure that alloc_stack variables are statically enforced.
public func captureBox() -> Int {
var x = 3
takeEscapingClosure { x = 4; return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection10captureBoxSiyF
// Dynamic access for `return x`.
// CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
// CHECK-LABEL: $s28access_enforcement_selection10captureBoxSiyFSiycfU_
// Generate a closure in which the @inout_aliasing argument
// escapes to an @inout function `bar`.
public func recaptureStack() -> Int {
var x = 3
takeClosure { takesInout(&x); return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14recaptureStackSiyF
//
// Static access for `return x`.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14recaptureStackSiyFSiyXEfU_
//
// The first [modify] access inside the closure is static. It enforces the
// @inout argument.
// CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
//
// The second [read] access is static. Same as `captureStack` above.
//
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
| apache-2.0 | dc49541c7ce471e9252d5113f7cb751d | 42.07 | 166 | 0.703506 | 3.774759 | false | false | false | false |
lorentey/swift | test/PrintAsObjC/mixed-framework-fwd.swift | 32 | 2017 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module %s -typecheck -emit-objc-header-path %t/mixed.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=NO-IMPORT %s < %t/mixed.h
// RUN: %check-in-clang -F %S/Inputs/ %t/mixed.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -typecheck -emit-objc-header-path %t/mixed-header.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=NO-IMPORT %s < %t/mixed-header.h
// RUN: %check-in-clang -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t/mixed-header.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module %s -typecheck -emit-objc-header-path %t/mixed-proto.h -DREQUIRE
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=FRAMEWORK %s < %t/mixed-proto.h
// RUN: %check-in-clang -F %S/Inputs/ %t/mixed-proto.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -typecheck -emit-objc-header-path %t/mixed-header-proto.h -DREQUIRE
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=HEADER %s < %t/mixed-header-proto.h
// RUN: %check-in-clang -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t/mixed-header-proto.h
// REQUIRES: objc_interop
// CHECK-LABEL: #if __has_feature(modules)
// CHECK-NEXT: #if __has_warning
// CHECK-NEXT: #pragma clang diagnostic
// CHECK-NEXT: #endif
// CHECK-NEXT: @import Foundation;
// CHECK-NEXT: #endif
// NO-IMPORT-NOT: #import
// NO-IMPORT: @protocol CustomProto;
// FRAMEWORK-LABEL: #import <Mixed/Mixed.h>
// HEADER-NOT: __ObjC
// HEADER: #import "{{.*}}Mixed.h"
// HEADER-NOT: __ObjC
import Foundation
public class Dummy: NSNumber {
@objc public func getProto() -> CustomProto? {
return nil
}
}
#if REQUIRE
extension Dummy: CustomProto {}
#endif
| apache-2.0 | 681756727dc802498b3b82f883b50829 | 43.822222 | 213 | 0.712444 | 2.889685 | false | false | false | false |
voyages-sncf-technologies/Collor | Example/Collor/Alphabet/AlphabetCollectionData.swift | 1 | 1523 | //
// AlphabetCollectionData.swift
// Collor
//
// Created by Guihal Gwenn on 29/01/2019.
//Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import Collor
final class AlphabetCollectionData : CollectionData {
let model = AlphabetModel()
override func reloadData() {
super.reloadData()
model.values.forEach { letter in
let section = AlphabetSectionDescriptorSectionDescriptor().uid(letter.key).reload { builder in
letter.countries.forEach { country in
let cell = AlphabetDescriptor(adapter: AlphabetAdapter(country: country)).uid(country)
builder.cells.append(cell)
}
// supplementaryView
let letterAdapter = LetterAdapter(letter: letter.key)
let letterDescriptor = LetterCollectionReusableViewDescriptor(adapter: letterAdapter)
builder.add(supplementaryView: letterDescriptor, kind: "letter")
}
sections.append(section)
}
}
func add() -> UpdateCollectionResult {
model.add()
return diff()
}
func shake() -> UpdateCollectionResult {
model.shake()
return diff()
}
func reset() -> UpdateCollectionResult {
model.reset()
return diff()
}
func diff() -> UpdateCollectionResult {
return update { (updater) in
updater.diff()
}
}
}
| bsd-3-clause | c243733c505962125f90a5571ce20667 | 26.178571 | 106 | 0.582129 | 5.159322 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/SideMenu/SideMenuCoordinator.swift | 1 | 23976 | // File created from ScreenTemplate
// $ createScreen.sh SideMenu SideMenu
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
import SideMenu
import SafariServices
class SideMenuCoordinatorParameters {
let appNavigator: AppNavigatorProtocol
let userSessionsService: UserSessionsService
let appInfo: AppInfo
init(appNavigator: AppNavigatorProtocol,
userSessionsService: UserSessionsService,
appInfo: AppInfo) {
self.appNavigator = appNavigator
self.userSessionsService = userSessionsService
self.appInfo = appInfo
}
}
final class SideMenuCoordinator: NSObject, SideMenuCoordinatorType {
// MARK: - Constants
private enum SideMenu {
static let widthRatio: CGFloat = 0.82
static let maxWidthiPad: CGFloat = 320.0
}
// MARK: - Properties
// MARK: Private
private let parameters: SideMenuCoordinatorParameters
private var sideMenuViewModel: SideMenuViewModelType
private weak var spaceListCoordinator: SpaceListCoordinatorType?
private lazy var sideMenuNavigationViewController: SideMenuNavigationController = {
return self.createSideMenuNavigationController(with: self.sideMenuViewController)
}()
private let sideMenuViewController: SideMenuViewController
let spaceMenuPresenter = SpaceMenuPresenter()
let spaceDetailPresenter = SpaceDetailPresenter()
private var exploreRoomCoordinator: ExploreRoomCoordinator?
private var membersCoordinator: SpaceMembersCoordinator?
private var createSpaceCoordinator: SpaceCreationCoordinator?
private var createRoomCoordinator: CreateRoomCoordinator?
private var spaceSettingsCoordinator: Coordinator?
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: SideMenuCoordinatorDelegate?
// MARK: - Setup
init(parameters: SideMenuCoordinatorParameters) {
self.parameters = parameters
let sideMenuViewModel = SideMenuViewModel(userSessionsService: self.parameters.userSessionsService, appInfo: parameters.appInfo)
self.sideMenuViewController = SideMenuViewController.instantiate(with: sideMenuViewModel)
self.sideMenuViewModel = sideMenuViewModel
}
// MARK: - Public methods
func start() {
self.sideMenuViewModel.coordinatorDelegate = self
self.sideMenuNavigationViewController.sideMenuDelegate = self
self.sideMenuNavigationViewController.dismissOnRotation = false
// Set the sideMenuNavigationViewController as default left menu
SideMenuManager.default.leftMenuNavigationController = self.sideMenuNavigationViewController
self.addSpaceListIfNeeded()
self.registerUserSessionsServiceNotifications()
}
func toPresentable() -> UIViewController {
return self.sideMenuNavigationViewController
}
@discardableResult func addScreenEdgePanGesturesToPresent(to view: UIView) -> UIScreenEdgePanGestureRecognizer {
return self.sideMenuNavigationViewController.sideMenuManager.addScreenEdgePanGesturesToPresent(toView: view, forMenu: .left)
}
@discardableResult func addPanGestureToPresent(to view: UIView) -> UIPanGestureRecognizer {
return self.sideMenuNavigationViewController.sideMenuManager.addPanGestureToPresent(toView: view)
}
func select(spaceWithId spaceId: String) {
self.spaceListCoordinator?.select(spaceWithId: spaceId)
}
// MARK: - Private
private func createSideMenuNavigationController(with rootViewController: UIViewController) -> SideMenuNavigationController {
var sideMenuSettings = SideMenuSettings()
sideMenuSettings.presentationStyle = .viewSlideOut
sideMenuSettings.menuWidth = self.getMenuWidth()
let navigationController = SideMenuNavigationController(rootViewController: rootViewController, settings: sideMenuSettings)
// FIX: SideMenuSettings are not taken into account at init apply them again
navigationController.settings = sideMenuSettings
return navigationController
}
private func getMenuWidth() -> CGFloat {
let appScreenRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds
let minimumSize = min(appScreenRect.width, appScreenRect.height)
let menuWidth: CGFloat
if UIDevice.current.isPhone {
menuWidth = round(minimumSize * SideMenu.widthRatio)
} else {
// Set a max menu width on iPad
menuWidth = min(round(minimumSize * SideMenu.widthRatio), SideMenu.maxWidthiPad * SideMenu.widthRatio)
}
return menuWidth
}
private func addSpaceListIfNeeded() {
guard self.spaceListCoordinator == nil else {
return
}
guard let mainMatrixSession = self.parameters.userSessionsService.mainUserSession?.matrixSession else {
return
}
self.addSpaceList(with: mainMatrixSession)
}
private func addSpaceList(with matrixSession: MXSession) {
let parameters = SpaceListCoordinatorParameters(userSessionsService: self.parameters.userSessionsService)
let spaceListCoordinator = SpaceListCoordinator(parameters: parameters)
spaceListCoordinator.delegate = self
spaceListCoordinator.start()
let spaceListPresentable = spaceListCoordinator.toPresentable()
// sideMenuViewController.spaceListContainerView can be nil, load controller view to avoid this case
self.sideMenuViewController.loadViewIfNeeded()
self.sideMenuViewController.vc_addChildViewController(viewController: spaceListPresentable, onView: self.sideMenuViewController.spaceListContainerView)
self.add(childCoordinator: spaceListCoordinator)
self.spaceListCoordinator = spaceListCoordinator
}
private func createSettingsViewController() -> SettingsViewController {
let viewController: SettingsViewController = SettingsViewController.instantiate()
viewController.loadViewIfNeeded()
return viewController
}
private func showSettings() {
let viewController = self.createSettingsViewController()
// Push view controller and dismiss side menu
self.sideMenuNavigationViewController.pushViewController(viewController, animated: true)
}
private func showBugReport() {
let bugReportViewController = BugReportViewController()
// Show in fullscreen to animate presentation along side menu dismiss
bugReportViewController.modalPresentationStyle = .fullScreen
bugReportViewController.modalTransitionStyle = .crossDissolve
self.sideMenuNavigationViewController.present(bugReportViewController, animated: true)
}
private func showHelp() {
guard let helpURL = URL(string: BuildSettings.applicationHelpUrlString) else {
return
}
let safariViewController = SFSafariViewController(url: helpURL)
// Show in fullscreen to animate presentation along side menu dismiss
safariViewController.modalPresentationStyle = .fullScreen
self.sideMenuNavigationViewController.present(safariViewController, animated: true, completion: nil)
}
private func showExploreRooms(spaceId: String, session: MXSession) {
let exploreRoomCoordinator = ExploreRoomCoordinator(session: session, spaceId: spaceId)
exploreRoomCoordinator.delegate = self
let presentable = exploreRoomCoordinator.toPresentable()
presentable.presentationController?.delegate = self
self.sideMenuViewController.present(presentable, animated: true, completion: nil)
exploreRoomCoordinator.start()
self.exploreRoomCoordinator = exploreRoomCoordinator
}
private func showMembers(spaceId: String, session: MXSession) {
let parameters = SpaceMembersCoordinatorParameters(userSessionsService: self.parameters.userSessionsService, session: session, spaceId: spaceId)
let spaceMembersCoordinator = SpaceMembersCoordinator(parameters: parameters)
spaceMembersCoordinator.delegate = self
let presentable = spaceMembersCoordinator.toPresentable()
presentable.presentationController?.delegate = self
self.sideMenuViewController.present(presentable, animated: true, completion: nil)
spaceMembersCoordinator.start()
self.membersCoordinator = spaceMembersCoordinator
}
private func showInviteFriends(from sourceView: UIView?) {
let myUserId = self.parameters.userSessionsService.mainUserSession?.userId ?? ""
let inviteFriendsPresenter = InviteFriendsPresenter()
inviteFriendsPresenter.present(for: myUserId, from: self.sideMenuViewController, sourceView: sourceView, animated: true)
}
private func showMenu(forSpaceWithId spaceId: String, from sourceView: UIView?) {
guard let session = self.parameters.userSessionsService.mainUserSession?.matrixSession else {
return
}
self.spaceMenuPresenter.delegate = self
self.spaceMenuPresenter.present(forSpaceWithId: spaceId, from: self.sideMenuViewController, sourceView: sourceView, session: session, animated: true)
}
private func showSpaceDetail(forSpaceWithId spaceId: String, from sourceView: UIView?) {
guard let session = self.parameters.userSessionsService.mainUserSession?.matrixSession else {
return
}
self.spaceDetailPresenter.delegate = self
self.spaceDetailPresenter.present(forSpaceWithId: spaceId, from: self.sideMenuViewController, sourceView: sourceView, session: session, animated: true)
}
@available(iOS 14.0, *)
private func showCreateSpace() {
guard let session = self.parameters.userSessionsService.mainUserSession?.matrixSession else {
return
}
let coordinator = SpaceCreationCoordinator(parameters: SpaceCreationCoordinatorParameters(session: session))
let presentable = coordinator.toPresentable()
presentable.presentationController?.delegate = self
self.sideMenuViewController.present(presentable, animated: true, completion: nil)
coordinator.callback = { [weak self] result in
guard let self = self else {
return
}
self.createSpaceCoordinator?.toPresentable().dismiss(animated: true) {
self.createSpaceCoordinator = nil
switch result {
case .cancel:
break
case .done(let spaceId):
self.select(spaceWithId: spaceId)
}
}
}
coordinator.start()
self.createSpaceCoordinator = coordinator
}
private func showAddRoom(spaceId: String, session: MXSession) {
let space = session.spaceService.getSpace(withId: spaceId)
let createRoomCoordinator = CreateRoomCoordinator(parameters: CreateRoomCoordinatorParameter(session: session, parentSpace: space))
createRoomCoordinator.delegate = self
let presentable = createRoomCoordinator.toPresentable()
presentable.presentationController?.delegate = self
toPresentable().present(presentable, animated: true, completion: nil)
createRoomCoordinator.start()
self.createRoomCoordinator = createRoomCoordinator
}
@available(iOS 14.0, *)
private func showSpaceSettings(spaceId: String, session: MXSession) {
let coordinator = SpaceSettingsModalCoordinator(parameters: SpaceSettingsModalCoordinatorParameters(session: session, spaceId: spaceId))
coordinator.callback = { [weak self] result in
guard let self = self else { return }
coordinator.toPresentable().dismiss(animated: true) {
self.spaceSettingsCoordinator = nil
self.resetExploringSpaceIfNeeded()
}
}
let presentable = coordinator.toPresentable()
presentable.presentationController?.delegate = self
toPresentable().present(presentable, animated: true, completion: nil)
coordinator.start()
self.spaceSettingsCoordinator = coordinator
}
func showSpaceInvite(spaceId: String, session: MXSession) {
guard let space = session.spaceService.getSpace(withId: spaceId), let spaceRoom = space.room else {
MXLog.error("[SideMenuCoordinator] showSpaceInvite: failed to find space with id \(spaceId)")
return
}
spaceRoom.state { [weak self] roomState in
guard let self = self else { return }
guard let powerLevels = roomState?.powerLevels, let userId = session.myUserId else {
MXLog.error("[SpaceMembersCoordinator] spaceMemberListCoordinatorShowInvite: failed to find powerLevels for room")
return
}
let userPowerLevel = powerLevels.powerLevelOfUser(withUserID: userId)
guard userPowerLevel >= powerLevels.invite else {
let alert = UIAlertController(title: VectorL10n.spacesInvitePeople, message: VectorL10n.spaceInviteNotEnoughPermission, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: VectorL10n.ok, style: .default, handler: nil))
self.sideMenuViewController.present(alert, animated: true)
return
}
let coordinator = ContactsPickerCoordinator(session: session, room: spaceRoom, initialSearchText: nil, actualParticipants: nil, invitedParticipants: nil, userParticipant: nil)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.sideMenuViewController.present(coordinator.toPresentable(), animated: true)
}
}
private func resetExploringSpaceIfNeeded() {
if sideMenuNavigationViewController.presentedViewController == nil {
Analytics.shared.exploringSpace = nil
}
}
// MARK: UserSessions management
private func registerUserSessionsServiceNotifications() {
// Listen only notifications from the current UserSessionsService instance
let userSessionService = self.parameters.userSessionsService
NotificationCenter.default.addObserver(self, selector: #selector(userSessionsServiceDidAddUserSession(_:)), name: UserSessionsService.didAddUserSession, object: userSessionService)
}
@objc private func userSessionsServiceDidAddUserSession(_ notification: Notification) {
self.addSpaceListIfNeeded()
}
}
// MARK: - SideMenuViewModelCoordinatorDelegate
extension SideMenuCoordinator: SideMenuViewModelCoordinatorDelegate {
func sideMenuViewModel(_ viewModel: SideMenuViewModelType, didTapMenuItem menuItem: SideMenuItem, fromSourceView sourceView: UIView) {
switch menuItem {
case .inviteFriends:
self.showInviteFriends(from: sourceView)
case .settings:
self.showSettings()
case .help:
self.showHelp()
case .feedback:
self.showBugReport()
}
self.delegate?.sideMenuCoordinator(self, didTapMenuItem: menuItem, fromSourceView: sourceView)
}
}
// MARK: - SideMenuNavigationControllerDelegate
extension SideMenuCoordinator: SideMenuNavigationControllerDelegate {
func sideMenuWillAppear(menu: SideMenuNavigationController, animated: Bool) {
}
func sideMenuDidAppear(menu: SideMenuNavigationController, animated: Bool) {
}
func sideMenuWillDisappear(menu: SideMenuNavigationController, animated: Bool) {
}
func sideMenuDidDisappear(menu: SideMenuNavigationController, animated: Bool) {
}
}
// MARK: - SideMenuNavigationControllerDelegate
extension SideMenuCoordinator: SpaceListCoordinatorDelegate {
func spaceListCoordinatorDidSelectHomeSpace(_ coordinator: SpaceListCoordinatorType) {
self.parameters.appNavigator.sideMenu.dismiss(animated: true) {
}
self.parameters.appNavigator.navigate(to: .homeSpace)
}
func spaceListCoordinator(_ coordinator: SpaceListCoordinatorType, didSelectSpaceWithId spaceId: String) {
self.parameters.appNavigator.sideMenu.dismiss(animated: true) {
}
self.parameters.appNavigator.navigate(to: .space(spaceId))
}
func spaceListCoordinator(_ coordinator: SpaceListCoordinatorType, didSelectInviteWithId spaceId: String, from sourceView: UIView?) {
self.showSpaceDetail(forSpaceWithId: spaceId, from: sourceView)
}
func spaceListCoordinator(_ coordinator: SpaceListCoordinatorType, didPressMoreForSpaceWithId spaceId: String, from sourceView: UIView) {
self.showMenu(forSpaceWithId: spaceId, from: sourceView)
}
func spaceListCoordinatorDidSelectCreateSpace(_ coordinator: SpaceListCoordinatorType) {
if #available(iOS 14.0, *) {
self.showCreateSpace()
}
}
}
// MARK: - SpaceMenuPresenterDelegate
extension SideMenuCoordinator: SpaceMenuPresenterDelegate {
func spaceMenuPresenter(_ presenter: SpaceMenuPresenter, didCompleteWith action: SpaceMenuPresenter.Actions, forSpaceWithId spaceId: String, with session: MXSession) {
presenter.dismiss(animated: false) {
switch action {
case .exploreRooms:
Analytics.shared.viewRoomTrigger = .spaceMenu
self.showExploreRooms(spaceId: spaceId, session: session)
case .exploreMembers:
Analytics.shared.viewRoomTrigger = .spaceMenu
self.showMembers(spaceId: spaceId, session: session)
case .addRoom:
session.spaceService.getSpace(withId: spaceId)?.canAddRoom { canAddRoom in
if canAddRoom {
self.showAddRoom(spaceId: spaceId, session: session)
} else {
let alert = UIAlertController(title: VectorL10n.spacesAddRoom, message: VectorL10n.spacesAddRoomMissingPermissionMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: VectorL10n.ok, style: .default, handler: nil))
self.toPresentable().present(alert, animated: true, completion: nil)
}
}
case .addSpace:
AppDelegate.theDelegate().showAlert(withTitle: VectorL10n.spacesAddSpace, message: VectorL10n.spacesFeatureNotAvailable(AppInfo.current.displayName))
case .settings:
if #available(iOS 14.0, *) {
self.showSpaceSettings(spaceId: spaceId, session: session)
} else {
AppDelegate.theDelegate().showAlert(withTitle: VectorL10n.settingsTitle, message: VectorL10n.spacesFeatureNotAvailable(AppInfo.current.displayName))
}
case .invite:
self.showSpaceInvite(spaceId: spaceId, session: session)
}
}
}
}
extension SideMenuCoordinator: SpaceDetailPresenterDelegate {
func spaceDetailPresenter(_ presenter: SpaceDetailPresenter, didJoinSpaceWithId spaceId: String) {
self.spaceListCoordinator?.select(spaceWithId: spaceId)
}
func spaceDetailPresenter(_ presenter: SpaceDetailPresenter, didOpenSpaceWithId spaceId: String) {
// this use case cannot happen here as the space list open directly joined spaces on tap
self.spaceListCoordinator?.revertItemSelection()
}
func spaceDetailPresenterDidComplete(_ presenter: SpaceDetailPresenter) {
self.spaceListCoordinator?.revertItemSelection()
}
}
// MARK: - ExploreRoomCoordinatorDelegate
extension SideMenuCoordinator: ExploreRoomCoordinatorDelegate {
func exploreRoomCoordinatorDidComplete(_ coordinator: ExploreRoomCoordinatorType) {
self.exploreRoomCoordinator?.toPresentable().dismiss(animated: true) {
self.exploreRoomCoordinator = nil
self.resetExploringSpaceIfNeeded()
}
}
}
// MARK: - SpaceMembersCoordinatorDelegate
extension SideMenuCoordinator: SpaceMembersCoordinatorDelegate {
func spaceMembersCoordinatorDidCancel(_ coordinator: SpaceMembersCoordinatorType) {
self.membersCoordinator?.toPresentable().dismiss(animated: true) {
self.membersCoordinator = nil
self.resetExploringSpaceIfNeeded()
}
}
}
// MARK: - CreateRoomCoordinatorDelegate
extension SideMenuCoordinator: CreateRoomCoordinatorDelegate {
func createRoomCoordinator(_ coordinator: CreateRoomCoordinatorType, didCreateNewRoom room: MXRoom) {
coordinator.toPresentable().dismiss(animated: true) {
self.createRoomCoordinator = nil
self.parameters.appNavigator.sideMenu.dismiss(animated: true) {
self.resetExploringSpaceIfNeeded()
}
if let spaceId = coordinator.parentSpace?.spaceId {
self.parameters.appNavigator.navigate(to: .space(spaceId))
}
}
}
func createRoomCoordinator(_ coordinator: CreateRoomCoordinatorType, didAddRoomsWithIds roomIds: [String]) {
coordinator.toPresentable().dismiss(animated: true) {
self.createRoomCoordinator = nil
self.parameters.appNavigator.sideMenu.dismiss(animated: true) {
self.resetExploringSpaceIfNeeded()
}
if let spaceId = coordinator.parentSpace?.spaceId {
self.parameters.appNavigator.navigate(to: .space(spaceId))
}
}
}
func createRoomCoordinatorDidCancel(_ coordinator: CreateRoomCoordinatorType) {
coordinator.toPresentable().dismiss(animated: true) {
self.createRoomCoordinator = nil
self.resetExploringSpaceIfNeeded()
}
}
}
// MARK: - ContactsPickerCoordinatorDelegate
extension SideMenuCoordinator: ContactsPickerCoordinatorDelegate {
func contactsPickerCoordinatorDidStartLoading(_ coordinator: ContactsPickerCoordinatorProtocol) {
}
func contactsPickerCoordinatorDidEndLoading(_ coordinator: ContactsPickerCoordinatorProtocol) {
}
func contactsPickerCoordinatorDidClose(_ coordinator: ContactsPickerCoordinatorProtocol) {
remove(childCoordinator: coordinator)
}
}
// MARK: - UIAdaptivePresentationControllerDelegate
extension SideMenuCoordinator: UIAdaptivePresentationControllerDelegate {
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
self.exploreRoomCoordinator = nil
self.membersCoordinator = nil
self.createSpaceCoordinator = nil
self.createRoomCoordinator = nil
self.spaceSettingsCoordinator = nil
self.resetExploringSpaceIfNeeded()
}
}
| apache-2.0 | ff532abac82b790db3b179f916d76878 | 41.063158 | 188 | 0.696238 | 5.72083 | false | false | false | false |
MiezelKat/AWSense | AWSenseConnectTest/AWSenseConnectTest WatchKit Extension/InterfaceController.swift | 1 | 1570 | //
// InterfaceController.swift
// AWSenseConnectTest WatchKit Extension
//
// Created by Katrin Haensel on 22/02/2017.
// Copyright © 2017 Katrin Haensel. All rights reserved.
//
import WatchKit
import Foundation
import AWSenseShared
import AWSenseWatch
import AWSenseConnectWatch
class InterfaceController: WKInterfaceController, SensingEventHandler{
@IBOutlet var stateLabel: WKInterfaceLabel!
@IBOutlet var hrLabel: WKInterfaceLabel!
@IBOutlet var deviceMotionLabel: WKInterfaceLabel!
@IBOutlet var accelLabel: WKInterfaceLabel!
let sessionManager : SensingSessionManager = SensingSessionManager.instance
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
sessionManager.subscribe(handler: self)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
public func handle(withType type: SensingEventType, forSession session: SensingSession) {
DispatchQueue.main.async {
if(type == .sessionCreated){
self.stateLabel.setText("created")
}else if( type == .sessionStateChanged){
self.stateLabel.setText(session.state.rawValue)
}
}
}
}
| mit | d980d1222c0e52b7d7c89dc28356d028 | 27.017857 | 93 | 0.67559 | 5.028846 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift | 1 | 2867 | //
// Debug.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
import class Foundation.DateFormatter
let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) {
print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)")
}
final class DebugSink<Source: ObservableType, O: ObserverType>: Sink<O>, ObserverType where O.E == Source.E {
typealias Element = O.E
typealias Parent = Debug<Source>
private let _parent: Parent
private let _timestampFormatter = DateFormatter()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_timestampFormatter.dateFormat = dateFormat
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "subscribed")
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
let maxEventTextLength = 40
let eventText = "\(event)"
let eventNormalized = (eventText.characters.count > maxEventTextLength) && _parent._trimOutput
? String(eventText.characters.prefix(maxEventTextLength / 2)) + "..." + String(eventText.characters.suffix(maxEventTextLength / 2))
: eventText
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "Event \(eventNormalized)")
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
override func dispose() {
if !self.disposed {
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "isDisposed")
}
super.dispose()
}
}
final class Debug<Source: ObservableType>: Producer<Source.E> {
fileprivate let _identifier: String
fileprivate let _trimOutput: Bool
fileprivate let _source: Source
init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) {
_trimOutput = trimOutput
if let identifier = identifier {
_identifier = identifier
} else {
let trimmedFile: String
if let lastIndex = file.lastIndexOf("/") {
trimmedFile = file[file.index(after: lastIndex) ..< file.endIndex]
} else {
trimmedFile = file
}
_identifier = "\(trimmedFile):\(line) (\(function))"
}
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Source.E {
let sink = DebugSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit | 45aa2bdb9a6bd22fb3f2854bf1cd77cd | 33.119048 | 145 | 0.638521 | 4.443411 | false | false | false | false |
varshylmobile/LocationManager | LocationManager.swift | 1 | 27278 | //
// LocationManager.swift
//
//
// Created by Jimmy Jose on 14/08/14.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreLocation
import MapKit
typealias LMReverseGeocodeCompletionHandler = ((_ reverseGecodeInfo:NSDictionary?,_ placemark:CLPlacemark?, _ error:String?)->Void)?
typealias LMGeocodeCompletionHandler = ((_ gecodeInfo:NSDictionary?,_ placemark:CLPlacemark?, _ error:String?)->Void)?
typealias LMLocationCompletionHandler = ((_ latitude:Double, _ longitude:Double, _ status:String, _ verboseMessage:String, _ error:String?)->())?
// Todo: Keep completion handler differerent for all services, otherwise only one will work
enum GeoCodingType{
case geocoding
case reverseGeocoding
}
class LocationManager: NSObject,CLLocationManagerDelegate {
/* Private variables */
fileprivate var completionHandler:LMLocationCompletionHandler
fileprivate var reverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler
fileprivate var geocodingCompletionHandler:LMGeocodeCompletionHandler
fileprivate var locationStatus : NSString = "Calibrating"// to pass in handler
fileprivate var locationManager: CLLocationManager!
fileprivate var verboseMessage = "Calibrating"
fileprivate let verboseMessageDictionary = [CLAuthorizationStatus.notDetermined:"You have not yet made a choice with regards to this application.",
CLAuthorizationStatus.restricted:"This application is not authorized to use location services. Due to active restrictions on location services, the user cannot change this status, and may not have personally denied authorization.",
CLAuthorizationStatus.denied:"You have explicitly denied authorization for this application, or location services are disabled in Settings.",
CLAuthorizationStatus.authorizedAlways:"App is Authorized to use location services.",
CLAuthorizationStatus.authorizedWhenInUse:"You have granted authorization to use your location only when the app is visible to you."]
var delegate:LocationManagerDelegate? = nil
var latitude:Double = 0.0
var longitude:Double = 0.0
var latitudeAsString:String = ""
var longitudeAsString:String = ""
var lastKnownLatitude:Double = 0.0
var lastKnownLongitude:Double = 0.0
var lastKnownLatitudeAsString:String = ""
var lastKnownLongitudeAsString:String = ""
var keepLastKnownLocation:Bool = true
var hasLastKnownLocation:Bool = true
var autoUpdate:Bool = false
var showVerboseMessage = false
var isRunning = false
class var sharedInstance : LocationManager {
struct Static {
static let instance : LocationManager = LocationManager()
}
return Static.instance
}
fileprivate override init(){
super.init()
if(!autoUpdate){
autoUpdate = !CLLocationManager.significantLocationChangeMonitoringAvailable()
}
}
fileprivate func resetLatLon(){
latitude = 0.0
longitude = 0.0
latitudeAsString = ""
longitudeAsString = ""
}
fileprivate func resetLastKnownLatLon(){
hasLastKnownLocation = false
lastKnownLatitude = 0.0
lastKnownLongitude = 0.0
lastKnownLatitudeAsString = ""
lastKnownLongitudeAsString = ""
}
func startUpdatingLocationWithCompletionHandler(_ completionHandler:((_ latitude:Double, _ longitude:Double, _ status:String, _ verboseMessage:String, _ error:String?)->())? = nil){
self.completionHandler = completionHandler
initLocationManager()
}
func startUpdatingLocation(){
initLocationManager()
}
func stopUpdatingLocation(){
if(autoUpdate){
locationManager.stopUpdatingLocation()
}else{
locationManager.stopMonitoringSignificantLocationChanges()
}
resetLatLon()
if(!keepLastKnownLocation){
resetLastKnownLatLon()
}
}
fileprivate func initLocationManager() {
// App might be unreliable if someone changes autoupdate status in between and stops it
locationManager = CLLocationManager()
locationManager.delegate = self
// locationManager.locationServicesEnabled
locationManager.desiredAccuracy = kCLLocationAccuracyBest
let Device = UIDevice.current
let iosVersion = NSString(string: Device.systemVersion).doubleValue
let iOS8 = iosVersion >= 8
if iOS8{
//locationManager.requestAlwaysAuthorization() // add in plist NSLocationAlwaysUsageDescription
locationManager.requestWhenInUseAuthorization() // add in plist NSLocationWhenInUseUsageDescription
}
startLocationManger()
}
fileprivate func startLocationManger(){
if(autoUpdate){
locationManager.startUpdatingLocation()
}else{
locationManager.startMonitoringSignificantLocationChanges()
}
isRunning = true
}
fileprivate func stopLocationManger(){
if(autoUpdate){
locationManager.stopUpdatingLocation()
}else{
locationManager.stopMonitoringSignificantLocationChanges()
}
isRunning = false
}
internal func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
stopLocationManger()
resetLatLon()
if(!keepLastKnownLocation){
resetLastKnownLatLon()
}
var verbose = ""
if showVerboseMessage {verbose = verboseMessage}
completionHandler?(0.0, 0.0, locationStatus as String, verbose,error.localizedDescription)
if ((delegate != nil) && (delegate?.responds(to: #selector(LocationManagerDelegate.locationManagerReceivedError(_:))))!){
delegate?.locationManagerReceivedError!(error.localizedDescription as NSString)
}
}
internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let arrayOfLocation = locations as NSArray
let location = arrayOfLocation.lastObject as! CLLocation
let coordLatLon = location.coordinate
latitude = coordLatLon.latitude
longitude = coordLatLon.longitude
latitudeAsString = coordLatLon.latitude.description
longitudeAsString = coordLatLon.longitude.description
var verbose = ""
if showVerboseMessage {verbose = verboseMessage}
if(completionHandler != nil){
completionHandler?(latitude, longitude, locationStatus as String,verbose, nil)
}
lastKnownLatitude = coordLatLon.latitude
lastKnownLongitude = coordLatLon.longitude
lastKnownLatitudeAsString = coordLatLon.latitude.description
lastKnownLongitudeAsString = coordLatLon.longitude.description
hasLastKnownLocation = true
if (delegate != nil){
if((delegate?.responds(to: #selector(LocationManagerDelegate.locationFoundGetAsString(_:longitude:))))!){
delegate?.locationFoundGetAsString!(latitudeAsString as NSString,longitude:longitudeAsString as NSString)
}
if((delegate?.responds(to: #selector(LocationManagerDelegate.locationFound(_:longitude:))))!){
delegate?.locationFound(latitude,longitude:longitude)
}
}
}
internal func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
var hasAuthorised = false
let verboseKey = status
switch status {
case CLAuthorizationStatus.restricted:
locationStatus = "Restricted Access"
case CLAuthorizationStatus.denied:
locationStatus = "Denied access"
case CLAuthorizationStatus.notDetermined:
locationStatus = "Not determined"
default:
locationStatus = "Allowed access"
hasAuthorised = true
}
verboseMessage = verboseMessageDictionary[verboseKey]!
if (hasAuthorised == true) {
startLocationManger()
}else{
resetLatLon()
if (!locationStatus.isEqual(to: "Denied access")){
var verbose = ""
if showVerboseMessage {
verbose = verboseMessage
if ((delegate != nil) && (delegate?.responds(to: #selector(LocationManagerDelegate.locationManagerVerboseMessage(_:))))!){
delegate?.locationManagerVerboseMessage!(verbose as NSString)
}
}
if(completionHandler != nil){
completionHandler?(latitude, longitude, locationStatus as String, verbose,nil)
}
}
if ((delegate != nil) && (delegate?.responds(to: #selector(LocationManagerDelegate.locationManagerStatus(_:))))!){
delegate?.locationManagerStatus!(locationStatus)
}
}
}
func reverseGeocodeLocationWithLatLon(latitude:Double, longitude: Double,onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){
let location:CLLocation = CLLocation(latitude:latitude, longitude: longitude)
reverseGeocodeLocationWithCoordinates(location,onReverseGeocodingCompletionHandler: onReverseGeocodingCompletionHandler)
}
func reverseGeocodeLocationWithCoordinates(_ coord:CLLocation, onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){
self.reverseGeocodingCompletionHandler = onReverseGeocodingCompletionHandler
reverseGocode(coord)
}
fileprivate func reverseGocode(_ location:CLLocation){
let geocoder: CLGeocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
self.reverseGeocodingCompletionHandler!(nil,nil, error!.localizedDescription)
}
else{
if let placemark = placemarks?.first {
let address = AddressParser()
address.parseAppleLocationData(placemark)
let addressDict = address.getAddressDictionary()
self.reverseGeocodingCompletionHandler!(addressDict,placemark,nil)
}
else {
self.reverseGeocodingCompletionHandler!(nil,nil,"No Placemarks Found!")
return
}
}
})
}
func geocodeAddressString(address:NSString, onGeocodingCompletionHandler:LMGeocodeCompletionHandler){
self.geocodingCompletionHandler = onGeocodingCompletionHandler
geoCodeAddress(address)
}
fileprivate func geoCodeAddress(_ address:NSString){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address as String, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
if (error != nil) {
self.geocodingCompletionHandler!(nil,nil,error!.localizedDescription)
}
else{
if let placemark = placemarks?.first {
let address = AddressParser()
address.parseAppleLocationData(placemark)
let addressDict = address.getAddressDictionary()
self.geocodingCompletionHandler!(addressDict,placemark,nil)
}
else {
self.geocodingCompletionHandler!(nil,nil,"invalid address: \(address)")
}
}
} as! CLGeocodeCompletionHandler)
}
func geocodeUsingGoogleAddressString(address:NSString, onGeocodingCompletionHandler:LMGeocodeCompletionHandler){
self.geocodingCompletionHandler = onGeocodingCompletionHandler
geoCodeUsignGoogleAddress(address)
}
fileprivate func geoCodeUsignGoogleAddress(_ address:NSString){
var urlString = "http://maps.googleapis.com/maps/api/geocode/json?address=\(address)&sensor=true" as NSString
urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! as NSString
performOperationForURL(urlString, type: GeoCodingType.geocoding)
}
func reverseGeocodeLocationUsingGoogleWithLatLon(latitude:Double, longitude: Double,onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){
self.reverseGeocodingCompletionHandler = onReverseGeocodingCompletionHandler
reverseGocodeUsingGoogle(latitude: latitude, longitude: longitude)
}
func reverseGeocodeLocationUsingGoogleWithCoordinates(_ coord:CLLocation, onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){
reverseGeocodeLocationUsingGoogleWithLatLon(latitude: coord.coordinate.latitude, longitude: coord.coordinate.longitude, onReverseGeocodingCompletionHandler: onReverseGeocodingCompletionHandler)
}
fileprivate func reverseGocodeUsingGoogle(latitude:Double, longitude: Double){
var urlString = "http://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&sensor=true" as NSString
urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! as NSString
performOperationForURL(urlString, type: GeoCodingType.reverseGeocoding)
}
fileprivate func performOperationForURL(_ urlString:NSString,type:GeoCodingType){
let url:URL? = URL(string:urlString as String)
let request:URLRequest = URLRequest(url:url!)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if(error != nil){
self.setCompletionHandler(responseInfo:nil, placemark:nil, error:error!.localizedDescription, type:type)
}else{
let kStatus = "status"
let kOK = "ok"
let kZeroResults = "ZERO_RESULTS"
let kAPILimit = "OVER_QUERY_LIMIT"
let kRequestDenied = "REQUEST_DENIED"
let kInvalidRequest = "INVALID_REQUEST"
let kInvalidInput = "Invalid Input"
//let dataAsString: NSString? = NSString(data: data!, encoding: NSUTF8StringEncoding)
let jsonResult: NSDictionary = (try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary
var status = jsonResult.value(forKey: kStatus) as! NSString
status = status.lowercased as NSString
if(status.isEqual(to: kOK)){
let address = AddressParser()
address.parseGoogleLocationData(jsonResult)
let addressDict = address.getAddressDictionary()
let placemark:CLPlacemark = address.getPlacemark()
self.setCompletionHandler(responseInfo:addressDict, placemark:placemark, error: nil, type:type)
}else if(!status.isEqual(to: kZeroResults) && !status.isEqual(to: kAPILimit) && !status.isEqual(to: kRequestDenied) && !status.isEqual(to: kInvalidRequest)){
self.setCompletionHandler(responseInfo:nil, placemark:nil, error:kInvalidInput, type:type)
}
else{
//status = (status.componentsSeparatedByString("_") as NSArray).componentsJoinedByString(" ").capitalizedString
self.setCompletionHandler(responseInfo:nil, placemark:nil, error:status as String, type:type)
}
}
})
task.resume()
}
fileprivate func setCompletionHandler(responseInfo:NSDictionary?,placemark:CLPlacemark?, error:String?,type:GeoCodingType){
if(type == GeoCodingType.geocoding){
self.geocodingCompletionHandler!(responseInfo,placemark,error)
}else{
self.reverseGeocodingCompletionHandler!(responseInfo,placemark,error)
}
}
}
@objc protocol LocationManagerDelegate : NSObjectProtocol
{
func locationFound(_ latitude:Double, longitude:Double)
@objc optional func locationFoundGetAsString(_ latitude:NSString, longitude:NSString)
@objc optional func locationManagerStatus(_ status:NSString)
@objc optional func locationManagerReceivedError(_ error:NSString)
@objc optional func locationManagerVerboseMessage(_ message:NSString)
}
private class AddressParser: NSObject{
fileprivate var latitude = NSString()
fileprivate var longitude = NSString()
fileprivate var streetNumber = NSString()
fileprivate var route = NSString()
fileprivate var locality = NSString()
fileprivate var subLocality = NSString()
fileprivate var formattedAddress = NSString()
fileprivate var administrativeArea = NSString()
fileprivate var administrativeAreaCode = NSString()
fileprivate var subAdministrativeArea = NSString()
fileprivate var postalCode = NSString()
fileprivate var country = NSString()
fileprivate var subThoroughfare = NSString()
fileprivate var thoroughfare = NSString()
fileprivate var ISOcountryCode = NSString()
fileprivate var state = NSString()
override init(){
super.init()
}
fileprivate func getAddressDictionary()-> NSDictionary{
let addressDict = NSMutableDictionary()
addressDict.setValue(latitude, forKey: "latitude")
addressDict.setValue(longitude, forKey: "longitude")
addressDict.setValue(streetNumber, forKey: "streetNumber")
addressDict.setValue(locality, forKey: "locality")
addressDict.setValue(subLocality, forKey: "subLocality")
addressDict.setValue(administrativeArea, forKey: "administrativeArea")
addressDict.setValue(postalCode, forKey: "postalCode")
addressDict.setValue(country, forKey: "country")
addressDict.setValue(formattedAddress, forKey: "formattedAddress")
return addressDict
}
fileprivate func parseAppleLocationData(_ placemark:CLPlacemark){
let addressLines = placemark.addressDictionary!["FormattedAddressLines"] as! NSArray
//self.streetNumber = placemark.subThoroughfare ? placemark.subThoroughfare : ""
self.streetNumber = (placemark.thoroughfare != nil ? placemark.thoroughfare : "")! as NSString
self.locality = (placemark.locality != nil ? placemark.locality : "")! as NSString
self.postalCode = (placemark.postalCode != nil ? placemark.postalCode : "")! as NSString
self.subLocality = (placemark.subLocality != nil ? placemark.subLocality : "")! as NSString
self.administrativeArea = (placemark.administrativeArea != nil ? placemark.administrativeArea : "")! as NSString
self.country = (placemark.country != nil ? placemark.country : "")! as NSString
self.longitude = placemark.location!.coordinate.longitude.description as NSString;
self.latitude = placemark.location!.coordinate.latitude.description as NSString
if(addressLines.count>0){
self.formattedAddress = addressLines.componentsJoined(by: ", ") as NSString}
else{
self.formattedAddress = ""
}
}
fileprivate func parseGoogleLocationData(_ resultDict:NSDictionary){
let locationDict = (resultDict.value(forKey: "results") as! NSArray).firstObject as! NSDictionary
let formattedAddrs = locationDict.object(forKey: "formatted_address") as! NSString
let geometry = locationDict.object(forKey: "geometry") as! NSDictionary
let location = geometry.object(forKey: "location") as! NSDictionary
let lat = location.object(forKey: "lat") as! Double
let lng = location.object(forKey: "lng") as! Double
self.latitude = lat.description as NSString
self.longitude = lng.description as NSString
let addressComponents = locationDict.object(forKey: "address_components") as! NSArray
self.subThoroughfare = component("street_number", inArray: addressComponents, ofType: "long_name")
self.thoroughfare = component("route", inArray: addressComponents, ofType: "long_name")
self.streetNumber = self.subThoroughfare
self.locality = component("locality", inArray: addressComponents, ofType: "long_name")
self.postalCode = component("postal_code", inArray: addressComponents, ofType: "long_name")
self.route = component("route", inArray: addressComponents, ofType: "long_name")
self.subLocality = component("subLocality", inArray: addressComponents, ofType: "long_name")
self.administrativeArea = component("administrative_area_level_1", inArray: addressComponents, ofType: "long_name")
self.administrativeAreaCode = component("administrative_area_level_1", inArray: addressComponents, ofType: "short_name")
self.subAdministrativeArea = component("administrative_area_level_2", inArray: addressComponents, ofType: "long_name")
self.country = component("country", inArray: addressComponents, ofType: "long_name")
self.ISOcountryCode = component("country", inArray: addressComponents, ofType: "short_name")
self.formattedAddress = formattedAddrs;
}
fileprivate func component(_ component:NSString,inArray:NSArray,ofType:NSString) -> NSString{
let index = inArray.indexOfObject(passingTest:) {obj, idx, stop in
let objDict:NSDictionary = obj as! NSDictionary
let types:NSArray = objDict.object(forKey: "types") as! NSArray
let type = types.firstObject as! NSString
return type.isEqual(to: component as String)
}
if (index == NSNotFound){
return ""
}
if (index >= inArray.count){
return ""
}
let type = ((inArray.object(at: index) as! NSDictionary).value(forKey: ofType as String)!) as! NSString
if (type.length > 0){
return type
}
return ""
}
fileprivate func getPlacemark() -> CLPlacemark{
var addressDict = [String : AnyObject]()
let formattedAddressArray = self.formattedAddress.components(separatedBy: ", ") as Array
let kSubAdministrativeArea = "SubAdministrativeArea"
let kSubLocality = "SubLocality"
let kState = "State"
let kStreet = "Street"
let kThoroughfare = "Thoroughfare"
let kFormattedAddressLines = "FormattedAddressLines"
let kSubThoroughfare = "SubThoroughfare"
let kPostCodeExtension = "PostCodeExtension"
let kCity = "City"
let kZIP = "ZIP"
let kCountry = "Country"
let kCountryCode = "CountryCode"
addressDict[kSubAdministrativeArea] = self.subAdministrativeArea
addressDict[kSubLocality] = self.subLocality as NSString
addressDict[kState] = self.administrativeAreaCode
addressDict[kStreet] = formattedAddressArray.first! as NSString
addressDict[kThoroughfare] = self.thoroughfare
addressDict[kFormattedAddressLines] = formattedAddressArray as AnyObject?
addressDict[kSubThoroughfare] = self.subThoroughfare
addressDict[kPostCodeExtension] = "" as AnyObject?
addressDict[kCity] = self.locality
addressDict[kZIP] = self.postalCode
addressDict[kCountry] = self.country
addressDict[kCountryCode] = self.ISOcountryCode
let lat = self.latitude.doubleValue
let lng = self.longitude.doubleValue
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict as [String : AnyObject]?)
return (placemark as CLPlacemark)
}
}
| mit | c702e7a563d97d2b6594dbd30faf99e6 | 37.528249 | 239 | 0.623616 | 5.909445 | false | false | false | false |
ShauryaS/TestStudyPlanner-iosApp | Test Study Plan/PlanInformation.swift | 1 | 1958 | //
// PlanInformation.swift
// Test Study Plan
//
// Created by Shaurya Srivastava on 4/17/16.
// Copyright © 2016 Shaurya Srivastava. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class PlanInformation: UIViewController{
var planName = "";
@IBOutlet var planNameLable: UILabel!
fileprivate var i = 0
@IBOutlet var planInfoDisp: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title="Plan Information"
planInfoDisp.contentSize.height = 30
planNameLable.text = planName
planNameLable.font = planNameLable.font.withSize(25)
planNameLable.textColor = UIColor.white
showPlan()
// Do any additional setup after loading the view, typically from a nib.\
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showPlan(){//error when storing data when assignments hit > 10
CURRENT_USER.child(byAppendingPath: "plans").child(byAppendingPath: planName).child(byAppendingPath: "time").queryOrderedByKey().observe(.value, with: {snapshot in
for t in snapshot?.children.allObjects as! [FDataSnapshot] {
let label = UILabel(frame: CGRect(x: 0,y: 5+(CGFloat(self.i)-3)*25,width: 374,height: 25))
var tl = "Time to Study for Section "+String(self.i+1)
tl = tl + ": "+((t.value as AnyObject).stringValue)+" minutes"
label.text = tl
label.font = label.font.withSize(15)
label.textColor = UIColor.white
self.planInfoDisp.addSubview(label)
if (5+CGFloat(self.i))*25>self.planInfoDisp.contentSize.height{
self.planInfoDisp.contentSize.height+=30
}
self.i = self.i+1;
}
})
}
}
| apache-2.0 | 684c37ad22e7895718093ca94e142674 | 35.240741 | 171 | 0.621359 | 4.291667 | false | false | false | false |
kevto/SwiftClient | SwiftClient/FormData.swift | 1 | 3036 | //
// FormData.swift
// SwiftClient
//
// Created by Adam Nalisnick on 11/4/14.
// Copyright (c) 2014 Adam Nalisnick. All rights reserved.
//
import Foundation
import MobileCoreServices
internal class FormData {
private let boundary = "BOUNDARY-" + NSUUID().UUIDString;
private let nl = stringToData("\r\n");
internal init(){}
private var fields:[(name:String, value:String)] = Array();
private var files:[(name:String, data:NSData, filename:String, mimeType:String)] = Array();
internal func append(name:String, _ value:String){
fields += [(name: name, value: value)]
}
internal func append(name:String, _ data:NSData, _ filename:String, _ mimeType:String? = nil){
let type = mimeType ?? determineMimeType(filename)
files += [(name: name, data: data, filename: filename, mimeType: type)]
}
private func determineMimeType(filename:String) -> String {
let type = NSURL(string: filename)!.pathExtension!
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, type as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream";
}
internal func getContentType() -> String {
return "multipart/form-data; boundary=\(boundary)";
}
internal func getBody() -> NSData? {
if(fields.count > 0 || files.count > 0){
var body = NSMutableData();
for (field) in fields {
appendField(body, field.name, field.value)
}
for (file) in files {
appendFile(body, file.name, file.data, file.filename, file.mimeType);
}
body.appendData(stringToData("--\(boundary)--"));
body.appendData(nl);
return body;
}
return nil
}
private func appendFile(body:NSMutableData, _ name:String, _ data:NSData, _ filename:String, _ mimeType:String) {
body.appendData(stringToData("--\(boundary)"))
body.appendData(nl)
body.appendData(stringToData("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\""))
body.appendData(nl);
body.appendData(stringToData("Content-Type: \(mimeType)"));
body.appendData(nl);
body.appendData(nl);
body.appendData(data);
body.appendData(nl);
}
private func appendField(body:NSMutableData, _ name:String, _ value:String) {
body.appendData(stringToData("--\(boundary)"))
body.appendData(nl)
body.appendData(stringToData("Content-Disposition: form-data; name=\"\(name)\""))
body.appendData(nl);
body.appendData(nl);
body.appendData(stringToData(value))
body.appendData(nl);
}
}
| mit | ce0e77ad4fe5177493223182fecf3420 | 33.11236 | 134 | 0.596838 | 4.635115 | false | false | false | false |
dche/GLMath | Sources/VecRel.swift | 1 | 2010 | //
// GLMath - VecRel.swift
//
// GLSLangSpec 8.7 Vector Relational Functions
//
// Copyright (c) 2016 The GLMath authors
// Licensed under MIT License
func vecRel<T: NumericVector>(
_ x: T,
_ y: T,
_ p: (T.Component, T.Component) -> Bool
) -> T.AssociatedBooleanVector {
var a = T.AssociatedBooleanVector(false)
for i in 0 ..< T.dimension {
a[i] = p(x[i], y[i])
}
return a
}
/// Returns the component-wise compare of `x < y`.
public func lessThan<T: NumericVector>(
_ x: T,
_ y: T
) -> T.AssociatedBooleanVector {
return vecRel(x, y, <)
}
/// Returns the component-wise compare of `x ≤ y`.
public func lessThanEqual<T: NumericVector>(
_ x: T,
_ y: T
) -> T.AssociatedBooleanVector {
return vecRel(x, y, <=)
}
/// Returns the component-wise compare of `x > y`.
public func greaterThan<T: NumericVector>(
_ x: T,
_ y: T
) -> T.AssociatedBooleanVector {
return vecRel(x, y, >)
}
/// Returns the component-wise compare of `x ≥ y`.
public func greaterThanEqual<T: NumericVector>(
_ x: T,
_ y: T
) -> T.AssociatedBooleanVector {
return vecRel(x, y, >=)
}
/// Returns the component-wise compare of `x == y`.
public func equal<T: NumericVector>(
_ x: T,
_ y: T
) -> T.AssociatedBooleanVector {
return vecRel(x, y, ==)
}
/// Returns the component-wise compare of `x ≠ y`.
public func notEqual<T: NumericVector>(
_ x: T,
_ y: T
) -> T.AssociatedBooleanVector {
return vecRel(x, y, !=)
}
/// Returns `true` if any component of `x` is **true**.
public func any<T: Vector>(_ x: T) -> Bool
where
T.Component == Bool
{
return x.reduce { $0 || $1 }
}
/// Returns `true` only if all components of `x` are **true**.
public func all<T: Vector>(_ x: T) -> Bool
where
T.Component == Bool
{
return x.reduce { $0 && $1 }
}
/// Returns the component-wise logical complement of `x`.
public func not<T: Vector>(_ x: T) -> T
where
T.Component == Bool
{
return x.map { !$0 }
}
| mit | 3027f3759cd39d33934fe618e6d52e8b | 21.021978 | 62 | 0.598802 | 3.092593 | false | false | false | false |
JALsnipe/google-news-reader | google-news-reader/google-news-reader/Controllers/ArticleListTableViewController.swift | 1 | 6402 | //
// ArticleListTableViewController.swift
// google-news-reader
//
// Created by Josh Lieberman on 7/25/15.
// Copyright © 2015 Lieberman. All rights reserved.
//
import UIKit
import CoreData
class ArticleListTableViewController: UITableViewController {
var context: NSManagedObjectContext!
// Set up an NSFetchedResultsController to fetch articles by date published
lazy var fetchedResultsController: NSFetchedResultsController = {
let articlesFetchRequest = NSFetchRequest(entityName: "Article")
articlesFetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
let frc = NSFetchedResultsController(fetchRequest: articlesFetchRequest, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)
return frc
}()
override func viewDidLoad() {
super.viewDidLoad()
// Perform an intial fetch of Article objects from Core Data to show cached data, if any
do {
try self.fetchedResultsController.performFetch()
self.tableView.reloadData()
} catch {
print("Error performing initial fetch: \(error)")
}
self.reloadTableWithArticles()
}
func reloadTableWithArticles() {
// Download new articles
NetworkManager().fetchAllArticlesWithCompletion { (data, error) -> Void in
if error != nil {
// handle errors and return
if let networkError = error as? NetworkError {
switch networkError{
case .NetworkFailure:
self.alertUserWithTitleAndMessage("Network Error", message: kNetworkFailureMessage)
return
default:
self.alertUserWithTitleAndMessage("Unknown Error", message: kUnknownErrorMessage)
return
}
}
}
if let unwrappedData = data as? NSData {
NetworkManager().parseAllArticleData(unwrappedData, completion: { (content, error) -> Void in
if error == nil {
// Hop back on the main thread to reload, since we're in an async callback
dispatch_async(dispatch_get_main_queue(), { () -> Void in
do {
try self.fetchedResultsController.performFetch()
self.tableView.reloadData()
} catch {
print("Error: \(error)")
// TODO: Core Data fetch failed, use prototype objects (content) returned
}
})
} else {
// handle error
if let networkError = error as? NetworkError {
switch networkError {
case .ParsingError:
self.alertUserWithTitleAndMessage("Network Error", message: kParsingErrorMessage)
return
default:
self.alertUserWithTitleAndMessage("Unknown Error", message: kUnknownErrorMessage)
}
}
}
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func refreshTable(sender: AnyObject) {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.reloadTableWithArticles()
sender.endRefreshing()
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let results = self.fetchedResultsController.fetchedObjects?.count {
return results
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("articleListCell", forIndexPath: indexPath) as! ArticleListTableViewCell
if let dataSource = self.fetchedResultsController.fetchedObjects as? [Article] {
cell.articleTitleLabel.text = dataSource[indexPath.row].title
cell.articleDescriptionLabel.text = dataSource[indexPath.row].articleDesciption
if let cellImage: UIImage = dataSource[indexPath.row].image as? UIImage {
cell.articleImageView.image = cellImage
} else {
cell.articleImageView.image = UIImage(named: "img_thumb_placeholder")
}
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 88.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showArticleDetail", sender: indexPath)
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Check if the destination view controller is the detail controller
if let detailVC = segue.destinationViewController as? ArticleDetailTableViewController {
// The sender should only be an indexPath, so unwrap it
if let indexPath = sender as? NSIndexPath {
// Find the Article from the indexPath.row specified and pass it to our destination view controller
if let dataSource = self.fetchedResultsController.fetchedObjects as? [Article] {
detailVC.article = dataSource[indexPath.row]
}
}
}
}
}
| mit | 9254baf6e0b2fd6b87482612ec5c555e | 38.030488 | 157 | 0.557725 | 6.426707 | false | false | false | false |
rock-n-code/Kashmir | Kashmir/iOS/Common/Extensions/UIImageExtensions.swift | 1 | 1486 | //
// UIImageExtensions.swift
// Kashmir
//
// Created by Javier Cicchelli on 06/04/2017.
// Copyright © 2017 Rock & Code. All rights reserved.
//
import UIKit
public extension UIImage {
/**
Create a new masked image with a defined color from the current image.
- parameters:
- color: The color to use to mask the current image.
- opaque: A `Boolean` flag indicating whether the bitmap is opaque. If you know the bitmap is fully opaque, specify true to ignore the alpha channel and optimize the bitmap’s storage. Specifying false means that the bitmap must include an alpha channel to handle any partially transparent pixels.
- returns: A color-masked version of the current `UIImage` instance painted with the given color.
*/
func mask(withColor color: UIColor, isOpaque opaque: Bool = false) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, opaque, UIScreen.main.scale)
guard
let context = UIGraphicsGetCurrentContext(),
let image = cgImage
else {
return nil
}
let frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
color.setFill()
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(.colorBurn)
context.draw(image, in: frame)
context.setBlendMode(.sourceIn)
context.addRect(frame)
context.drawPath(using: .fill)
let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return coloredImage
}
}
| mit | 7b812a915bfb07fe90da2e51bd7514c6 | 28.66 | 298 | 0.729602 | 3.882199 | false | false | false | false |
vzool/ios-nanodegree-virtual-tourist | Virtual Tourist/CoreDataStackManager.swift | 1 | 5272 | //
// CoreDataStackManager.swift
// FavoriteActors
//
// Created by Jason on 3/10/15.
// Copyright (c) 2015 Udacity. All rights reserved.
//
import Foundation
import CoreData
/**
* The CoreDataStackManager contains the code that was previously living in the
* AppDelegate in Lesson 3. Apple puts the code in the AppDelegate in many of their
* Xcode templates. But they put it in a convenience class like this in sample code
* like the "Earthquakes" project.
*
*/
private let SQLITE_FILE_NAME = "VirtualTouristDataFile.sqlite"
class CoreDataStackManager {
// MARK: - Shared Instance
/**
* This class variable provides an easy way to get access
* to a shared instance of the CoreDataStackManager class.
*/
class func sharedInstance() -> CoreDataStackManager {
struct Static {
static let instance = CoreDataStackManager()
}
return Static.instance
}
// MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate.
lazy var applicationDocumentsDirectory: NSURL = {
println("Instantiating the applicationDocumentsDirectory property")
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
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.
println("Instantiating the managedObjectModel property")
let modelURL = NSBundle.mainBundle().URLForResource("Virtual_Tourist", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
/**
* The Persistent Store Coordinator is an object that the Context uses to interact with the underlying file system. Usually
* the persistent store coordinator object uses an SQLite database file to save the managed objects. But it is possible to
* configure it to use XML or other formats.
*
* Typically you will construct your persistent store manager exactly like this. It needs two pieces of information in order
* to be set up:
*
* - The path to the sqlite file that will be used. Usually in the documents directory
* - A configured Managed Object Model. See the next property for details.
*/
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
println("Instantiating the persistentStoreCoordinator property")
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME)
println("sqlite path: \(url.path!)")
var error: NSError? = nil
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data."
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// Left in for development development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
println("Instantiating the managedObjectContext property")
// 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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let context = self.managedObjectContext {
var error: NSError? = nil
if context.hasChanges && !context.save(&error) {
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
} | mit | fc140be6a6fbac58d0dfcb6ebd5765d9 | 40.195313 | 290 | 0.673938 | 5.674919 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/ArticleViewController+WIconPopover.swift | 1 | 1691 | import Foundation
/// W icon popover tooltip
extension ArticleViewController {
var shouldShowWIconPopover: Bool {
guard
!UserDefaults.standard.wmf_didShowWIconPopover(),
presentedViewController == nil,
navigationController != nil,
navigationBar.navigationBarPercentHidden < 0.1
else {
return false
}
return true
}
func showWIconPopoverIfNecessary() {
guard shouldShowWIconPopover else {
return
}
perform(#selector(showWIconPopover), with: nil, afterDelay: 1.0)
}
func cancelWIconPopoverDisplay() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(showWIconPopover), object: nil)
}
@objc func showWIconPopover() {
guard let titleView = navigationItem.titleView else {
return
}
let sourceRect = titleView.convert(titleView.bounds, to: view)
guard sourceRect.origin.y > 0 else {
return
}
let title = WMFLocalizedString("back-button-popover-title", value: "Tap to go back", comment: "Title for popover explaining the 'W' icon may be tapped to go back.")
let message = WMFLocalizedString("original-tab-button-popover-description", value: "Tap on the 'W' to return to the tab you started from", comment: "Description for popover explaining the 'W' icon may be tapped to return to the original tab.")
wmf_presentDynamicHeightPopoverViewController(forSourceRect: sourceRect, withTitle: title, message: message, width: 230, duration: 3)
UserDefaults.standard.wmf_setDidShowWIconPopover(true)
}
}
| mit | abfa6cf683d28c5c2e944188d91bff87 | 40.243902 | 251 | 0.664695 | 4.859195 | false | false | false | false |
BurntCaramel/Lantern | Lantern/SourcePreviewViewController.swift | 1 | 5912 | //
// SourcePreviewViewController.swift
// Hoverlytics
//
// Created by Patrick Smith on 27/04/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Cocoa
import LanternModel
enum SourcePreviewTabItemSection: String {
case Main = "Main"
case HTMLHead = "HTMLHead"
case HTMLBody = "HTMLBody"
var stringValue: String { return rawValue }
func titleWithPageInfo(_ pageInfo: PageInfo) -> String {
switch self {
case .Main:
if let MIMEType = pageInfo.MIMEType {
return MIMEType.stringValue
}
else {
return "Main"
}
case .HTMLHead:
return "<head>"
case .HTMLBody:
return "<body>"
}
}
}
class SourcePreviewTabViewController: NSTabViewController {
override func viewDidLoad() {
super.viewDidLoad()
//tabView.delegate = self
}
var pageInfo: PageInfo! {
didSet {
switch pageInfo.baseContentType {
case .localHTMLPage:
updateForHTMLPreview()
default:
updateForGeneralPreview()
}
}
}
func updateWithSections(_ sections: [SourcePreviewTabItemSection]) {
let tabViewItems = sections.map { section in
self.newSourcePreviewTabViewItem(section)
}
// This crashes for some reason
// self.tabViewItems = tabViewItems
let existingItems = self.tabViewItems
for existingItem in existingItems {
removeTabViewItem(existingItem)
}
for tabViewItem in tabViewItems {
addTabViewItem(tabViewItem)
}
//updateSourceTextForSection(sections[0], tabViewItem: tabViewItems[0])
}
func updateForGeneralPreview() {
updateWithSections([.Main])
}
func updateForHTMLPreview() {
updateWithSections([.HTMLHead, .HTMLBody])
}
func newSourcePreviewTabViewItem(_ section: SourcePreviewTabItemSection) -> NSTabViewItem {
let item = NSTabViewItem(identifier: section.stringValue)
let vc = newSourcePreviewController()
vc.wantsToDismiss = {
self.dismiss(nil)
}
item.viewController = vc
item.label = section.titleWithPageInfo(pageInfo)
return item
}
func newSourcePreviewController() -> SourcePreviewViewController {
return NSStoryboard.lantern_contentPreviewStoryboard.instantiateController(withIdentifier: "Source Preview View Controller") as! SourcePreviewViewController
}
func updateSourceTextForSection(_ section: SourcePreviewTabItemSection, tabViewItem: NSTabViewItem) {
let vc = tabViewItem.viewController as! SourcePreviewViewController
if let contentInfo = self.pageInfo.contentInfo {
switch section {
case .Main:
setSourceText(contentInfo.stringContent, forSourcePreviewViewController: vc)
case .HTMLHead:
setSourceText(contentInfo.HTMLHeadStringContent, forSourcePreviewViewController: vc)
case .HTMLBody:
setSourceText(contentInfo.HTMLBodyStringContent, forSourcePreviewViewController: vc)
}
}
else {
setSourceText("(none)", forSourcePreviewViewController: vc)
}
}
func setSourceText(_ sourceText: String?, forSourcePreviewViewController vc: SourcePreviewViewController) {
vc.sourceText = sourceText ?? "(None)"
}
override func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) {
if let
tabViewItem = tabViewItem,
let identifier = tabViewItem.identifier as? String,
let section = SourcePreviewTabItemSection(rawValue: identifier)
{
updateSourceTextForSection(section, tabViewItem: tabViewItem)
}
}
override func keyDown(with theEvent: NSEvent) {
if theEvent.burnt_isSpaceKey {
// Just like QuickLook, use space to dismiss.
dismiss(nil)
}
}
}
extension SourcePreviewTabViewController: NSPopoverDelegate {
func popoverWillShow(_ notification: Notification) {
let popover = notification.object as! NSPopover
popover.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
//popover.appearance = NSAppearance(named: NSAppearanceNameLightContent)
//popover.appearance = .HUD
}
func popoverDidShow(_ notification: Notification) {
if let window = view.window , selectedTabViewItemIndex != -1 {
let tabViewItem = tabViewItems[selectedTabViewItemIndex]
let vc = tabViewItem.viewController as! SourcePreviewViewController
window.makeFirstResponder(vc.textView)
}
view.layoutSubtreeIfNeeded()
}
}
class SourcePreviewViewController: NSViewController {
@IBOutlet var textView: SourcePreviewTextView!
var wantsToDismiss: (() -> ())?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
textView.wantsToDismiss = wantsToDismiss
}
let defaultTextAttributes: [String: AnyObject] = [
convertFromNSAttributedStringKey(NSAttributedString.Key.font): NSFont(name: "Menlo", size: 11.0)!,
convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): NSColor.highlightColor
]
var sourceText: String! {
didSet {
_ = self.view // Make sure view has loaded
if let textStorage = textView.textStorage {
let attributes = defaultTextAttributes
let newAttributedString = NSAttributedString(string: sourceText, attributes:convertToOptionalNSAttributedStringKeyDictionary(attributes))
textStorage.replaceCharacters(in: NSMakeRange(0, textStorage.length), with: newAttributedString)
}
}
}
}
class SourcePreviewTextView: NSTextView {
var wantsToDismiss: (() -> ())?
override func keyDown(with theEvent: NSEvent) {
if theEvent.burnt_isSpaceKey {
wantsToDismiss?()
}
else {
super.keyDown(with: theEvent)
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
| apache-2.0 | e4ae38c13bf32a89de38a79a31eb683c | 26.497674 | 158 | 0.748816 | 4.140056 | false | false | false | false |
TZLike/GiftShow | GiftShow/GiftShow/Classes/ProductDetail/Model/LeeListDetailModel.swift | 1 | 839 | //
// LeeListDetailModel.swift
// GiftShow
//
// Created by admin on 16/11/3.
// Copyright © 2016年 Mr_LeeKi. All rights reserved.
//
import UIKit
class LeeListDetailModel:LeeBaseModel {
//描述
var des:String?
//网页地址
var detail_html:String?
var favorites_count:NSNumber = 0
var image_urls:[String]?
var likes_count:NSNumber = 0
var name:String?
var price:CGFloat = 0
var purchase_url:String?
var short_description:String?
init(dict:[String:NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if "description" == key {
self.des = value as! String?
}
super.setValue(value, forKey: key)
}
}
| apache-2.0 | acf2b05282692574b81244d9f755bbd2 | 19.6 | 63 | 0.570388 | 3.905213 | false | false | false | false |
Masteryyz/CSYMicroBlockSina | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/WelcomePage(欢迎页面)/NewfeatureCollectionViewController.swift | 1 | 6205 | //
// NewfeatureCollectionViewController.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/12.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class NewfeatureCollectionViewController: UICollectionViewController {
init(){
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSizeMake(screen_Width, screen_Height)
layout.scrollDirection = .Horizontal
super.init(collectionViewLayout:layout)
collectionView?.pagingEnabled = true
collectionView?.showsVerticalScrollIndicator = false
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.bounces = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(CSYCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return featureImageCount
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CSYCollectionViewCell
// Configure the cell
cell.backgroundColor = UIColor.redColor()
cell.index = indexPath.item
return cell
}
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
//print("-------->\(indexPath.item)")
if let cell = collectionView.visibleCells().last as? CSYCollectionViewCell {
let index : NSInteger = (collectionView.indexPathForCell(cell)?.row)!
//print("INDEX :: \(index)")
collectionView.subviews.last
if index == featureImageCount - 1{
cell.startAnimation()
}
}
}
// override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
//
// let page : NSInteger = NSInteger(scrollView.contentOffset.x / screen_Width)
//
// print(page)
//
// if page == featureImageCount - 1 {
//
// if let cell = collectionView?.visibleCells().last as? CSYCollectionViewCell {
//
// cell.startAnimation()
//
// }
//
// }
//
//
// }
}
class CSYCollectionViewCell : UICollectionViewCell{
var index : NSInteger = 0{
didSet{
startButton.hidden = true
newFeatureImage.image = UIImage(named: "new_feature_\(index + 1)")
}
}
func startAnimation (){
// self.startButton.hidden = false
startButton.transform = CGAffineTransformMakeScale(0, 0)
UIView.animateWithDuration(1.2, delay: 0.1, usingSpringWithDamping: 0.9, initialSpringVelocity: 9.0, options: [], animations: { () -> Void in
self.startButton.hidden = false
self.startButton.transform = CGAffineTransformMakeScale(1,1)
}) { (_) -> Void in
print("欢迎页载入完成")
}
}
func setUpUI(){
contentView.addSubview(newFeatureImage)
contentView.addSubview(startButton)
newFeatureImage.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(contentView.snp_edges)
}
startButton.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(contentView.snp_bottom).offset(-screen_Height * 0.3)
make.centerX.equalTo(contentView.snp_centerX).offset(0)
}
self.startButton.hidden = true
self.startButton.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
}
@objc func clickStartButton(){
NSNotificationCenter.defaultCenter().postNotificationName(APPDELEGATESHOULDSWITCHROOTVIEWCONTROLLER, object: "abc")
}
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var newFeatureImage : UIImageView = UIImageView()
lazy var startButton : UIButton = {
let btn = UIButton()
btn.setTitle("开始体验", forState: .Normal)
btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
return btn
}()
}
| mit | 4222c040de6335eee9d15c1763d945fb | 26.171806 | 160 | 0.588197 | 5.863118 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/examples/SwiftPlayground/Swift.playground/Pages/EarlyExit.xcplaygroundpage/Contents.swift | 1 | 2363 | /*: [Previous](@previous)
# Early Exit
A `guard` statement is used to perform validation or optional binding that must succeed in order for the function to continue. Like an `if` statement, a `guard` statement checks conditions or performs optional bindings. Unlike an `if` statement, there is always an `else` block of code that is required to transfer control to exit the block of code in which the `guard` statement appears (i.e., `return` or `throw` in a function, `continue` or `break` in a loop, etc.):
*/
func process(_ response: String, withStatus status: Int) -> Bool {
guard status >= 200 && status < 300 else {
print("Error response")
return false
}
print("Successful response")
return true
}
process("Unauthorized Response", withStatus: 401)
process("Successful Response", withStatus: 200)
func countCats(in animals: [String]?) -> Int {
guard let someAnimals = animals else {
return 0
}
var count = 0
for animal in someAnimals {
guard animal == "Cat" else {
continue
}
count += 1
}
return count
}
countCats(in: nil)
countCats(in: ["Cat", "Cat", "Goose"])
//: One typical issue that arises with exiting early is handling the cleanup of any resources that are being used prior to exiting (closing an input stream, releasing resources, etc.). Swift provides a mechanism for such cleanup so that it can be specified in a single place. This is done with a `defer` statement, which ensures that a particular block of code will always be run prior to exit:
import Foundation
func handleConnection(inputStream: InputStream) throws -> NSData {
inputStream.open()
defer {
inputStream.close()
}
let data = NSMutableData()
var buffer = Array<UInt8>(repeating: 0, count: 1024)
while inputStream.hasBytesAvailable {
let readByteCount = inputStream.read(&buffer, maxLength: buffer.count)
guard readByteCount != -1 else {
throw NSError(domain: "edu.uoregon.cs.cis399", code: 0, userInfo: nil)
// The defer block executes here prior to propogation of the thrown error
}
data.append(&buffer, length: buffer.count)
}
return data
// The defer block executes here prior to the return from the method
}
//: Note: If multiple defer blocks are present, they will be executed in reverse order that they appear in (i.e., the ones latest in the code block being exited will occur first).
//: [Next](@next)
| gpl-3.0 | d9d68862cbc474f61ea13f2b12cdce8d | 33.246377 | 471 | 0.727465 | 3.829822 | false | false | false | false |
i-schuetz/SwiftCharts | SwiftCharts/Layers/ChartPointsLineLayer.swift | 1 | 8603 | //
// ChartPointsLineLayer.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public enum LineJoin {
case miter
case round
case bevel
public var CALayerString: String {
switch self {
case .miter: return convertFromCAShapeLayerLineJoin(CAShapeLayerLineJoin.miter)
case .round: return convertFromCAShapeLayerLineCap(CAShapeLayerLineCap.round)
case .bevel: return convertFromCAShapeLayerLineJoin(CAShapeLayerLineJoin.bevel)
}
}
public var CGValue: CGLineJoin {
switch self {
case .miter: return .miter
case .round: return .round
case .bevel: return .bevel
}
}
}
public enum LineCap {
case butt
case round
case square
public var CALayerString: String {
switch self {
case .butt: return convertFromCAShapeLayerLineCap(CAShapeLayerLineCap.butt)
case .round: return convertFromCAShapeLayerLineCap(CAShapeLayerLineCap.round)
case .square: return convertFromCAShapeLayerLineCap(CAShapeLayerLineCap.square)
}
}
public var CGValue: CGLineCap {
switch self {
case .butt: return .butt
case .round: return .round
case .square: return .square
}
}
}
public struct ScreenLine<T: ChartPoint> {
public internal(set) var points: [CGPoint]
public let colors: [UIColor]
public let lineWidth: CGFloat
public let lineJoin: LineJoin
public let lineCap: LineCap
public let animDuration: Float
public let animDelay: Float
public let lineModel: ChartLineModel<T>
public let dashPattern: [Double]?
init(points: [CGPoint], colors: [UIColor], lineWidth: CGFloat, lineJoin: LineJoin, lineCap: LineCap, animDuration: Float, animDelay: Float, lineModel: ChartLineModel<T>, dashPattern: [Double]?) {
self.points = points
self.colors = colors
self.lineWidth = lineWidth
self.lineJoin = lineJoin
self.lineCap = lineCap
self.animDuration = animDuration
self.animDelay = animDelay
self.lineModel = lineModel
self.dashPattern = dashPattern
}
init(points: [CGPoint], color: UIColor, lineWidth: CGFloat, lineJoin: LineJoin, lineCap: LineCap, animDuration: Float, animDelay: Float, lineModel: ChartLineModel<T>, dashPattern: [Double]?) {
self.init(points: points, colors: [color], lineWidth: lineWidth, lineJoin: lineJoin, lineCap: lineCap, animDuration: animDuration, animDelay: animDelay, lineModel: lineModel, dashPattern: dashPattern)
}
}
open class ChartPointsLineLayer<T: ChartPoint>: ChartPointsLayer<T> {
open fileprivate(set) var lineModels: [ChartLineModel<T>]
open fileprivate(set) var lineViews: [ChartLinesView] = []
public let pathGenerator: ChartLinesViewPathGenerator
open fileprivate(set) var screenLines: [(screenLine: ScreenLine<T>, view: ChartLinesView)] = []
public let useView: Bool
public let delayInit: Bool
fileprivate var isInTransform = false
public init(xAxis: ChartAxis, yAxis: ChartAxis, lineModels: [ChartLineModel<T>], pathGenerator: ChartLinesViewPathGenerator = StraightLinePathGenerator(), displayDelay: Float = 0, useView: Bool = true, delayInit: Bool = false) {
self.lineModels = lineModels
self.pathGenerator = pathGenerator
self.useView = useView
self.delayInit = delayInit
let chartPoints: [T] = lineModels.flatMap{$0.chartPoints}
super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: chartPoints, displayDelay: displayDelay)
}
fileprivate func toScreenLine(lineModel: ChartLineModel<T>, chart: Chart) -> ScreenLine<T> {
return ScreenLine(
points: lineModel.chartPoints.map{chartPointScreenLoc($0)},
colors: lineModel.lineColors,
lineWidth: lineModel.lineWidth,
lineJoin: lineModel.lineJoin,
lineCap: lineModel.lineCap,
animDuration: lineModel.animDuration,
animDelay: lineModel.animDelay,
lineModel: lineModel,
dashPattern: lineModel.dashPattern
)
}
override open func display(chart: Chart) {
if !delayInit {
if useView {
initScreenLines(chart)
}
}
}
open func initScreenLines(_ chart: Chart) {
let screenLines = lineModels.map{toScreenLine(lineModel: $0, chart: chart)}
for screenLine in screenLines {
let lineView = generateLineView(screenLine, chart: chart)
lineViews.append(lineView)
lineView.isUserInteractionEnabled = false
chart.addSubviewNoTransform(lineView)
self.screenLines.append((screenLine, lineView))
}
}
open func generateLineView(_ screenLine: ScreenLine<T>, chart: Chart) -> ChartLinesView {
return ChartLinesView(
path: pathGenerator.generatePath(points: screenLine.points, lineWidth: screenLine.lineWidth),
frame: chart.contentView.bounds,
lineColors: screenLine.colors,
lineWidth: screenLine.lineWidth,
lineJoin: screenLine.lineJoin,
lineCap: screenLine.lineCap,
animDuration: isInTransform ? 0 : screenLine.animDuration,
animDelay: isInTransform ? 0 : screenLine.animDelay,
dashPattern: screenLine.dashPattern
)
}
override open func chartDrawersContentViewDrawing(context: CGContext, chart: Chart, view: UIView) {
if !useView {
for lineModel in lineModels {
let points = lineModel.chartPoints.map { modelLocToScreenLoc(x: $0.x.scalar, y: $0.y.scalar) }
let path = pathGenerator.generatePath(points: points, lineWidth: lineModel.lineWidth)
context.saveGState()
context.addPath(path.cgPath)
context.setLineWidth(lineModel.lineWidth)
context.setLineJoin(lineModel.lineJoin.CGValue)
context.setLineCap(lineModel.lineCap.CGValue)
context.setLineDash(phase: 0, lengths: lineModel.dashPattern?.map { CGFloat($0) } ?? [])
context.setStrokeColor(lineModel.lineColors.first?.cgColor ?? UIColor.white.cgColor)
context.strokePath()
context.restoreGState()
}
}
}
open override func modelLocToScreenLoc(x: Double) -> CGFloat {
return xAxis.screenLocForScalar(x) - (chart?.containerFrame.origin.x ?? 0)
}
open override func modelLocToScreenLoc(y: Double) -> CGFloat {
return yAxis.screenLocForScalar(y) - (chart?.containerFrame.origin.y ?? 0)
}
open override func zoom(_ scaleX: CGFloat, scaleY: CGFloat, centerX: CGFloat, centerY: CGFloat) {
if !useView {
chart?.drawersContentView.setNeedsDisplay()
}
}
open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) {
if !useView {
chart?.drawersContentView.setNeedsDisplay()
} else {
updateScreenLines()
}
}
open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) {
if !useView {
chart?.drawersContentView.setNeedsDisplay()
} else {
updateScreenLines()
}
}
fileprivate func updateScreenLines() {
guard let chart = chart else {return}
isInTransform = true
for i in 0..<screenLines.count {
for j in 0..<screenLines[i].screenLine.points.count {
let chartPoint = screenLines[i].screenLine.lineModel.chartPoints[j]
screenLines[i].screenLine.points[j] = modelLocToScreenLoc(x: chartPoint.x.scalar, y: chartPoint.y.scalar)
}
screenLines[i].view.removeFromSuperview()
screenLines[i].view = generateLineView(screenLines[i].screenLine, chart: chart)
chart.addSubviewNoTransform(screenLines[i].view)
}
isInTransform = false
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromCAShapeLayerLineJoin(_ input: CAShapeLayerLineJoin) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromCAShapeLayerLineCap(_ input: CAShapeLayerLineCap) -> String {
return input.rawValue
}
| apache-2.0 | 1f6119a4caadaba05c1c54b3e150a0f6 | 36.081897 | 232 | 0.644426 | 4.811521 | false | false | false | false |
lixiangzhou/ZZLib | Source/ZZCustom/ZZRefresh/ZZRefreshHeader.swift | 1 | 2213 | //
// ZZRefreshHeader.swift
// ZZRefresh
//
// Created by lixiangzhou on 16/10/27.
// Copyright © 2016年 lixiangzhou. All rights reserved.
//
import UIKit
open class ZZRefreshHeader: ZZRefreshView {
open override var state: ZZRefreshState {
didSet {
switch state {
case .refreshing:
UIView.animate(withDuration: zz_RefreshConstant.headerRefreshDuration, animations: {
self.scrollView.contentInset.top = zz_RefreshConstant.headerHeight
})
default: break
}
}
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let offsetY = scrollView.contentOffset.y
let width = scrollView.bounds.width
let headerHeight = zz_RefreshConstant.headerHeight
// 处理 style
switch style {
case .bottom:
frame = CGRect(x: 0, y: -headerHeight, width: width, height: headerHeight)
case .scaleToFill:
var height: CGFloat = min(headerHeight, abs(min(offsetY, 0)))
let y = min(offsetY, 0);
height = offsetY < 0 ? abs(offsetY) : 0
frame = CGRect(x: 0, y: y, width: width, height: height)
case .top:
let y = offsetY < -headerHeight ? offsetY : -headerHeight
frame = CGRect(x: 0, y: y, width: width, height: headerHeight)
}
// 处理状态变化
if offsetY > 0 || state == .refreshing {
return
}
if scrollView.isDragging {
if (state == .normal || state == .releaseRefreshing) && -offsetY < headerHeight {
state = .willRefreshing
} else if state == .willRefreshing && -offsetY >= headerHeight {
state = .releaseRefreshing
}
} else if state == .willRefreshing {
state = .normal
} else if state == .releaseRefreshing {
state = .refreshing
}
}
// 自定义刷新控件时重写此方法
open override func setupUI() { }
}
| mit | 2ec11341807a7240185998d0bcbb65ef | 31.848485 | 156 | 0.556273 | 4.743982 | false | false | false | false |
appone/GPUImage | examples/iOS/FilterShowcaseSwift/FilterShowcaseSwift/FilterListViewController.swift | 4 | 1273 | import UIKit
class FilterListViewController: UITableViewController {
var filterDisplayViewController: FilterDisplayViewController? = nil
var objects = NSMutableArray()
// #pragma mark - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
let filterInList = filterOperations[indexPath.row]
(segue.destinationViewController as FilterDisplayViewController).filterOperation = filterInList
}
}
// #pragma mark - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filterOperations.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let filterInList:FilterOperationInterface = filterOperations[indexPath.row]
cell.textLabel.text = filterInList.listName
return cell
}
}
| bsd-3-clause | 085fae17f0909020d2023ef6f6cf658e | 34.361111 | 118 | 0.723488 | 5.92093 | false | false | false | false |
Liaojiahao/JHNavigationBar | demo/JHNavBarHandle.swift | 2 | 1921 | //
// JHNavBarHandle.swift
//
// Created by JiaHao on 6/23/15.
// Copyright (c) 2015 JH. All rights reserved.
//
import UIKit
class JHNavBarHandle: NSObject {
class func handleJHNavigationBarAlpha(scroll:UIScrollView,uiviewcontoller:UIViewController){
uiviewcontoller.automaticallyAdjustsScrollViewInsets = false
var overlayColor = uiviewcontoller.navigationController?.navigationBar.overlayColor
var offsetY = scroll.contentOffset.y
if offsetY > 50{
let alpha = 1 - ((50+64-offsetY)/64)
uiviewcontoller.navigationController?.navigationBar.jh_setBackgroundColor(overlayColor!.colorWithAlphaComponent(alpha))
}else{
uiviewcontoller.navigationController?.navigationBar.jh_setBackgroundColor(overlayColor!.colorWithAlphaComponent(0))
}
}
class func handleJHNavigationBarHeight(scroll:UIScrollView,uiviewcontoller:UIViewController){
uiviewcontoller.automaticallyAdjustsScrollViewInsets = false
var offsetY = scroll.contentOffset.y
if offsetY > 0{
if(offsetY >= 44){
self.setNavigationBarTransformProgress(uiviewcontoller,progress: 1)
}else{
self.setNavigationBarTransformProgress(uiviewcontoller,progress: offsetY / 44)
}
}else{
self.setNavigationBarTransformProgress(uiviewcontoller,progress: 0)
uiviewcontoller.navigationController?.navigationBar.backIndicatorImage = nil
uiviewcontoller.navigationController?.navigationBar.backIndicatorTransitionMaskImage = nil
}
}
class func setNavigationBarTransformProgress(uiviewcontoller:UIViewController,progress:CGFloat){
uiviewcontoller.navigationController?.navigationBar.jh_setTranslationY(-44 * progress)
uiviewcontoller.navigationController?.navigationBar.jh_setContentAlpha(1-progress)
}
}
| mit | c5d9d954f4f83fae17e1a539dae0c233 | 42.659091 | 131 | 0.721499 | 5.263014 | false | false | false | false |
904388172/-TV | DouYuTV/DouYuTV/Classes/Tools/Common.swift | 1 | 315 | //
// Common.swift
// DouYuTV
//
// Created by GS on 2017/10/19.
// Copyright © 2017年 Demo. All rights reserved.
//
import UIKit
let kStatebarH: CGFloat = 20
let kNavigationBarH: CGFloat = 44
let kTabbarH: CGFloat = 49
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
| mit | 53d0d63db37aa51685c4519e0ab8d778 | 17.352941 | 48 | 0.714744 | 3.319149 | false | false | false | false |
YetiiNet/AuthenticationManager | AuthenticationManager/PINAuthenticationViewController.swift | 1 | 1684 | //
// PINAuthenticationViewController.swift
// AuthenticationManager
//
// Created by Joseph Duffy on 23/07/2014.
// Copyright (c) 2014 Yetii Ltd. All rights reserved.
//
import UIKit
/// A view controller used to manage the input of a PIN and check its validity
public class PINAuthenticationViewController: PINViewController, PINViewControllerDelegate {
public var PIN: String?
public var authenticationDelegate: PINAuthenticationDelegate?
override public func viewDidLoad() {
super.viewDidLoad()
if self.PIN == nil {
// PIN has not been explictly set, try to load it from the keychain
self.PIN = PINManager.sharedInstance.PIN
}
assert(self.PIN != nil, "Cannot load the PIN authentication view controller when no PIN has been set")
self.viewController.delegate = self
self.viewController.textLabel.text = "Enter your passcode"
self.title = "Enter Passcode"
}
public func PINWasInput(inputPIN: String) {
if self.PIN == nil {
// PIN is not set, alert the delegate that a PIN has been input
self.authenticationDelegate?.PINWasInput?(inputPIN)
} else {
// PIN has been set, check it
if inputPIN == self.PIN {
// Input PIN is correct
self.authenticationDelegate?.authenticationDidSucceed()
} else {
// Input PIN is incorrect, update the UI...
self.viewController.inputPINWasInvalid()
// ... and alert the delegate
self.authenticationDelegate?.inputPINWasIncorrect?(inputPIN)
}
}
}
}
| mit | bf5e5093d089630c483c881c0a0b0cf8 | 36.422222 | 110 | 0.633017 | 4.811429 | false | false | false | false |
OpenStreetMap-Monitoring/OsMoiOs | iOsmoTests/iOsmoTests.swift | 2 | 1238 | //
// iOsmoTests.swift
// iOsmoTests
//
// Created by Olga Grineva on 07/12/14.
// Copyright (c) 2014 Olga Grineva. All rights reserved.
//
import UIKit
import XCTest
import Foundation
class iOsmoTests: XCTestCase {
private var launched = false
let app = XCUIApplication()
override func setUp() {
super.setUp()
continueAfterFailure = false
launchIfNecessary()
}
private func launchIfNecessary() {
if !launched {
launched = true
app.launchArguments = ["https://osmo.mobi/g/xynspxrncxiodsoh"]
app.launchEnvironment = ["url":"https://osmo.mobi/g/xynspxrncxiodsoh"]
app.launch()
}
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-3.0 | 35b16398562bb827b49141c58e0f89f8 | 23.27451 | 111 | 0.587237 | 4.390071 | false | true | false | false |
gottesmm/swift | stdlib/public/SDK/Foundation/URL.swift | 4 | 61982 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// Keys used in the result of `URLResourceValues.thumbnailDictionary`.
@available(OSX 10.10, iOS 8.0, *)
public struct URLThumbnailSizeKey : RawRepresentable, Hashable {
public typealias RawValue = String
public init(rawValue: RawValue) { self.rawValue = rawValue }
private(set) public var rawValue: RawValue
/// Key for a 1024 x 1024 thumbnail image.
static public let none: URLThumbnailSizeKey = URLThumbnailSizeKey(rawValue: URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue)
public var hashValue: Int {
return rawValue.hashValue
}
}
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
fileprivate var _values: [URLResourceKey: Any]
fileprivate var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(OSX 10.11, iOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(OSX)
/// True if the resource is scriptable. Only applies to applications.
@available(OSX 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(OSX)
/// The array of Tag names.
public var tagNames: [String]? { return _get(.tagNamesKey) }
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(OSX)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(OSX 10.10, *)
public var quarantineProperties: [String : Any]? {
get {
let value = _values[.quarantinePropertiesKey]
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if value is NSNull {
return nil
} else {
return value as? [String : Any]
}
}
set {
// Use NSNull for nil, a special case for deleting quarantine
// properties
_set(.quarantinePropertiesKey, newValue: newValue ?? NSNull())
}
}
#endif
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
/// Total number of resources on the volume.
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
/// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// true if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// true if the volume format supports hard links.
public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) }
/// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) }
/// true if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) }
/// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// true if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// true if the volume can be renamed.
public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) }
/// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// true if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) }
/// true if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) }
/// true if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) }
/// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) }
/// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) }
/// true if the volume is stored on a local device.
public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) }
/// true if the volume is read-only.
public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName : String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) }
/// true if the volume is encrypted.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) }
/// true if the volume is the root filesystem.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) }
/// true if the volume supports transparent decompression of compressed files using decmpfs.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
/// true if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
/// true if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// true if data is being downloaded for this item.
public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// true if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// true if data is being uploaded for this item.
public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// returns the download status of this item.
public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// returns the name of this item's container as displayed to users.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
#if !os(OSX)
/// The protection level for this file
@available(iOS 9.0, *)
public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) }
#endif
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL : ReferenceConvertible, Equatable {
public typealias ReferenceType = NSURL
fileprivate var _url : NSURL
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String, relativeTo url: URL?) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string, relativeTo: url) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: String, isDirectory: Bool) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(OSX 10.11, iOS 9.0, *)
public init?(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) {
guard dataRepresentation.count > 0 else { return nil }
if isAbsolute {
_url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
} else {
_url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url))
}
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
public init?(resolvingBookmarkData data: Data, options: BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method.
@available(OSX 10.10, iOS 8.0, *)
public init(resolvingAliasFileAt url: URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: URL?) {
_url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL))
}
public var hashValue: Int {
return _url.hash
}
// MARK: -
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(OSX 10.11, iOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
// MARK: -
// Future implementation note:
// NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult.
// Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API.
/// Returns the absolute string for the URL.
public var absoluteString: String {
if let string = _url.absoluteString {
return string
} else {
// This should never fail for non-file reference URLs
return ""
}
}
/// The relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
if let url = _url.absoluteURL {
return url
} else {
// This should never fail for non-file reference URLs
return self
}
}
// MARK: -
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
// This thing was never really part of the URL specs
@available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead")
public var resourceSpecifier: String {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var host: String? {
return _url.host
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port?.intValue
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var user: String? {
return _url.user
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var password: String? {
return _url.password
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string.
///
/// If the URL contains a parameter string, it is appended to the path with a `;`.
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
public var path: String {
if let parameterString = _url.parameterString {
if let path = _url.path {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.path {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// If the URL contains a parameter string, it is appended to the path with a `;`.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
if let parameterString = _url.parameterString {
if let path = _url.relativePath {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.relativePath {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var fragment: String? {
return _url.fragment
}
@available(*, unavailable, message: "use the 'path' property")
public var parameterString: String? {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var query: String? {
return _url.query
}
/// Returns true if the URL path represents a directory.
@available(OSX 10.11, iOS 9.0, *)
public var hasDirectoryPath: Bool {
return _url.hasDirectoryPath
}
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
@available(OSX 10.9, iOS 7.0, *)
public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
return try block(_url.fileSystemRepresentation)
}
// MARK: -
// MARK: Path manipulation
/// Returns the path components of the URL, or an empty array if the path is an empty string.
public var pathComponents: [String] {
// In accordance with our above change to never return a nil path, here we return an empty array.
return _url.pathComponents ?? []
}
/// Returns the last path component of the URL, or an empty string if the path is an empty string.
public var lastPathComponent: String {
return _url.lastPathComponent ?? ""
}
/// Returns the path extension of the URL, or an empty string if the path is an empty string.
public var pathExtension: String {
return _url.pathExtension ?? ""
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL {
if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
return self
}
}
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public func appendingPathComponent(_ pathComponent: String) -> URL {
if let result = _url.appendingPathComponent(pathComponent) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
// Ultimate fallback:
return self
}
}
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingLastPathComponent() -> URL {
// This is a slight behavior change from NSURL, but better than returning "http://www.example.com../".
if path.isEmpty {
return self
}
if let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Returns a URL constructed by appending the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
///
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public func appendingPathExtension(_ pathExtension: String) -> URL {
if path.isEmpty {
return self
}
if let result = _url.appendingPathExtension(pathExtension) {
return result
} else {
return self
}
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingPathExtension() -> URL {
if path.isEmpty {
return self
}
if let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Appends a path component to the URL.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: Use `true` if the resulting path is a directory.
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) {
self = appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
/// Appends a path component to the URL.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public mutating func appendPathComponent(_ pathComponent: String) {
self = appendingPathComponent(pathComponent)
}
/// Appends the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public mutating func appendPathExtension(_ pathExtension: String) {
self = appendingPathExtension(pathExtension)
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deleteLastPathComponent() {
self = deletingLastPathComponent()
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deletePathExtension() {
self = deletingPathExtension()
}
/// Returns a `URL` with any instances of ".." or "." removed from its path.
public var standardized : URL {
// The NSURL API can only return nil in case of file reference URL, which we should not be
if let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func standardize() {
self = self.standardized
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public var standardizedFileURL : URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public func resolvingSymlinksInPath() -> URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func resolveSymlinksInPath() {
self = self.resolvingSymlinksInPath()
}
// MARK: - Reachability
/// Returns whether the URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
public func checkResourceIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkResourceIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
/// Returns whether the promised item URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
@available(OSX 10.10, iOS 8.0, *)
public func checkPromisedItemIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkPromisedItemIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
// MARK: - Resource Values
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
/// Get resource values from URLs of 'promised' items.
///
/// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently:
/// NSMetadataQueryUbiquitousDataScope
/// NSMetadataQueryUbiquitousDocumentsScope
/// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof
///
/// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true:
/// You are using a URL that you know came directly from one of the above APIs
/// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly
///
/// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.
@available(OSX 10.10, iOS 8.0, *)
public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys)))
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws {
fatalError()
}
// MARK: - Bookmarks and Alias Files
/// Returns bookmark data for the URL, created with specified options and resource values.
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
return result as Data
}
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? {
return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) }
}
/// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.
public static func writeBookmarkData(_ data : Data, to url: URL) throws {
// Options are unused
try NSURL.writeBookmarkData(data, to: url, options: 0)
}
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
let result = try NSURL.bookmarkData(withContentsOf: url)
return result as Data
}
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).
@available(OSX 10.7, iOS 8.0, *)
public func startAccessingSecurityScopedResource() -> Bool {
return _url.startAccessingSecurityScopedResource()
}
/// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.
@available(OSX 10.7, iOS 8.0, *)
public func stopAccessingSecurityScopedResource() {
_url.stopAccessingSecurityScopedResource()
}
// MARK: - Bridging Support
/// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions.
private static func _converted(from url: NSURL) -> NSURL {
// Future readers: file reference URL here is not the same as playgrounds "file reference"
if url.isFileReferenceURL() {
// Convert to a file path URL, or use an invalid scheme
return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL
} else {
return url
}
}
fileprivate init(reference: NSURL) {
_url = URL._converted(from: reference).copy() as! NSURL
}
private var reference : NSURL {
return _url
}
public static func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
}
extension URL : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURL {
return _url
}
public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool {
result = URL(reference: source)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL {
var result: URL?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension URL : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
}
extension NSURL : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URL)
}
}
extension URL : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
//===----------------------------------------------------------------------===//
// File references, for playgrounds.
//===----------------------------------------------------------------------===//
extension URL : _ExpressibleByFileReferenceLiteral {
public init(fileReferenceLiteralResourceName name: String) {
self = Bundle.main.url(forResource: name, withExtension: nil)!
}
}
public typealias _FileReferenceLiteralType = URL
| apache-2.0 | 9fb37b3b03bd8db09d92618be90f6bc4 | 50.608659 | 765 | 0.681811 | 4.989294 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyer/Pipeline/PublicPipelinesTableViewDataSource.swift | 1 | 1376 | import RxSwift
import RxDataSources
class PublicPipelinesTableViewDataSource: RxTableViewSectionedReloadDataSource<PipelineGroupSection>, UITableViewDelegate {
func setUp() {
configureCell = { (dataSource: TableViewSectionedDataSource<PipelineGroupSection>, tableView: UITableView, indexPath: IndexPath, item: PipelineGroupSection.Item) in
let pipeline = item
let cell = tableView.dequeueReusableCell(withIdentifier: PipelineTableViewCell.cellReuseIdentifier, for: indexPath) as! PipelineTableViewCell
cell.nameLabel?.text = pipeline.name
return cell
}
titleForHeaderInSection = { (dataSource: TableViewSectionedDataSource<PipelineGroupSection>, sectionIndex: Int) -> String in
let section = dataSource[sectionIndex]
if let teamName = section.items.first?.teamName {
return teamName
}
return "ungrouped"
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.contentView.backgroundColor = Style.Colors.logsBackground
headerView.textLabel?.font = Style.Fonts.regular(withSize: 18)
headerView.textLabel?.textColor = UIColor.white
}
}
}
| apache-2.0 | f5c9f2172530dbc75e5a34a336f93d96 | 40.69697 | 172 | 0.696221 | 5.905579 | false | false | false | false |
socialbanks/ios-wallet | SocialWallet/AppDelegate.swift | 1 | 6269 | //
// AppDelegate.swift
// Social Wallet
//
// Created by Mauricio de Oliveira on 5/2/15.
// Copyright (c) 2015 SocialBanks. All rights reserved.
//
import Foundation
import UIKit
import Parse
import Bolts
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
//private let fix = PFUser.hash() // here's the weird trick
var window: UIWindow?
var drawerController: MMDrawerController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Fabric
Fabric.with([Crashlytics()])
// Setting the settings
AppManager.sharedInstance.debugMode = false;
// UI settings
// removing navigation bar separator and shadow
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
UINavigationBar.appearance().shadowImage = UIImage()
UIApplication.sharedApplication().statusBarStyle = .LightContent
// Initializing Parse
Parse.enableLocalDatastore()
Parse.setApplicationId("bCOd9IKjrpxCPGYQfyagabirn7pYFjYTvJqkq1x1", clientKey: "ug8CJXOxrkKZXlHIGKYAMaINXX9gCb1kwMgMr0ye")
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
// Registering subclasses
SocialBank.registerSubclass()
Wallet.registerSubclass()
Transaction.registerSubclass()
// Checking current logged user:
if( PFUser.currentUser() != nil ) {
AppManager.sharedInstance.userLocalData = UserLocalData(parseId: PFUser.currentUser()!.objectId!)
if AppManager.sharedInstance.userLocalData!.secret != nil {
AppManager.sharedInstance.userLocalData!.generatePrivateAddressWithSecret()
self.showMenu(false)
} else {
let alert = UIAlertView(title: "Error"
, message: "Your private key was not found in this device. You have been logged out. Log in again and redeem your wallet with your 24 words."
, delegate: nil
, cancelButtonTitle: "Ok")
alert.show()
PFUser.logOut() // Force user to log in again - error with his address
}
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func showAuhtentication(animated: Bool) {
let storyboard = UIStoryboard(name: "Authentication", bundle: nil);
let navVC = storyboard.instantiateInitialViewController() as! UINavigationController
UIApplication.sharedApplication().statusBarStyle = .LightContent
if (animated) {
UIView.transitionFromView(self.window!.rootViewController!.view, toView: navVC.view, duration: 0.65, options:UIViewAnimationOptions.TransitionCrossDissolve , completion: {(fininshed: Bool) -> () in
self.window!.rootViewController = navVC
self.window?.makeKeyAndVisible()
})
} else {
self.window!.rootViewController = navVC
self.window?.makeKeyAndVisible()
}
}
func showMenu(animated: Bool) {
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let leftDrawer = storyboard.instantiateViewControllerWithIdentifier("DrawerMenu") as! UITableViewController;
let center = storyboard.instantiateViewControllerWithIdentifier("SocialBankPickerNavigationController") as! UINavigationController;
self.drawerController = MMDrawerController(centerViewController: center, leftDrawerViewController: leftDrawer)
drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.All
drawerController?.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.All
drawerController?.maximumLeftDrawerWidth = 210
UIApplication.sharedApplication().statusBarStyle = .LightContent
if (animated) {
UIView.transitionFromView(self.window!.rootViewController!.view, toView: drawerController!.view, duration: 0.65, options:UIViewAnimationOptions.TransitionCrossDissolve , completion: {(fininshed: Bool) -> () in
self.window!.rootViewController = self.drawerController!
self.window?.makeKeyAndVisible()
})
} else {
self.window!.rootViewController = self.drawerController!
self.window?.makeKeyAndVisible()
}
}
}
| mit | 758123c06015f534a9bc3a0fd8b23c43 | 44.759124 | 285 | 0.683522 | 5.730347 | false | false | false | false |
vgorloff/AUHost | Vendor/mc/mcxUI/Sources/Sources/SystemAppearance.swift | 1 | 2161 | //
// SystemAppearance.swift
// MCA-OSS-VSTNS;MCA-OSS-AUH
//
// Created by Vlad Gorlov on 09.08.18.
// Copyright © 2018 Vlad Gorlov. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
@objc public enum SystemAppearance: Int, CaseIterable, CustomStringConvertible {
case light, highContrastLight
case dark, highContrastDark
#if os(OSX)
@available(OSX 10.14, *)
public init?(name: NSAppearance.Name) {
if let value = SystemAppearance.allCases.first(where: { $0.name == name }) {
self = value
} else {
return nil
}
}
#endif
public init?(serializedValue: String) {
if let value = SystemAppearance.allCases.first(where: { $0.serializedValue == serializedValue }) {
self = value
} else {
return nil
}
}
// MARK: -
public var isDark: Bool {
switch self {
case .dark, .highContrastDark:
return true
case .light, .highContrastLight:
return false
}
}
public var isLight: Bool {
return !isDark
}
public var isHighContrast: Bool {
switch self {
case .highContrastLight, .highContrastDark:
return true
case .light, .dark:
return false
}
}
public var description: String {
return serializedValue
}
public var serializedValue: String {
switch self {
case .dark:
return "dark"
case .light:
return "light"
case .highContrastDark:
return "highContrastDark"
case .highContrastLight:
return "highContrastLight"
}
}
#if os(OSX)
@available(OSX 10.14, *)
public var name: NSAppearance.Name {
switch self {
case .dark:
return .darkAqua
case .light:
return .aqua
case .highContrastDark:
return .accessibilityHighContrastDarkAqua
case .highContrastLight:
return .accessibilityHighContrastAqua
}
}
@available(OSX 10.14, *)
public var appearance: NSAppearance? {
return NSAppearance(named: name)
}
#endif
}
| mit | 787a46bd3058fbc770c33782662945f2 | 20.6 | 104 | 0.601852 | 4.029851 | false | false | false | false |
rudkx/swift | test/Concurrency/async_main_resolution.swift | 1 | 2364 | // Non-apple platforms don't need to worry about the version number as much
// because they can pull in the concurrency libraries with the swift
// installation.
// async main is nested deeper in protocols than sync, use sync
// sync main is nested deeper in protocols than async, use async
// async and sync are same level, use async
// REQUIRES: rdar89500797
// REQUIRES: concurrency
// UNSUPPORTED: VENDOR=apple
// Async is deeper in the protocol chain from `MyMain`, use sync
// RUN: %target-swift-frontend -DASYNC_NESTED -DINHERIT_SYNC -typecheck -dump-ast -parse-as-library %s | %FileCheck %s --check-prefix=CHECK-IS-SYNC
// Sync is deeper in the protocol chain from `MyMain`, use async
// RUN: %target-swift-frontend -typecheck -dump-ast -parse-as-library %s | %FileCheck %s --check-prefix=CHECK-IS-ASYNC
// Async and sync are the same level, use async
// RUN: %target-swift-frontend -DBOTH -DINHERIT_SYNC -typecheck -dump-ast -parse-as-library %s | %FileCheck %s --check-prefix=CHECK-IS-ASYNC
#if ASYNC_NESTED
protocol AsyncMainProtocol { }
protocol MainProtocol : AsyncMainProtocol { }
#else
protocol MainProtocol { }
protocol AsyncMainProtocol : MainProtocol { }
#endif
#if NO_SYNC
#else
extension MainProtocol {
static func main() { }
}
#endif
#if NO_ASYNC
#else
extension AsyncMainProtocol {
static func main() async { }
}
#endif
#if BOTH
extension MainProtocol {
static func main() async { }
}
#endif
#if INHERIT_SYNC
@main struct MyMain : MainProtocol {}
#else
@main struct MyMain : AsyncMainProtocol {}
#endif
// CHECK-IS-SYNC-LABEL: "MyMain" interface type='MyMain.Type'
// CHECK-IS-SYNC: (func_decl implicit "$main()" interface type='(MyMain.Type) -> () -> ()'
// CHECK-IS-SYNC: (declref_expr implicit type='(MyMain.Type) -> () -> ()'
// CHECK-IS-ASYNC-LABEL: "MyMain" interface type='MyMain.Type'
// CHECK-IS-ASYNC: (func_decl implicit "$main()" interface type='(MyMain.Type) -> () async -> ()'
// CHECK-IS-ASYNC: (declref_expr implicit type='(MyMain.Type) -> () async -> ()'
// CHECK-IS-ERROR: error: 'MyMain' is annotated with @main and must provide a main static function of type () -> Void or () throws -> Void
// CHECK-IS-ERROR-ASYNC: error: 'MyMain' is annotated with @main and must provide a main static function of type () -> Void, () throws -> Void, () async -> Void, or () async throws -> Void
| apache-2.0 | f5ff4f2f94a5e15da7cbb5a5b7351579 | 32.771429 | 188 | 0.701777 | 3.466276 | false | false | false | false |
306244907/Weibo | JLSina/JLSina/Classes/View(视图和控制器)/Home/TitleButton/JLTitleButton.swift | 1 | 1695 | //
// JLTitleButton.swift
// JLSina
//
// Created by 盘赢 on 2017/11/13.
// Copyright © 2017年 JinLong. All rights reserved.
//
import UIKit
class JLTitleButton: UIButton {
//重载构造函数
//title 如果是 nil,就显示首页,
//如果不为nil,显示昵称和箭头图像
init(title: String?) {
super.init(frame: CGRect())
//1,判断title是否为nil
if title == nil {
setTitle("首页", for: [])
} else {
setTitle(title! + " ", for: [])
//设置图像
setImage(UIImage.init(named: "navigationbar_arrow_down"), for: [])
setImage(UIImage.init(named: "navigationbar_arrow_up"), for: .selected)
}
//2,设置字体和颜色
titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
setTitleColor(UIColor.darkGray, for: [])
//3,设置大小
sizeToFit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//FIXME: 导航图片第一次右移
//重新布局子视图
override func layoutSubviews() {
super.layoutSubviews()
guard let titleLabel = titleLabel ,
let imageView = imageView else {
return
}
print("\(titleLabel),\(imageView)")
//将label的x向左移动imageView的宽度,
//OC中不允许直接修改结构体内部的值
//Swift可以直接修改
titleLabel.frame.origin.x = 0
//将imageView的x向右移动label的宽度
imageView.frame.origin.x = titleLabel.bounds.width
}
}
| mit | 51baf1bb1b46fa4b901e094cd81b1e46 | 23.949153 | 83 | 0.553668 | 4.055096 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.