repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
sharath-cliqz/browser-ios
Utils/AuthenticationKeychainInfo.swift
2
7159
/* 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 SwiftKeychainWrapper // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } public let KeychainKeyAuthenticationInfo = "authenticationInfo" public let AllowedPasscodeFailedAttempts = 3 // Passcode intervals with rawValue in seconds. public enum PasscodeInterval: Int { case immediately = 0 case oneMinute = 60 case fiveMinutes = 300 case tenMinutes = 600 case fifteenMinutes = 900 case oneHour = 3600 } let baseBundleIdentifier = AppInfo.baseBundleIdentifier()! //let accessGroupPrefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as! String //let accessGroupIdentifier = AppInfo.keychainAccessGroupWithPrefix(accessGroupPrefix)! private var sharedAppKeychainWrapper = KeychainWrapper(serviceName: baseBundleIdentifier, accessGroup: nil) // MARK: - Helper methods for accessing Authentication information from the Keychain public extension KeychainWrapper { static var sharedAppContainerKeychain: KeychainWrapper { return sharedAppKeychainWrapper } func authenticationInfo() -> AuthenticationKeychainInfo? { NSKeyedUnarchiver.setClass(AuthenticationKeychainInfo.self, forClassName: "AuthenticationKeychainInfo") return KeychainWrapper.standard.object(forKey: KeychainKeyAuthenticationInfo) as? AuthenticationKeychainInfo // return KeychainWrapper.objectForKey(KeychainKeyAuthenticationInfo) as? AuthenticationKeychainInfo } func setAuthenticationInfo(_ info: AuthenticationKeychainInfo?) { NSKeyedArchiver.setClassName("AuthenticationKeychainInfo", for: AuthenticationKeychainInfo.self) if let info = info { KeychainWrapper.standard.set(info, forKey: KeychainKeyAuthenticationInfo) // KeychainWrapper.setObject(info, forKey: KeychainKeyAuthenticationInfo) } else { KeychainWrapper.standard.removeObject(forKey: KeychainKeyAuthenticationInfo) // KeychainWrapper.removeObjectForKey(KeychainKeyAuthenticationInfo) } } } open class AuthenticationKeychainInfo: NSObject, NSCoding { fileprivate(set) open var lastPasscodeValidationInterval: TimeInterval? fileprivate(set) open var passcode: String? fileprivate(set) open var requiredPasscodeInterval: PasscodeInterval? fileprivate(set) open var lockOutInterval: TimeInterval? fileprivate(set) open var failedAttempts: Int open var useTouchID: Bool // Timeout period before user can retry entering passcodes open var lockTimeInterval: TimeInterval = 15 * 60 public init(passcode: String) { self.passcode = passcode self.requiredPasscodeInterval = .immediately self.failedAttempts = 0 self.useTouchID = false } open func encode(with aCoder: NSCoder) { if let lastPasscodeValidationInterval = lastPasscodeValidationInterval { let interval = NSNumber(value: lastPasscodeValidationInterval as Double) aCoder.encode(interval, forKey: "lastPasscodeValidationInterval") } if let lockOutInterval = lockOutInterval, isLocked() { let interval = NSNumber(value: lockOutInterval as Double) aCoder.encode(interval, forKey: "lockOutInterval") } aCoder.encode(passcode, forKey: "passcode") aCoder.encode(requiredPasscodeInterval?.rawValue, forKey: "requiredPasscodeInterval") aCoder.encode(failedAttempts, forKey: "failedAttempts") aCoder.encode(useTouchID, forKey: "useTouchID") } public required init?(coder aDecoder: NSCoder) { self.lastPasscodeValidationInterval = (aDecoder.decodeObject(forKey: "lastPasscodeValidationInterval") as? NSNumber)?.doubleValue self.lockOutInterval = (aDecoder.decodeObject(forKey: "lockOutInterval") as? NSNumber)?.doubleValue self.passcode = aDecoder.decodeObject(forKey: "passcode") as? String self.failedAttempts = aDecoder.decodeInteger(forKey: "failedAttempts") self.useTouchID = aDecoder.decodeBool(forKey: "useTouchID") if let interval = aDecoder.decodeObject(forKey: "requiredPasscodeInterval") as? NSNumber { self.requiredPasscodeInterval = PasscodeInterval(rawValue: interval.intValue) } } } // MARK: - API public extension AuthenticationKeychainInfo { fileprivate func resetLockoutState() { self.failedAttempts = 0 self.lockOutInterval = nil } func updatePasscode(_ passcode: String) { self.passcode = passcode self.lastPasscodeValidationInterval = nil } func updateRequiredPasscodeInterval(_ interval: PasscodeInterval) { self.requiredPasscodeInterval = interval self.lastPasscodeValidationInterval = nil } func recordValidation() { // Save the timestamp to remember the last time we successfully // validated and clear out the failed attempts counter. self.lastPasscodeValidationInterval = SystemUtils.systemUptime() resetLockoutState() } func lockOutUser() { self.lockOutInterval = SystemUtils.systemUptime() } func recordFailedAttempt() { if (self.failedAttempts >= AllowedPasscodeFailedAttempts) { //This is a failed attempt after a lockout period. Reset the lockout state //This prevents failedAttemps from being higher than 3 self.resetLockoutState() } self.failedAttempts += 1 } func isLocked() -> Bool { guard self.lockOutInterval != nil else { return false } if SystemUtils.systemUptime() < self.lockOutInterval { // Unlock and require passcode input resetLockoutState() return false } return (SystemUtils.systemUptime() - (self.lockOutInterval ?? 0)) < lockTimeInterval } func requiresValidation() -> Bool { // If there isn't a passcode, don't need validation. guard let _ = passcode else { return false } // Need to make sure we've validated in the past. If not, its a definite yes. guard let lastValidationInterval = lastPasscodeValidationInterval, let requireInterval = requiredPasscodeInterval else { return true } // We've authenticated before so lets see how long since. If the uptime is less than the last validation stamp, // we probably restarted which means we should require validation. return SystemUtils.systemUptime() - lastValidationInterval > Double(requireInterval.rawValue) || SystemUtils.systemUptime() < lastValidationInterval } }
mpl-2.0
88f36e90b18e519b0d9919cd82176ed7
38.772222
137
0.707501
5.006294
false
false
false
false
benlangmuir/swift
test/SILGen/toplevel_globalactorvars.swift
9
5238
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -disable-availability-checking -enable-experimental-async-top-level %s | %FileCheck %s // a // CHECK-LABEL: sil_global hidden @$s24toplevel_globalactorvars1aSivp : $Int // CHECK-LABEL: sil hidden [ossa] @async_Main // CHECK: bb0: // CHECK-NEXT: // function_ref // CHECK-NEXT: [[GET_MAIN:%.*]] = function_ref @swift_task_getMainExecutor // CHECK-NEXT: [[MAIN:%.*]] = apply [[GET_MAIN]]() // CHECK-NEXT: [[MAIN_OPTIONAL:%[0-9]+]] = enum $Optional<Builtin.Executor>, #Optional.some!enumelt, [[MAIN]] actor MyActorImpl {} @globalActor struct MyActor { static let shared = MyActorImpl() } var a = 10 // a initialization // CHECK: alloc_global @$s24toplevel_globalactorvars1aSivp // CHECK: [[AREF:%[0-9]+]] = global_addr @$s24toplevel_globalactorvars1aSivp // CHECK: [[TEN_LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 10 // CHECK: [[INT_TYPE:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[INT_INIT:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC // CHECK: [[TEN:%[0-9]+]] = apply [[INT_INIT]]([[TEN_LIT]], [[INT_TYPE]]) // CHECK: store [[TEN]] to [trivial] [[AREF]] @MyActor func printFromMyActor(value : Int) { print(value) } print(a) // print // CHECK-NOT: hop_to_executor // CHECK: [[AACCESS:%[0-9]+]] = begin_access [read] [dynamic] [[AREF]] : $*Int // CHECK: [[AGLOBAL:%[0-9]+]] = load [trivial] [[AACCESS]] : $*Int // CHECK: end_access [[AACCESS]] // CHECK-NOT: hop_to_executor a += 1 // CHECK: [[ONE_LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 1 // CHECK: [[INT_TYPE:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[INT_INIT:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC // CHECK: [[ONE:%[0-9]+]] = apply [[INT_INIT]]([[ONE_LIT]], [[INT_TYPE]]) // CHECK-NOT: hop_to_executor // CHECK: [[AACCESS:%[0-9]+]] = begin_access [modify] [dynamic] [[AREF]] : $*Int // static Int.+= infix(_:_:) // CHECK: [[PE_INT_FUNC:%[0-9]+]] = function_ref @$sSi2peoiyySiz_SitFZ // CHECK: [[INCREMENTED:%[0-9]+]] = apply [[PE_INT_FUNC]]([[AACCESS]], [[ONE]], {{%[0-9]+}}) // CHECK: end_access [[AACCESS]] // CHECK-NOT: hop_to_executor await printFromMyActor(value: a) // CHECK: [[AACCESS:%[0-9]+]] = begin_access [read] [dynamic] [[AREF]] : $*Int // CHECK: [[AGLOBAL:%[0-9]+]] = load [trivial] [[AACCESS]] : $*Int // CHECK: end_access [[AACCESS]] // CHECK: [[PRINTFROMMYACTOR_FUNC:%[0-9]+]] = function_ref @$s24toplevel_globalactorvars16printFromMyActor5valueySi_tF // CHECK: [[ACTORREF:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $MyActorImpl // CHECK: hop_to_executor [[ACTORREF]] : $MyActorImpl // CHECK: {{%[0-9]+}} = apply [[PRINTFROMMYACTOR_FUNC]]([[AGLOBAL]]) // CHECK: hop_to_executor [[MAIN_OPTIONAL]] // CHECK: end_borrow [[ACTORREF]] if a < 10 { // CHECK: [[AACCESS:%[0-9]+]] = begin_access [read] [dynamic] [[AREF]] : $*Int // CHECK: [[AGLOBAL:%[0-9]+]] = load [trivial] [[AACCESS]] : $*Int // CHECK: end_access [[AACCESS]] // CHECK: [[TEN_LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 10 // CHECK: [[INT_TYPE:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[INT_INIT:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC // CHECK: [[TEN:%[0-9]+]] = apply [[INT_INIT]]([[TEN_LIT]], [[INT_TYPE]]) // function_ref static Swift.Int.< infix(Swift.Int, Swift.Int) -> Swift.Bool // CHECK: [[LESS_FUNC:%[0-9]+]] = function_ref @$sSi1loiySbSi_SitFZ // CHECK: [[WRAPPED_COND:%[0-9]+]] = apply [[LESS_FUNC]]([[AGLOBAL]], [[TEN]], {{%[0-9]+}}) // CHECK: [[COND:%[0-9]+]] = struct_extract [[WRAPPED_COND]] // CHECK: cond_br [[COND]], bb1, bb2 // CHECK: bb1: print(a) // print // CHECK-NOT: hop_to_executor // CHECK: [[AACCESS:%[0-9]+]] = begin_access [read] [dynamic] [[AREF]] : $*Int // CHECK: [[AGLOBAL:%[0-9]+]] = load [trivial] [[AACCESS]] : $*Int // CHECK: end_access [[AACCESS]] // CHECK-NOT: hop_to_executor a += 1 // CHECK: [[ONE_LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 1 // CHECK: [[INT_TYPE:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[INT_INIT:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC // CHECK: [[ONE:%[0-9]+]] = apply [[INT_INIT]]([[ONE_LIT]], [[INT_TYPE]]) // CHECK-NOT: hop_to_executor // CHECK: [[AACCESS:%[0-9]+]] = begin_access [modify] [dynamic] [[AREF]] : $*Int // static Int.+= infix(_:_:) // CHECK: [[PE_INT_FUNC:%[0-9]+]] = function_ref @$sSi2peoiyySiz_SitFZ // CHECK: [[INCREMENTED:%[0-9]+]] = apply [[PE_INT_FUNC]]([[AACCESS]], [[ONE]], {{%[0-9]+}}) // CHECK: end_access [[AACCESS]] // CHECK-NOT: hop_to_executor await printFromMyActor(value: a) // CHECK: [[AACCESS:%[0-9]+]] = begin_access [read] [dynamic] [[AREF]] : $*Int // CHECK: [[AGLOBAL:%[0-9]+]] = load [trivial] [[AACCESS]] : $*Int // CHECK: end_access [[AACCESS]] // CHECK: [[PRINTFROMMYACTOR_FUNC:%[0-9]+]] = function_ref @$s24toplevel_globalactorvars16printFromMyActor5valueySi_tF // CHECK: [[ACTORREF:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $MyActorImpl // CHECK: hop_to_executor [[ACTORREF]] : $MyActorImpl // CHECK: {{%[0-9]+}} = apply [[PRINTFROMMYACTOR_FUNC]]([[AGLOBAL]]) // CHECK: hop_to_executor [[MAIN_OPTIONAL]] // CHECK: end_borrow [[ACTORREF]] }
apache-2.0
a8eafbadf9713bb2b3f454ec139107cb
40.244094
146
0.600038
3
false
false
false
false
goto10/Vapor-FileMaker
Sources/FMSConnector/FMPResultSet.swift
1
6194
// // FMPResultSet.swift // PerfectFileMaker // // Created by Kyle Jessup on 2016-08-03. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectXML let fmrs = "fmrs" let fmrsNamespaces = [(fmrs, "http://www.filemaker.com/xml/fmresultset")] let fmrsErrorCode = "/\(fmrs):fmresultset/\(fmrs):error/@code" let fmrsResultSet = "/\(fmrs):fmresultset/\(fmrs):resultset" let fmrsMetaData = "/\(fmrs):fmresultset/\(fmrs):metadata" let fmrsDataSource = "/\(fmrs):fmresultset/\(fmrs):datasource" let fmrsFieldDefinition = "field-definition" let fmrsRelatedSetDefinition = "relatedset-definition" let fmrsRecord = "record" let fmrsField = "field" let fmrsRelatedSet = "relatedset" let fmrsData = "\(fmrs):data/text()" /// A returned FileMaker field value. public enum FMPFieldValue: CustomStringConvertible { /// A text field. case text(String) /// A numeric field. case number(Double) /// A container field. case container(String) /// A date field. case date(String) /// A time field. case time(String) /// A timestamp field. case timestamp(String) init(value: String, type: FMPFieldType) { switch type { case .number: self = .number(Double(value) ?? 0.0) case .container: self = .container(value) case .date: self = .date(value) case .time: self = .time(value) case .timestamp: self = .timestamp(value) case .text: self = .text(value) } } /// Returns the field value converted to String public var description: String { switch self { case .text(let s): return s case .number(let s): return String(s) case .container(let s): return s case .date(let s): return s case .time(let s): return s case .timestamp(let s): return s } } } /// Meta-information for a database. public struct FMPDatabaseInfo { /// The date format indicated by the server. public let dateFormat: String /// The time format indicated by the server. public let timeFormat: String /// The timestamp format indicated by the server. public let timeStampFormat: String /// The total number of records in the database. public let recordCount: Int init(node: XElement) { dateFormat = node.getAttribute(name: "date-format") ?? "MM/dd/yyyy" timeFormat = node.getAttribute(name: "time-format") ?? "HH:mm:ss" timeStampFormat = node.getAttribute(name: "timestamp-format") ?? "MM/dd/yyyy HH:mm:ss" recordCount = Int(node.getAttribute(name: "total-count") ?? "0") ?? 0 } } /// An individual result set record. public struct FMPRecord { /// A type of record item. public enum RecordItem { /// An individual field. case field(String, FMPFieldValue) /// A related set containing a list of related records. case relatedSet(String, [FMPRecord]) init(node: XElement, fieldTypes: [String:FMPFieldType]) { let name: String if node.nodeName == fmrsField { name = node.getAttribute(name: "name") ?? "" } else { name = node.getAttribute(name: "table") ?? "" } let type = fieldTypes[name] ?? .text if node.nodeName == fmrsField { let data = node.getElementsByTagName("data").first self = .field(name, FMPFieldValue(value: data?.nodeValue ?? "", type: type)) } else { self = .relatedSet(name, node.childElements.map { FMPRecord(node: $0, fieldTypes: fieldTypes) }) } } // this can only be field init(setName: String, node: XElement, fieldTypes: [String:FMPFieldType]) { let name = node.getAttribute(name: "name") ?? "" let type = fieldTypes[setName + "::" + name] ?? .text let data = node.getElementsByTagName("data").first self = .field(name, FMPFieldValue(value: data?.nodeValue ?? "", type: type)) } } /// The record id. public let recordId: Int /// The contained record items keyed by name. public let elements: [String:RecordItem] init(node: XElement, fieldTypes: [String:FMPFieldType]) { self.recordId = Int(node.getAttribute(name: "record-id") ?? "-1") ?? -1 var elements = [String:RecordItem]() for e in node.childElements { let item = RecordItem(node: e, fieldTypes: fieldTypes) let name: String switch item { case .field(let n, _): name = n case .relatedSet(let n, _): name = n } elements[name] = item } self.elements = elements } init(setName: String, node: XElement, fieldTypes: [String:FMPFieldType]) { self.recordId = Int(node.getAttribute(name: "record-id") ?? "-1") ?? -1 var elements = [String:RecordItem]() for e in node.childElements { let item = RecordItem(setName: setName, node: e, fieldTypes: fieldTypes) let name: String switch item { case .field(let n, _): name = n case .relatedSet(let n, _): // inconceivable! name = n } elements[name] = item } self.elements = elements } } /// The result set produced by a query. public struct FMPResultSet { /// Database meta-info. public let databaseInfo: FMPDatabaseInfo /// Layout meta-info. public let layoutInfo: FMPLayoutInfo /// The number of records found by the query. public let foundCount: Int /// The list of records produced by the query. public let records: [FMPRecord] init?(doc: XDocument) { guard let databaseNode = doc.extractOne(path: fmrsDataSource, namespaces: fmrsNamespaces) as? XElement, let metaDataNode = doc.extractOne(path: fmrsMetaData, namespaces: fmrsNamespaces) as? XElement, let resultSetNode = doc.extractOne(path: fmrsResultSet, namespaces: fmrsNamespaces) as? XElement else { return nil } self.databaseInfo = FMPDatabaseInfo(node: databaseNode) self.layoutInfo = FMPLayoutInfo(node: metaDataNode) self.foundCount = Int(resultSetNode.getAttribute(name: "count") ?? "") ?? 0 let fieldTypes = self.layoutInfo.fieldsByName self.records = resultSetNode.childElements.map { FMPRecord(node: $0, fieldTypes: fieldTypes) } } }
apache-2.0
4c1aebe9a1a89a9e627435b6d604525d
29.81592
106
0.67081
3.362649
false
false
false
false
adrfer/swift
test/DebugInfo/argument.swift
4
2210
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | FileCheck %s func markUsed<T>(t: T) {} // CHECK-DAG: !DILocalVariable(name: "arg", arg: 1,{{.*}} line: [[@LINE+1]] func a(arg : Int64) { // CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]] var local = arg } // CHECK-DAG: !DILocalVariable(name: "a", arg: 1,{{.*}} line: [[@LINE+3]] // CHECK-DAG: !DILocalVariable(name: "b", arg: 2,{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "c", arg: 3,{{.*}} line: [[@LINE+1]] func many(a: Int64, b: (Int64, Int64), c: Int64) -> Int64 { // CHECK-DAG: !DILocalVariable(name: "i1",{{.*}} line: [[@LINE+1]] var i1 = a // CHECK-DAG: !DILocalVariable(name: "i2",{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "i3",{{.*}} line: [[@LINE+1]] var (i2, i3) : (Int64, Int64) = b // CHECK-DAG: !DILocalVariable(name: "i4",{{.*}} line: [[@LINE+1]] var i4 = c return i1+i2+i3+i4 } class A { var member : Int64 // CHECK-DAG: !DILocalVariable(name: "a", arg: 1,{{.*}} line: [[@LINE+1]] init(a: Int64) { member = a } // CHECK-DAG: !DILocalVariable(name: "offset", arg: 1,{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "self", arg: 2,{{.*}} line: [[@LINE+1]] func getValuePlus(offset: Int64) -> Int64 { // CHECK-DAG: !DILocalVariable(name: "a",{{.*}} line: [[@LINE+1]] var a = member return a+offset } // CHECK-DAG: !DILocalVariable(name: "factor", arg: 1,{{.*}} line: [[@LINE+3]] // CHECK-DAG: !DILocalVariable(name: "offset", arg: 2,{{.*}} line: [[@LINE+2]] // CHECK-DAG: !DILocalVariable(name: "self", arg: 3,{{.*}} line: [[@LINE+1]] func getValueTimesPlus(factor: Int64, offset: Int64) -> Int64 { // CHECK-DAG: !DILocalVariable(name: "a",{{.*}} line: [[@LINE+1]] var a = member // CHECK-DAG: !DILocalVariable(name: "f",{{.*}} line: [[@LINE+1]] var f = factor return a*f+offset } // CHECK: !DILocalVariable(name: "self", arg: 1,{{.*}} line: [[@LINE+1]] deinit { markUsed(member) } } // CHECK: !DILocalVariable(name: "x", arg: 1,{{.*}} line: [[@LINE+2]] // CHECK: !DILocalVariable(name: "y", arg: 2,{{.*}} line: [[@LINE+1]] func tuple(x: Int64, y: (Int64, Float, String)) -> Int64 { return x+y.0 }
apache-2.0
b364e6718b129d7fbeddf65ca687c23f
35.229508
79
0.572398
2.896461
false
false
false
false
deepindo/DDLive
DDLive/DDLive/Librarys/TGPageView/TGPageCollectionView.swift
1
9204
// // TGPageCollectionView.swift // TGPageView // // Created by targetcloud on 2017/3/24. // Copyright © 2017年 targetcloud. All rights reserved. //http://blog.csdn.net/callzjy/article/details/70160050 import UIKit /* private let kPageCollectionViewCellID = "kPageCollectionViewCellID" */ protocol TGPageCollectionViewDataSource :class {//MARK:- DataSource 1 func numberOfSections(in pageCollectionView: TGPageCollectionView ) -> Int func pageCollectionView(_ pageCollectionView: TGPageCollectionView, numberOfItemsInSection section: Int) -> Int func pageCollectionView(_ pageCollectionView: TGPageCollectionView, collectionView : UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell } protocol TGPageCollectionViewDelegate : NSObjectProtocol { func pageCollectionView(_ pageCollectionView: TGPageCollectionView, didSelectItemAt indexPath: IndexPath) } class TGPageCollectionView: UIView { weak var dataSource : TGPageCollectionViewDataSource?//MARK:- DataSource 2 weak var delegate : TGPageCollectionViewDelegate? fileprivate var layout : TGPageCollectionLayout fileprivate var titles : [String] fileprivate var titleStyle : TGPageStyle fileprivate var titleView : TGTitleView! fileprivate var pageControl : UIPageControl! fileprivate lazy var currentIndex : IndexPath = IndexPath(item: 0, section: 0) // fileprivate var collectionView : UICollectionView? fileprivate var collectionView : UICollectionView!//用! 则后面使用到不用写写? -> 用!意思是这行代码的作者对此保证:若有用到此collectionView,则一定有值 -> 若用? 则后面的代码一直要用?,系统不会强行解包,而是进行可选链形式操作,如果没有值,则不往下操作 -> 如果使用的是!,发现没有值,则会崩 -> 所以你有把握用! 没有把握用? init(frame: CGRect,titles : [String],titleStyle : TGPageStyle,layout : TGPageCollectionLayout) { self.titles = titles self.titleStyle = titleStyle self.layout = layout super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ self.backgroundColor = titleStyle.contentBgColor let titleY = titleStyle.isTitleInTop ? 0 : bounds.height - titleStyle.titleViewHeight let titleViewFrame = CGRect(x: 0, y: titleY, width: bounds.width, height: titleStyle.titleViewHeight) let titleView = TGTitleView(frame:titleViewFrame,titles:titles,style:titleStyle) titleView.backgroundColor = titleStyle.titleBgColor//UIColor.random() addSubview(titleView) self.titleView = titleView let contentY = titleStyle.isTitleInTop ? titleStyle.titleViewHeight : 0 let contentFrame = CGRect(x: 0, y: contentY, width: bounds.width, height: bounds.height - titleStyle.titleViewHeight - titleStyle.pageControlHeigth) let contentView = UICollectionView(frame: contentFrame, collectionViewLayout: layout) contentView.showsHorizontalScrollIndicator = false contentView.backgroundColor = titleStyle.contentBgColor//UIColor.random() contentView.dataSource = self contentView.delegate = self /* contentView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kPageCollectionViewCellID) */ contentView.isPagingEnabled = true collectionView = contentView addSubview(contentView) let pageControlY = contentFrame.maxY let pageControlFrame = CGRect(x: 0, y: pageControlY, width: bounds.width, height: titleStyle.pageControlHeigth) let pageControl = UIPageControl(frame: pageControlFrame) pageControl.numberOfPages = 1 pageControl.backgroundColor = contentView.backgroundColor//UIColor.random() pageControl.tintColor = titleStyle.bottomLineColor pageControl.isUserInteractionEnabled = false addSubview(pageControl) self.pageControl = pageControl titleView.delegate = self//MARK:- 代理的使用 1 成为代理 } } extension TGPageCollectionView {//保持和系统一样的用法和习惯 func register(cellClass : AnyClass?, forCellWithReuseIdentifier reuseIdentifier: String){//UICollectionViewCell.Type? collectionView.register(cellClass, forCellWithReuseIdentifier: reuseIdentifier) } func register(nib: UINib?, forCellWithReuseIdentifier reuseIdentifier: String){ collectionView.register(nib, forCellWithReuseIdentifier: reuseIdentifier) } func reloadData() { collectionView.reloadData() } } extension TGPageCollectionView : UICollectionViewDataSource{//MARK:- DataSource 3 func numberOfSections(in collectionView: UICollectionView) -> Int { /* return dataSource?.numberOfSections(in: self) ?? 4 */ return dataSource?.numberOfSections(in: self) ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { /* return dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 1 + Int(arc4random_uniform(10)) */ let itemNum = dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 0 if section == 0 { pageControl.numberOfPages = (itemNum - 1) / (layout.rows * layout.cols) + 1 } return itemNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { /* let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPageCollectionViewCellID, for: indexPath) cell.backgroundColor = UIColor.random() var label :UILabel? = cell.contentView.subviews.first as? UILabel if label == nil{ label = UILabel(frame: cell.bounds) label?.textAlignment = .center cell.contentView.addSubview(label!) } label?.text = "\(indexPath.section)-\(indexPath.item)" return cell */ return (dataSource?.pageCollectionView(self, collectionView: collectionView,cellForItemAt: indexPath))!//通过参数暴露collectionView } } extension TGPageCollectionView:TGTitleViewDelegate{//MARK:- 代理的使用 2 遵守 //MARK:- 代理的使用 3 实现协议方法 func titleView(_ titleView: TGTitleView, targetIndex: Int) { let indexPath = IndexPath(item: 0, section: targetIndex) currentIndex = indexPath collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false) let sectionNum = dataSource?.numberOfSections(in: self) ?? 0 let itemNum = dataSource?.pageCollectionView(self, numberOfItemsInSection: targetIndex) ?? 0 pageControl.numberOfPages = (itemNum - 1) / (layout.rows * layout.cols) + 1 pageControl.currentPage = indexPath.item / (layout.rows * layout.cols) //print(" --- \(sectionNum) \(itemNum) ---"); if (targetIndex == (sectionNum - 1)) && (itemNum <= (layout.rows * layout.cols)) { }else{ collectionView.contentOffset.x -= layout.sectionInset.left } print("--- \(targetIndex) \((sectionNum - 1)) \(itemNum) \(layout.rows * layout.cols)---") } } extension TGPageCollectionView : UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.pageCollectionView(self, didSelectItemAt: indexPath) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewDidEndScroll() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { print("decelerate \(decelerate)") scrollViewDidEndScroll() } private func scrollViewDidEndScroll(){ /* guard let cell = collectionView.visibleCells.first,let indexPath = collectionView.indexPath(for: cell) else { return } indexPath.item / (layout.rows * layout.cols) */ let point = CGPoint(x: layout.sectionInset.left + 1 + collectionView.contentOffset.x, y: layout.sectionInset.top + 1) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } print( "---\(indexPath.section) \(point)--- ") if indexPath.section != currentIndex.section { let itemNum = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) ?? 0 pageControl.numberOfPages = (itemNum - 1) / (layout.rows * layout.cols) + 1 titleView.setCurrentIndex(indexPath.section) currentIndex = indexPath } pageControl.currentPage = indexPath.item / (layout.rows * layout.cols) } } extension TGPageCollectionView{ func setTitles(titles : [String]){ self.titles = titles titleView.setTitles(titles: titles) } }
mit
9a513291aa87344c3232faec6d3c309a
42.495098
217
0.692889
5.038614
false
false
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Renderers/CandleStickChartRenderer.swift
19
12394
// // CandleStickChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit @objc public protocol CandleStickChartRendererDelegate { func candleStickChartRendererCandleData(renderer: CandleStickChartRenderer) -> CandleChartData! func candleStickChartRenderer(renderer: CandleStickChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func candleStickChartDefaultRendererValueFormatter(renderer: CandleStickChartRenderer) -> NSNumberFormatter! func candleStickChartRendererChartYMax(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererChartYMin(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererChartXMax(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererChartXMin(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererMaxVisibleValueCount(renderer: CandleStickChartRenderer) -> Int } public class CandleStickChartRenderer: ChartDataRendererBase { public weak var delegate: CandleStickChartRendererDelegate? public init(delegate: CandleStickChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(#context: CGContext) { var candleData = delegate!.candleStickChartRendererCandleData(self) for set in candleData.dataSets as! [CandleChartDataSet] { if (set.isVisible) { drawDataSet(context: context, dataSet: set) } } } private var _shadowPoints = [CGPoint](count: 2, repeatedValue: CGPoint()) private var _bodyRect = CGRect() private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawDataSet(#context: CGContext, dataSet: CandleChartDataSet) { var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency) var phaseX = _animator.phaseX var phaseY = _animator.phaseY var bodySpace = dataSet.bodySpace var entries = dataSet.yVals as! [CandleChartDataEntry] var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.shadowWidth) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { // get the entry var e = entries[j] if (e.xIndex < _minX || e.xIndex > _maxX) { continue } // calculate the shadow _shadowPoints[0].x = CGFloat(e.xIndex) _shadowPoints[0].y = CGFloat(e.high) * phaseY _shadowPoints[1].x = CGFloat(e.xIndex) _shadowPoints[1].y = CGFloat(e.low) * phaseY trans.pointValuesToPixel(&_shadowPoints) // draw the shadow var shadowColor: UIColor! = nil if (dataSet.shadowColorSameAsCandle) { if (e.open > e.close) { shadowColor = dataSet.decreasingColor ?? dataSet.colorAt(j) } else if (e.open < e.close) { shadowColor = dataSet.increasingColor ?? dataSet.colorAt(j) } } if (shadowColor === nil) { shadowColor = dataSet.shadowColor ?? dataSet.colorAt(j); } CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeLineSegments(context, _shadowPoints, 2) // calculate the body _bodyRect.origin.x = CGFloat(e.xIndex) - 0.5 + bodySpace _bodyRect.origin.y = CGFloat(e.close) * phaseY _bodyRect.size.width = (CGFloat(e.xIndex) + 0.5 - bodySpace) - _bodyRect.origin.x _bodyRect.size.height = (CGFloat(e.open) * phaseY) - _bodyRect.origin.y trans.rectValueToPixel(&_bodyRect) // draw body differently for increasing and decreasing entry if (e.open > e.close) { var color = dataSet.decreasingColor ?? dataSet.colorAt(j) if (dataSet.isDecreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else if (e.open < e.close) { var color = dataSet.increasingColor ?? dataSet.colorAt(j) if (dataSet.isIncreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else { CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeRect(context, _bodyRect) } } CGContextRestoreGState(context) } public override func drawValues(#context: CGContext) { var candleData = delegate!.candleStickChartRendererCandleData(self) if (candleData === nil) { return } var defaultValueFormatter = delegate!.candleStickChartDefaultRendererValueFormatter(self) // if values are drawn if (candleData.yValCount < Int(ceil(CGFloat(delegate!.candleStickChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX))) { var dataSets = candleData.dataSets for (var i = 0; i < dataSets.count; i++) { var dataSet = dataSets[i] if (!dataSet.isDrawValuesEnabled) { continue } var valueFont = dataSet.valueFont var valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entries = dataSet.yVals as! [CandleChartDataEntry] var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) var positions = trans.generateTransformedValuesCandle(entries, phaseY: _animator.phaseY) var lineHeight = valueFont.lineHeight var yOffset: CGFloat = lineHeight + 5.0 for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * _animator.phaseX + CGFloat(minx))); j < count; j++) { var x = positions[j].x var y = positions[j].y if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsLeft(x) || !viewPortHandler.isInBoundsY(y)) { continue } var val = entries[j].high ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: x, y: y - yOffset), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(#context: CGContext) { } private var _vertPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint()) private var _horzPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint()) public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { var candleData = delegate!.candleStickChartRendererCandleData(self) if (candleData === nil) { return } for (var i = 0; i < indices.count; i++) { var xIndex = indices[i].xIndex; // get the x-position var set = candleData.getDataSetByIndex(indices[i].dataSetIndex) as! CandleChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } var e = set.entryForXIndex(xIndex) as! CandleChartDataEntry! if (e === nil || e.xIndex != xIndex) { continue } var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: set.axisDependency) CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var low = CGFloat(e.low) * _animator.phaseY var high = CGFloat(e.high) * _animator.phaseY var min = delegate!.candleStickChartRendererChartYMin(self) var max = delegate!.candleStickChartRendererChartYMax(self) _vertPtsBuffer[0] = CGPoint(x: CGFloat(xIndex) - 0.5, y: CGFloat(max)) _vertPtsBuffer[1] = CGPoint(x: CGFloat(xIndex) - 0.5, y: CGFloat(min)) _vertPtsBuffer[2] = CGPoint(x: CGFloat(xIndex) + 0.5, y: CGFloat(max)) _vertPtsBuffer[3] = CGPoint(x: CGFloat(xIndex) + 0.5, y: CGFloat(min)) _horzPtsBuffer[0] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMin(self)), y: low) _horzPtsBuffer[1] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMax(self)), y: low) _horzPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMin(self)), y: high) _horzPtsBuffer[3] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMax(self)), y: high) trans.pointValuesToPixel(&_vertPtsBuffer) trans.pointValuesToPixel(&_horzPtsBuffer) // draw the vertical highlight lines CGContextStrokeLineSegments(context, _vertPtsBuffer, 4) // draw the horizontal highlight lines CGContextStrokeLineSegments(context, _horzPtsBuffer, 4) } } }
mit
b59211f010e28efcf531e86d2b8e973a
38.224684
246
0.560675
5.677508
false
false
false
false
ktmswzw/FeelingClientBySwift
Pods/ImagePickerSheetController/ImagePickerSheetController/ImagePickerSheetController/Sheet/SheetController.swift
6
9400
// // SheetController.swift // ImagePickerSheetController // // Created by Laurin Brandner on 27/08/15. // Copyright © 2015 Laurin Brandner. All rights reserved. // import UIKit private let defaultInset: CGFloat = 10 class SheetController: NSObject { private(set) lazy var sheetCollectionView: UICollectionView = { let layout = SheetCollectionViewLayout() let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.accessibilityIdentifier = "ImagePickerSheet" collectionView.backgroundColor = .clearColor() collectionView.alwaysBounceVertical = false collectionView.registerClass(SheetPreviewCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(SheetPreviewCollectionViewCell.self)) collectionView.registerClass(SheetActionCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(SheetActionCollectionViewCell.self)) return collectionView }() var previewCollectionView: PreviewCollectionView private(set) var actions = [ImagePickerAction]() var actionHandlingCallback: (() -> ())? private(set) var previewHeight: CGFloat = 0 var numberOfSelectedImages = 0 var preferredSheetHeight: CGFloat { return allIndexPaths().map { self.sizeForSheetItemAtIndexPath($0).height } .reduce(0, combine: +) } var preferredSheetWidth: CGFloat { guard #available(iOS 9, *) else { return sheetCollectionView.bounds.width } return sheetCollectionView.bounds.width - 2 * defaultInset } // MARK: - Initialization init(previewCollectionView: PreviewCollectionView) { self.previewCollectionView = previewCollectionView super.init() } // MARK: - Data Source // These methods are necessary so that no call cycles happen when calculating some design attributes private func numberOfSections() -> Int { return 2 } private func numberOfItemsInSection(section: Int) -> Int { if section == 0 { return 1 } return actions.count } private func allIndexPaths() -> [NSIndexPath] { let s = numberOfSections() return (0 ..< s).map { (self.numberOfItemsInSection($0), $0) } .flatMap { numberOfItems, section in (0 ..< numberOfItems).map { NSIndexPath(forItem: $0, inSection: section) } } } private func sizeForSheetItemAtIndexPath(indexPath: NSIndexPath) -> CGSize { let height: CGFloat = { if indexPath.section == 0 { return previewHeight } let actionItemHeight: CGFloat if #available(iOS 9, *) { actionItemHeight = 57 } else { actionItemHeight = 50 } let insets = attributesForItemAtIndexPath(indexPath).backgroundInsets return actionItemHeight + insets.top + insets.bottom }() return CGSize(width: sheetCollectionView.bounds.width, height: height) } // MARK: - Design private func attributesForItemAtIndexPath(indexPath: NSIndexPath) -> (corners: RoundedCorner, backgroundInsets: UIEdgeInsets) { guard #available(iOS 9, *) else { return (.None, UIEdgeInsets()) } let cornerRadius: CGFloat = 13 let innerInset: CGFloat = 4 var indexPaths = allIndexPaths() guard indexPaths.first != indexPath else { return (.Top(cornerRadius), UIEdgeInsets(top: 0, left: defaultInset, bottom: 0, right: defaultInset)) } let cancelIndexPath = actions.indexOf { $0.style == ImagePickerActionStyle.Cancel } .map { NSIndexPath(forItem: $0, inSection: 1) } if let cancelIndexPath = cancelIndexPath { if cancelIndexPath == indexPath { return (.All(cornerRadius), UIEdgeInsets(top: innerInset, left: defaultInset, bottom: defaultInset, right: defaultInset)) } indexPaths.removeLast() if indexPath == indexPaths.last { return (.Bottom(cornerRadius), UIEdgeInsets(top: 0, left: defaultInset, bottom: innerInset, right: defaultInset)) } } else if indexPath == indexPaths.last { return (.Bottom(cornerRadius), UIEdgeInsets(top: 0, left: defaultInset, bottom: defaultInset, right: defaultInset)) } return (.None, UIEdgeInsets(top: 0, left: defaultInset, bottom: 0, right: defaultInset)) } private func fontForAction(action: ImagePickerAction) -> UIFont { guard #available(iOS 9, *), action.style == .Cancel else { return UIFont.systemFontOfSize(21) } return UIFont.boldSystemFontOfSize(21) } // MARK: - Actions func reloadActionItems() { sheetCollectionView.reloadSections(NSIndexSet(index: 1)) } func addAction(action: ImagePickerAction) { if action.style == .Cancel { actions = actions.filter { $0.style != .Cancel } } actions.append(action) if let index = actions.indexOf({ $0.style == .Cancel }) { let cancelAction = actions.removeAtIndex(index) actions.append(cancelAction) } reloadActionItems() } private func handleAction(action: ImagePickerAction) { actionHandlingCallback?() action.handle(numberOfSelectedImages) } func handleCancelAction() { let cancelAction = actions.filter { $0.style == ImagePickerActionStyle.Cancel } .first if let cancelAction = cancelAction { handleAction(cancelAction) } else { actionHandlingCallback?() } } // MARK: - func setPreviewHeight(height: CGFloat, invalidateLayout: Bool) { previewHeight = height if invalidateLayout { sheetCollectionView.collectionViewLayout.invalidateLayout() } } } extension SheetController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return numberOfSections() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfItemsInSection(section) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell: SheetCollectionViewCell if indexPath.section == 0 { let previewCell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(SheetPreviewCollectionViewCell.self), forIndexPath: indexPath) as! SheetPreviewCollectionViewCell previewCell.collectionView = previewCollectionView cell = previewCell } else { let action = actions[indexPath.item] let actionCell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(SheetActionCollectionViewCell.self), forIndexPath: indexPath) as! SheetActionCollectionViewCell actionCell.textLabel.font = fontForAction(action) actionCell.textLabel.text = numberOfSelectedImages > 0 ? action.secondaryTitle(numberOfSelectedImages) : action.title cell = actionCell } cell.separatorVisible = (indexPath.section == 1) // iOS specific design (cell.roundedCorners, cell.backgroundInsets) = attributesForItemAtIndexPath(indexPath) if #available(iOS 9, *) { cell.normalBackgroundColor = UIColor(white: 0.97, alpha: 1) cell.highlightedBackgroundColor = UIColor(white: 0.92, alpha: 1) cell.separatorColor = UIColor(white: 0.84, alpha: 1) } else { cell.normalBackgroundColor = .whiteColor() cell.highlightedBackgroundColor = UIColor(white: 0.85, alpha: 1) cell.separatorColor = UIColor(white: 0.784, alpha: 1) } return cell } } extension SheetController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return indexPath.section != 0 } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { collectionView.deselectItemAtIndexPath(indexPath, animated: true) handleAction(actions[indexPath.item]) } } extension SheetController: UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return sizeForSheetItemAtIndexPath(indexPath) } }
mit
a7ed1f934f6765ff36074c6b30a07d44
34.467925
199
0.628365
5.798273
false
false
false
false
navermaps/maps.ios
NMapSampleSwift/NMapSampleSwift/MapViewController.swift
1
5435
// // MapViewController.swift // NMapSampleSwift // // Created by Junggyun Ahn on 2016. 11. 9.. // Copyright © 2016년 Naver. All rights reserved. // import UIKit class MapViewController: UIViewController, NMapViewDelegate, NMapPOIdataOverlayDelegate { var mapView: NMapView? @IBOutlet weak var levelStepper: UIStepper! override func viewDidLoad() { super.viewDidLoad() mapView = NMapView(frame: self.view.bounds) if let mapView = mapView { // set the delegate for map view mapView.delegate = self // set the application api key for Open MapViewer Library mapView.setClientId("YOUR CLIENT ID") mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) // Zoom 용 UIStepper 셋팅. initLevelStepper(mapView.minZoomLevel(), maxValue:mapView.maxZoomLevel(), initialValue:11) view.bringSubview(toFront: levelStepper) mapView.setBuiltInAppControl(true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() mapView?.didReceiveMemoryWarning() } // MARK: - NMapViewDelegate open func onMapView(_ mapView: NMapView!, initHandler error: NMapError!) { if (error == nil) { // success // set map center and level mapView.setMapCenter(NGeoPoint(longitude:126.978371, latitude:37.5666091), atLevel:11) // set for retina display mapView.setMapEnlarged(true, mapHD: true) // set map mode : vector/satelite/hybrid mapView.mapViewMode = .vector } else { // fail print("onMapView:initHandler: \(error.description)") } } // MARK: - NMapPOIdataOverlayDelegate open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, imageForOverlayItem poiItem: NMapPOIitem!, selected: Bool) -> UIImage! { return NMapViewResources.imageWithType(poiItem.poiFlagType, selected: selected) } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, anchorPointWithType poiFlagType: NMapPOIflagType) -> CGPoint { return NMapViewResources.anchorPoint(withType: poiFlagType) } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, calloutOffsetWithType poiFlagType: NMapPOIflagType) -> CGPoint { return CGPoint(x: 0, y: 0) } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, imageForCalloutOverlayItem poiItem: NMapPOIitem!, constraintSize: CGSize, selected: Bool, imageForCalloutRightAccessory: UIImage!, calloutPosition: UnsafeMutablePointer<CGPoint>!, calloutHit calloutHitRect: UnsafeMutablePointer<CGRect>!) -> UIImage! { return nil } // MARK: - Layer Button @IBAction func layerButtonAction(_ sender: UIBarButtonItem) { let alertController = UIAlertController(title: "Layers", message: nil, preferredStyle: .actionSheet) if let map = mapView { // Action Sheet 생성 let trafficAction = UIAlertAction(title: "Traffic layer is " + (map.mapViewTrafficMode ? "On" : "Off"), style: .default, handler: { (action) -> Void in print("Traffic layer Selected...") map.mapViewTrafficMode = !map.mapViewTrafficMode }) let bicycleAction = UIAlertAction(title: "Bicycle layer is " + (map.mapViewBicycleMode ? "On" : "Off"), style: .default, handler: { (action) -> Void in print("Traffic layer Selected...") map.mapViewBicycleMode = !map.mapViewBicycleMode }) let alphaAction = UIAlertAction(title: "Alpha layer is " + (map.mapViewAlphaLayerMode ? "On" : "Off"), style: .default, handler: { (action) -> Void in print("Alpha layer Selected...") map.mapViewAlphaLayerMode = !map.mapViewAlphaLayerMode // 지도 위 반투명 레이어에 색을 지정할 때에는 다음 메서드를 사용한다 // map.setMapViewAlphaLayerMode(!map.mapViewAlphaLayerMode, with: UIColor(red: 0.5, green: 1.0, blue: 0.5, alpha: 0.9)) }) alertController.addAction(trafficAction) alertController.addAction(bicycleAction) alertController.addAction(alphaAction) } alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } // MARK: - Map Mode Segmented Control @IBAction func modeChanged(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: mapView?.mapViewMode = .vector case 1: mapView?.mapViewMode = .satellite case 2: mapView?.mapViewMode = .hybrid default: mapView?.mapViewMode = .vector } } // MARK: - Level Stepper func initLevelStepper(_ minValue: Int32, maxValue: Int32, initialValue: Int32) { levelStepper.minimumValue = Double(minValue) levelStepper.maximumValue = Double(maxValue) levelStepper.stepValue = 1 levelStepper.value = Double(initialValue) } @IBAction func levelStepperValeChanged(_ sender: UIStepper) { mapView?.setZoomLevel(Int32(sender.value)) } }
apache-2.0
6aeb1a97e07c09814ae9e3bb42c85dec
36.263889
317
0.641633
4.453112
false
false
false
false
benbahrenburg/SwiftDately
Example/Tests/Tests.swift
1
1178
// https://github.com/Quick/Quick import Quick import Nimble import SwiftDately 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 eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
9b72c532cf777f389bbfb4cf29b4e939
22.44
63
0.364334
5.476636
false
false
false
false
huonw/swift
test/SILGen/auto_closures.swift
3
3713
// RUN: %target-swift-emit-silgen -module-name auto_closures -enable-sil-ownership -parse-stdlib %s | %FileCheck %s struct Bool {} var false_ = Bool() // CHECK-LABEL: sil hidden @$S13auto_closures05call_A8_closureyAA4BoolVADyXKF : $@convention(thin) (@noescape @callee_guaranteed () -> Bool) -> Bool func call_auto_closure(_ x: @autoclosure () -> Bool) -> Bool { // CHECK: bb0([[CLOSURE:%.*]] : @trivial $@noescape @callee_guaranteed () -> Bool): // CHECK: [[RET:%.*]] = apply [[CLOSURE]]() // CHECK: return [[RET]] return x() } // CHECK-LABEL: sil hidden @$S13auto_closures05test_A21_closure_with_capture{{[_0-9a-zA-Z]*}}F func test_auto_closure_with_capture(_ x: Bool) -> Bool { // CHECK: [[CLOSURE:%.*]] = function_ref @$S13auto_closures05test_A21_closure_with_capture // CHECK: [[WITHCAPTURE:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE]]( // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[WITHCAPTURE]] // CHECK: [[RET:%.*]] = apply {{%.*}}([[CVT]]) // CHECK: return [[RET]] return call_auto_closure(x) } // CHECK-LABEL: sil hidden @$S13auto_closures05test_A24_closure_without_capture{{[_0-9a-zA-Z]*}}F func test_auto_closure_without_capture() -> Bool { // CHECK: [[CLOSURE:%.*]] = function_ref @$S13auto_closures05test_A24_closure_without_capture // CHECK: [[CVT:%.*]] = convert_function [[CLOSURE]] // CHECK: [[THICK:%.*]] = thin_to_thick_function [[CVT]] : $@convention(thin) @noescape () -> Bool to $@noescape @callee_guaranteed () -> Bool // CHECK: [[RET:%.*]] = apply {{%.*}}([[THICK]]) // CHECK: return [[RET]] return call_auto_closure(false_) } public class Base { var x: Bool { return false_ } } public class Sub : Base { // CHECK-LABEL: sil hidden @$S13auto_closures3SubC1xAA4BoolVvg : $@convention(method) (@guaranteed Sub) -> Bool { // CHECK: bb0([[SELF:%.*]] : @guaranteed $Sub): // CHECK: [[AUTOCLOSURE_FUNC:%.*]] = function_ref @$S13auto_closures3SubC1xAA4BoolVvgAFyXKfu_ : $@convention(thin) (@guaranteed Sub) -> Bool // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[AUTOCLOSURE:%.*]] = partial_apply [callee_guaranteed] [[AUTOCLOSURE_FUNC]]([[SELF_COPY]]) // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[AUTOCLOSURE]] // CHECK: [[AUTOCLOSURE_CONSUMER:%.*]] = function_ref @$S13auto_closures05call_A8_closureyAA4BoolVADyXKF : $@convention(thin) // CHECK: [[RET:%.*]] = apply [[AUTOCLOSURE_CONSUMER]]([[CVT]]) // CHECK: return [[RET]] : $Bool // CHECK: } // CHECK-LABEL: sil private [transparent] @$S13auto_closures3SubC1xAA4BoolVvgAFyXKfu_ : $@convention(thin) (@guaranteed Sub) -> Bool { // CHECK: [[SUPER:%[0-9]+]] = function_ref @$S13auto_closures4BaseC1xAA4BoolVvg : $@convention(method) (@guaranteed Base) -> Bool // CHECK: [[RET:%.*]] = apply [[SUPER]]({{%.*}}) // CHECK: return [[RET]] override var x: Bool { return call_auto_closure(super.x) } } // CHECK-LABEL: sil hidden @$S13auto_closures20closureInAutoclosureyAA4BoolVAD_ADtF : $@convention(thin) (Bool, Bool) -> Bool { // CHECK: } // CHECK-LABEL: sil private [transparent] @$S13auto_closures20closureInAutoclosureyAA4BoolVAD_ADtFADyXKfu_ : $@convention(thin) (Bool, Bool) -> Bool { // CHECK: } // CHECK-LABEL: sil private @$S13auto_closures20closureInAutoclosureyAA4BoolVAD_ADtFADyXKfu_A2DXEfU_ : $@convention(thin) (Bool, Bool) -> Bool { // CHECK: } func compareBool(_ lhs: Bool, _ rhs: Bool) -> Bool { return false_ } func testBool(_ x: Bool, _ pred: (Bool) -> Bool) -> Bool { return pred(x) } func delayBool(_ fn: @autoclosure () -> Bool) -> Bool { return fn() } func closureInAutoclosure(_ lhs: Bool, _ rhs: Bool) -> Bool { return delayBool(testBool(lhs, { compareBool($0, rhs) })) }
apache-2.0
4430b9ac0fc1e116ddedd2dc0e7527a7
49.863014
150
0.64934
3.303381
false
true
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CodeStarconnections/CodeStarconnections_Error.swift
1
2310
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for CodeStarconnections public struct CodeStarconnectionsErrorType: AWSErrorType { enum Code: String { case limitExceededException = "LimitExceededException" case resourceNotFoundException = "ResourceNotFoundException" case resourceUnavailableException = "ResourceUnavailableException" } private let error: Code public let context: AWSErrorContext? /// initialize CodeStarconnections public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Exceeded the maximum limit for connections. public static var limitExceededException: Self { .init(.limitExceededException) } /// Resource not found. Verify the connection resource ARN and try again. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// Resource not found. Verify the ARN for the host resource and try again. public static var resourceUnavailableException: Self { .init(.resourceUnavailableException) } } extension CodeStarconnectionsErrorType: Equatable { public static func == (lhs: CodeStarconnectionsErrorType, rhs: CodeStarconnectionsErrorType) -> Bool { lhs.error == rhs.error } } extension CodeStarconnectionsErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
9ffebb378121e19a30b0aa95dc0ab547
35.666667
117
0.669697
5.372093
false
false
false
false
hsoi/RxSwift
RxSwift/Schedulers/SerialDispatchQueueScheduler.swift
2
8772
// // SerialDispatchQueueScheduler.swift // Rx // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure that even if concurrent dispatch queue is passed, it's transformed into a serial one. It is extemely important that this scheduler is serial, because certain operator perform optimizations that rely on that property. Because there is no way of detecting is passed dispatch queue serial or concurrent, for every queue that is being passed, worst case (concurrent) will be assumed, and internal serial proxy dispatch queue will be created. This scheduler can also be used with internal serial queue alone. In case some customization need to be made on it before usage, internal serial queue can be customized using `serialQueueConfiguration` callback. */ public class SerialDispatchQueueScheduler: SchedulerType { public typealias TimeInterval = NSTimeInterval public typealias Time = NSDate private let _serialQueue : dispatch_queue_t /** - returns: Current time. */ public var now : NSDate { get { return NSDate() } } // leeway for scheduling timers private var _leeway: Int64 = 0 init(serialQueue: dispatch_queue_t) { _serialQueue = serialQueue } /** Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. - parameter internalSerialQueueName: Name of internal serial dispatch queue. - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. */ public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((dispatch_queue_t) -> Void)? = nil) { let queue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) serialQueueConfiguration?(queue) self.init(serialQueue: queue) } /** Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. - parameter queue: Possibly concurrent dispatch queue used to perform work. - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. */ public convenience init(queue: dispatch_queue_t, internalSerialQueueName: String) { let serialQueue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) dispatch_set_target_queue(serialQueue, queue) self.init(serialQueue: serialQueue) } /** Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues. - parameter globalConcurrentQueuePriority: Identifier for global dispatch queue with specified priority. - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. */ @available(*, deprecated=2.0.0, message="Use init(globalConcurrentQueueQOS:,internalSerialQueueName:) instead.") public convenience init(globalConcurrentQueuePriority: DispatchQueueSchedulerPriority, internalSerialQueueName: String = "rx.global_dispatch_queue.serial") { var priority: Int = 0 switch globalConcurrentQueuePriority { case .High: priority = DISPATCH_QUEUE_PRIORITY_HIGH case .Default: priority = DISPATCH_QUEUE_PRIORITY_DEFAULT case .Low: priority = DISPATCH_QUEUE_PRIORITY_LOW } self.init(queue: dispatch_get_global_queue(priority, UInt(0)), internalSerialQueueName: internalSerialQueueName) } /** Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues. - parameter globalConcurrentQueueQOS: Identifier for global dispatch queue with specified quality of service class. - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. */ @available(iOS 8, OSX 10.10, *) public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial") { let priority: qos_class_t switch globalConcurrentQueueQOS { case .UserInteractive: priority = QOS_CLASS_USER_INTERACTIVE case .UserInitiated: priority = QOS_CLASS_USER_INITIATED case .Default: priority = QOS_CLASS_DEFAULT case .Utility: priority = QOS_CLASS_UTILITY case .Background: priority = QOS_CLASS_BACKGROUND } self.init(queue: dispatch_get_global_queue(priority, UInt(0)), internalSerialQueueName: internalSerialQueueName) } class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 { return Int64(timeInterval * Double(NSEC_PER_SEC)) } class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t { return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval)) } /** Schedules an action to be executed immediatelly. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public final func schedule<StateType>(state: StateType, action: (StateType) -> Disposable) -> Disposable { return self.scheduleInternal(state, action: action) } func scheduleInternal<StateType>(state: StateType, action: (StateType) -> Disposable) -> Disposable { let cancel = SingleAssignmentDisposable() dispatch_async(_serialQueue) { if cancel.disposed { return } cancel.disposable = action(state) } return cancel } /** Schedules an action to be executed. - parameter state: State passed to the action to be executed. - parameter dueTime: Relative time after which to execute the action. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public final func scheduleRelative<StateType>(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable { let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _serialQueue) let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime) let compositeDisposable = CompositeDisposable() dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0) dispatch_source_set_event_handler(timer, { if compositeDisposable.disposed { return } compositeDisposable.addDisposable(action(state)) }) dispatch_resume(timer) compositeDisposable.addDisposable(AnonymousDisposable { dispatch_source_cancel(timer) }) return compositeDisposable } /** Schedules a periodic piece of work. - parameter state: State passed to the action to be executed. - parameter startAfter: Period after which initial work should be run. - parameter period: Period for running the work periodically. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _serialQueue) let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter) let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period) var timerState = state let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval) dispatch_source_set_timer(timer, initial, validDispatchInterval, 0) let cancel = AnonymousDisposable { dispatch_source_cancel(timer) } dispatch_source_set_event_handler(timer, { if cancel.disposed { return } timerState = action(timerState) }) dispatch_resume(timer) return cancel } }
mit
6d53b3fb5e63f347ff77181d3067cbf0
39.233945
161
0.689317
5.377682
false
false
false
false
dongjiali/DatePicker
DatePicker/DatePickerView.swift
1
10091
// // DatePickerView.swift // DatePicker // // Created by Curry on 15/5/14. // Copyright (c) 2015年 curry. All rights reserved. // import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } let HEADERVIEWHEIGHT:CGFloat = 50.0 let PICKERVIEWHEIGHT:CGFloat = 220.0 protocol DatePickerDelegate { func didSelectedItemDatePicker(_ datePickerView: DatePickerView) } class DatePickerView: UIView,PickerValueChangeDelegate{ var pickerArray = [AnyObject]() var pickerDataArray = [Array<String>]() var datePickerSource = DatePickerSource() var delegate:DatePickerDelegate? var selectedDateString:String = "" var yearString:String = "" var monthString:String = "" var dayString:String = "" var cancelButton:UIButton = UIButton.init(type:.custom) var doneButton:UIButton = UIButton.init(type:.custom) // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { self.buildViewControl() } override init(frame: CGRect) { super.init(frame: frame) self.initPickerDateSource() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initPickerDateSource() { pickerDataArray = [] pickerDataArray.append(datePickerSource.getYears()) pickerDataArray.append(datePickerSource.getMonths()) pickerDataArray.append(datePickerSource.getDaysInMonth(Date())) } func buildViewControl() { let button:UIButton = UIButton.init(type:.custom) button.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height - 270) button.backgroundColor = UIColor.clear button .addTarget(self, action:#selector(click), for: UIControlEvents.touchUpInside) self.addSubview(button) let pickerView:UIView = UIView(frame: CGRect(x: 0, y: self.frame.size.height - 270, width: self.frame.size.width, height: 270)) pickerView.backgroundColor = UIColor.clear self.addSubview(pickerView) //add header view self.addHeaderView(pickerView) //add picker view self.addPickerView(pickerView) } func click() { } func addHeaderView(_ subView:UIView) { let headerView:UIView = UIView(frame:CGRect(x: 0.0, y: 0.0, width: subView.frame.size.width, height: HEADERVIEWHEIGHT+5)) headerView.backgroundColor = UIColor(red: 0/255.0, green: 122/255.0, blue: 255/255.0, alpha: 1) headerView.layer.cornerRadius = 5.0 subView.addSubview(headerView) let label:UILabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: CGFloat(subView.frame.size.width), height: HEADERVIEWHEIGHT)) label.text = "请选择日期" label.textAlignment = NSTextAlignment.center label.backgroundColor = UIColor.clear label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 18.0) headerView.addSubview(label) //cancel cancelButton.setTitle("取消", for: UIControlState()) cancelButton.backgroundColor = UIColor.clear cancelButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18.0) cancelButton.setTitleColor(UIColor.white, for: UIControlState()) cancelButton.frame = CGRect(x: 0.0, y: 0.0, width: 60.0, height: HEADERVIEWHEIGHT) cancelButton.tag = -1 headerView.addSubview(cancelButton) cancelButton.addTarget(self, action: #selector(DatePickerView.cancelButtonClick(_:)), for: UIControlEvents.touchUpInside) //done doneButton.setTitle("确定", for: UIControlState()) doneButton.backgroundColor = UIColor.clear doneButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18.0) doneButton.setTitleColor(UIColor.white, for: UIControlState()) doneButton.frame = CGRect(x: headerView.frame.size.width - 60.0 , y: 0.0, width: 60.0, height: HEADERVIEWHEIGHT); doneButton.tag = 250; headerView.addSubview(doneButton) doneButton.addTarget(self, action: #selector(DatePickerView.doneButtonClick(_:)), for: UIControlEvents.touchUpInside) } func addPickerView(_ subView:UIView) { let bottomView:UIView = UIView(frame:CGRect(x: 0.0, y: HEADERVIEWHEIGHT, width: subView.frame.size.width, height: PICKERVIEWHEIGHT + 10.0)) bottomView.backgroundColor = UIColor.white subView.addSubview(bottomView) //add highlight selected view let barSelected:UIView = UIView(frame: CGRect(x: 0, y: 220/2.0 - 44/2.0, width: subView.frame.size.width, height: 44.0)) barSelected.backgroundColor = UIColor(red: 0/255.0, green: 122/255.0, blue: 255/255.0, alpha: 1) bottomView.addSubview(barSelected) //add picker view pickerArray.removeAll(keepingCapacity: true) var nowDate = datePickerSource.getYearAndMonthAndDay(Date()) yearString = nowDate[0] monthString = nowDate[1] dayString = nowDate[2] self.setSelectedDate() for i in 0 ..< pickerDataArray.count { let pickerWidth:CGFloat = self.frame.size.width / 3; let pickframe:CGRect = CGRect(x: pickerWidth*CGFloat(i), y: 0.0, width: pickerWidth, height: PICKERVIEWHEIGHT) let lineLayout:DatePickerFlowLayout = DatePickerFlowLayout(size: CGSize(width: pickerWidth, height: 44.0)) let pickerView = DatePickerCollectionView(frame: pickframe, collectionViewLayout: lineLayout) pickerView.cellItemArray = pickerDataArray[i] as [(String)] pickerView.pickerDelegate = self let cellArray:NSArray = pickerView.cellItemArray as NSArray pickerView.selectedItemTag = cellArray.index(of: nowDate[i]) pickerView.setCollectionViewOfContentOffset() pickerArray.append(pickerView) pickerView.tag = i bottomView.addSubview(pickerView) if i > 0 { let line = UIView(frame: CGRect(x: pickframe.size.width*CGFloat(i), y: 0, width: 1.0, height: PICKERVIEWHEIGHT)) line.backgroundColor = UIColor(white: 0.8, alpha: 1) bottomView.addSubview(line) } } self.addGradientLayer(bottomView) } func addGradientLayer(_ subView:UIView) { let gradientLayerTop = CAGradientLayer() gradientLayerTop.frame = CGRect(x: 0.0, y: 0.0, width: subView.frame.size.width, height: PICKERVIEWHEIGHT/2.0) gradientLayerTop.colors = [UIColor(white: 1.0, alpha: 0).cgColor,subView.backgroundColor!.cgColor] gradientLayerTop.startPoint = CGPoint(x: 0.0, y: 0.7) gradientLayerTop.endPoint = CGPoint(x: 0.0, y: 0.0) let gradientLayerBottom = CAGradientLayer() gradientLayerBottom.frame = CGRect(x: 0.0, y: PICKERVIEWHEIGHT/2.0, width: subView.frame.size.width, height: PICKERVIEWHEIGHT/2.0) gradientLayerBottom.colors = gradientLayerTop.colors gradientLayerBottom.startPoint = CGPoint(x: 0.0, y: 0.3); gradientLayerBottom.endPoint = CGPoint(x: 0.0, y: 1.0); subView.layer .addSublayer(gradientLayerTop) subView.layer .addSublayer(gradientLayerBottom) } func cancelButtonClick(_ button:UIButton) { delegate?.didSelectedItemDatePicker(self) } func doneButtonClick(_ button:UIButton) { delegate?.didSelectedItemDatePicker(self) } // TODO PickerValueChangeDelegate func didEndDecelerating(_ collectionView: DatePickerCollectionView) { switch collectionView.tag { case 0: yearString = collectionView.cellItemArray[collectionView.selectedItemTag!] self.getDaysInYearAndMonth(Int(yearString)!, month: Int(monthString)!, day: Int(dayString)!) case 1: monthString = collectionView.cellItemArray[collectionView.selectedItemTag!] self.getDaysInYearAndMonth(Int(yearString)!, month: Int(monthString)!, day: Int(dayString)!) case 2: dayString = collectionView.cellItemArray[collectionView.selectedItemTag!] default: break } self.setSelectedDate() cancelButton.isEnabled = true doneButton.isEnabled = true } func DidScroll(_ collectionView: DatePickerCollectionView) { cancelButton.isEnabled = false doneButton.isEnabled = false } func getDaysInYearAndMonth(_ year:Int,month:Int,day:Int) { let date = datePickerSource.convertToDateDay(1, month: month, year: year) let days = datePickerSource.getDaysInMonth(date) let dayCollectionView:DatePickerCollectionView = pickerArray[2] as! DatePickerCollectionView pickerDataArray[2] = days dayCollectionView.cellItemArray = pickerDataArray[2] if dayCollectionView.selectedItemTag >= pickerDataArray[2].count { dayCollectionView.selectedItemTag = pickerDataArray[2].count - 1; } dayCollectionView.reloadData() } func setSelectedDate() { selectedDateString = yearString + "-" + monthString + "-" + dayString } }
mit
ac64b5f0315a4a222e5d7ddb124bb4e5
38.649606
147
0.658524
4.3806
false
false
false
false
brandonlee503/Swift-Playground-Practice
Closures.playground/Contents.swift
1
2239
// Closure Expressions func doubler(i: Int) -> Int { return i * 2 } let doubleFunction = doubler doubleFunction(45) let numbers = [1,2,3,4,5] // Map is a function and doubleFunction is the function within let doubledNumbers = numbers.map(doubleFunction) // Using closure expressions with the map function let tripledNumbers = numbers.map({(i: Int) -> Int in return i * 3}) // Using closure expressions with the sorted function var names = ["Brandon", "Chris", "Austin", "Ray", "Nicole"] func backwards(s1: String, s2: String) -> Bool { return s1 > s2 } sorted(names, backwards) let sortedNames = sorted(names, {(s1: String, s2: String) -> Bool in return s1 > s2}) print(sortedNames) // Closure Shorthand Syntax let tripleFunction = { (i: Int) -> Int in return i * 3 } [1,2,3,4,5].map(tripleFunction) // Or... // Rule #1 - If you're just passing in a closure as an argument, then you don't need to assign it to a local var or constant [1,2,3,4,5].map({ (i: Int) -> Int in return i * 3 }) // Or... // Rule #2 (Inferring type from context) - When a closure is passed as an argument to a function, Swift can infer the types of parameters and the type of value it returns [1,2,3,4,5].map({ i in return i * 3 }) // Or... // Rule #3 - (Implicit returns from single expression closures) If we have a single expression closure, then the return value is implicit [1,2,3,4,5].map({ i in i * 3 }) // Or... // Rule #4 - (Shorthand Arguement Names) Swift provides shorthand argument names for inline closures. Ex - $0, $1, $2 [1,2,3,4,5].map({ $0 * 3 }) // Or... // Rule #5 - (Trailing Closure) If the closure expression is the last arg to a function, you can move the expression outside the parenthesis of the function call and write it as a trailing closure instead. // Example 1 [1,2,3,4,5].map() { $0 * 3 } // Example 2 [1,2,3,4,5].map() { (var digit) -> Int in if digit % 2 == 0 { return digit/2 } else { return digit } } // Or... // Rule #6 - (Ignoring Parenthesis) If a closure expression is the only argument to a function, then you can get rid of the function's parenthesis [1,2,3,4,5].map() { $0 * 3 } // Each of these rules is a chapter of Apple's documentation book
mit
6379083f059b6e42c1a49c249b1a4310
26.304878
205
0.661009
3.157969
false
false
false
false
Sajjon/Zeus
Pods/Alamofire/Source/Alamofire.swift
1
15919
// // Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to /// construct URL requests. public protocol URLStringConvertible { /// A URL that conforms to RFC 2396. /// /// Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. /// /// See https://tools.ietf.org/html/rfc2396 /// See https://tools.ietf.org/html/rfc1738 /// See https://tools.ietf.org/html/rfc1808 var urlString: String { get } } extension String: URLStringConvertible { /// The URL string. public var urlString: String { return self } } extension URL: URLStringConvertible { /// The URL string. public var urlString: String { return absoluteString } } extension URLComponents: URLStringConvertible { /// The URL string. public var urlString: String { return url!.urlString } } extension URLRequest: URLStringConvertible { /// The URL string. public var urlString: String { return url!.urlString } } // MARK: - /// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. public protocol URLRequestConvertible { /// The URL request. var urlRequest: URLRequest { get } } extension URLRequest: URLRequestConvertible { /// The URL request. public var urlRequest: URLRequest { return self } } // MARK: - extension URLRequest { /// Creates an instance with the specified `method`, `urlString` and `headers`. /// /// - parameter urlString: The URL string. /// - parameter method: The HTTP method. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The new `URLRequest` instance. public init(urlString: URLStringConvertible, method: HTTPMethod, headers: [String: String]? = nil) { self.init(url: URL(string: urlString.urlString)!) if let request = urlString as? URLRequest { self = request } httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { setValue(headerValue, forHTTPHeaderField: headerField) } } } } // MARK: - Data Request /// Creates a data `Request` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlString`, `method`, `parameters`, `encoding` and `headers`. /// /// - parameter urlString: The URL string. /// - parameter method: The HTTP method. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `.url` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created data `Request`. @discardableResult public func request( _ urlString: URLStringConvertible, withMethod method: HTTPMethod, parameters: [String: Any]? = nil, encoding: ParameterEncoding = .url, headers: [String: String]? = nil) -> Request { return SessionManager.default.request( urlString, withMethod: method, parameters: parameters, encoding: encoding, headers: headers ) } /// Creates a data `Request` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest`. /// /// - parameter urlRequest: The URL request /// /// - returns: The created data `Request`. @discardableResult public func request(_ urlRequest: URLRequestConvertible) -> Request { return SessionManager.default.request(urlRequest.urlRequest) } // MARK: - Download Request // MARK: URL Request /// Creates a download `Request` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlString`, `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. /// /// - parameter urlString: The URL string. /// - parameter destination: The closure used to determine the destination of the downloaded file. /// - parameter method: The HTTP method. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `.url` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created download `Request`. @discardableResult public func download( _ urlString: URLStringConvertible, to destination: Request.DownloadFileDestination, withMethod method: HTTPMethod, parameters: [String: Any]? = nil, encoding: ParameterEncoding = .url, headers: [String: String]? = nil) -> Request { return SessionManager.default.download( urlString, to: destination, withMethod: method, parameters: parameters, encoding: encoding, headers: headers ) } /// Creates a download `Request` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest` and save them to the `destination`. /// /// - parameter urlRequest: The URL request. /// - parameter destination: The closure used to determine the destination of the downloaded file. /// /// - returns: The created download `Request`. @discardableResult public func download( _ urlRequest: URLRequestConvertible, to destination: Request.DownloadFileDestination) -> Request { return SessionManager.default.download(urlRequest, to: destination) } // MARK: Resume Data /// Creates a download `Request` using the default `SessionManager` from the `resumeData` produced from a /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional /// information. /// - parameter destination: The closure used to determine the destination of the downloaded file. /// /// - returns: The created download `Request`. @discardableResult public func download(resourceWithin resumeData: Data, to destination: Request.DownloadFileDestination) -> Request { return SessionManager.default.download(resourceWithin: resumeData, to: destination) } // MARK: - Upload Request // MARK: File /// Creates an upload `Request` using the default `SessionManager` from the specified `method`, `urlString` /// and `headers` for uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter method: The HTTP method. /// - parameter urlString: The URL string. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created upload `Request`. @discardableResult public func upload( _ fileURL: URL, to urlString: URLStringConvertible, withMethod method: HTTPMethod, headers: [String: String]? = nil) -> Request { return SessionManager.default.upload(fileURL, to: urlString, withMethod: method, headers: headers) } /// Creates a upload `Request` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created upload `Request`. @discardableResult public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> Request { return SessionManager.default.upload(fileURL, with: urlRequest) } // MARK: Data /// Creates an upload `Request` using the default `SessionManager` from the specified `method`, `urlString` /// and `headers` for uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter urlString: The URL string. /// - parameter method: The HTTP method. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created upload `Request`. @discardableResult public func upload( _ data: Data, to urlString: URLStringConvertible, withMethod method: HTTPMethod, headers: [String: String]? = nil) -> Request { return SessionManager.default.upload(data, to: urlString, withMethod: method, headers: headers) } /// Creates an upload `Request` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created upload `Request`. @discardableResult public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> Request { return SessionManager.default.upload(data, with: urlRequest) } // MARK: InputStream /// Creates an upload `Request` using the default `SessionManager` from the specified `method`, `urlString` /// and `headers` for uploading the `stream`. /// /// - parameter stream: The stream to upload. /// - parameter urlString: The URL string. /// - parameter method: The HTTP method. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created upload `Request`. @discardableResult public func upload( _ stream: InputStream, to urlString: URLStringConvertible, withMethod method: HTTPMethod, headers: [String: String]? = nil) -> Request { return SessionManager.default.upload(stream, to: urlString, withMethod: method, headers: headers) } /// Creates an upload `Request` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `stream`. /// /// - parameter urlRequest: The URL request. /// - parameter stream: The stream to upload. /// /// - returns: The created upload `Request`. @discardableResult public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> Request { return SessionManager.default.upload(stream, with: urlRequest) } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls /// `encodingCompletion` with new upload `Request` using the `method`, `urlString` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlString: The URL string. /// - parameter method: The HTTP method. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to urlString: URLStringConvertible, withMethod method: HTTPMethod, headers: [String: String]? = nil, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, to: urlString, withMethod: method, headers: headers, encodingCompletion: encodingCompletion ) } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and /// calls `encodingCompletion` with new upload `Request` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) }
apache-2.0
f587128d7cebbaa670516a1377ea2379
40.240933
118
0.713738
4.743445
false
false
false
false
Sajjon/Zeus
Zeus/Models/JSON.swift
1
2418
// // JSON.swift // Zeus // // Created by Cyon Alexander (Ext. Netlight) on 29/08/16. // Copyright © 2016 com.cyon. All rights reserved. // import Foundation internal typealias RawJSON = Dictionary<String, NSObject> internal typealias ValuesForPropertiesNamed = Dictionary<String, NSObject> internal protocol JSONProtocol: Sequence { var map: RawJSON { get set } func valueFor(nestedKey: String) -> NSObject? } internal extension JSONProtocol { func makeIterator() -> DictionaryIterator<String, NSObject> { return map.makeIterator() } subscript(key: String) -> NSObject? { get { return map[key] } set(newValue) { map[key] = newValue } } func valueFor(nestedKey: String) -> NSObject? { return valueFor(nestedKey: nestedKey, inJson: map) } } private extension JSONProtocol { func valueFor(nestedKey: String, inJson rawJson: RawJSON?) -> NSObject? { let json = rawJson ?? map guard nestedKey.contains(".") else { let finalValue = json[nestedKey] return finalValue } let keys = nestedKey.components(separatedBy: ".") let slice: ArraySlice<String> = keys.dropFirst() let keysWithFirstDropped: [String] = Array(slice) let nestedKeyWithoutFirst: String if keysWithFirstDropped.count > 1 { nestedKeyWithoutFirst = keysWithFirstDropped.reduce("") { return $0 + "." + $1 } } else { nestedKeyWithoutFirst = keysWithFirstDropped[0] } let firstKey = keys[0] guard let subJson = json[firstKey] as? RawJSON else { return nil } return valueFor(nestedKey: nestedKeyWithoutFirst, inJson: subJson) } } internal struct JSON: JSONProtocol { internal var map: RawJSON internal init(_ map: RawJSON = [:]) { self.map = map } } internal struct FlattnedJSON: JSONProtocol { internal var map: RawJSON internal init(_ json: JSON? = nil) { self.map = json?.map ?? [:] } } internal struct MappedJSON: JSONProtocol { internal var map: RawJSON internal init(_ json: FlattnedJSON? = nil) { self.map = json?.map ?? [:] } } internal struct CherryPickedJSON: JSONProtocol { internal var map: RawJSON internal init(_ mappedJson: MappedJSON? = nil) { self.map = mappedJson?.map ?? [:] } }
apache-2.0
681cc198b5d2312cadd01b0d5e575ca1
25.271739
92
0.625155
4.117547
false
false
false
false
shitoudev/v2ex
v2ex/NotificationCell.swift
1
2976
// // NotificationCell.swift // v2ex // // Created by zhenwen on 8/19/15. // Copyright (c) 2015 zhenwen. All rights reserved. // import UIKit class NotificationCell: UITableViewCell { @IBOutlet weak var postTitleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var dateTimeLabel: UILabel! var markLayer: CAShapeLayer! override func setHighlighted(highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) cellSelected(highlighted, animated: animated) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) cellSelected(selected, animated: animated) } override func awakeFromNib() { super.awakeFromNib() selectionStyle = .None layoutMargins = UIEdgeInsetsZero separatorInset = UIEdgeInsetsZero postTitleLabel.backgroundColor = UIColor.colorWithHexString("#edf3f5") postTitleLabel.textColor = UIColor.colorWithHexString("#778087") dateTimeLabel.backgroundColor = postTitleLabel.backgroundColor dateTimeLabel.textColor = UIColor.grayColor() let x = CGFloat(20), width = CGFloat(10), height = CGFloat(6), y = postTitleLabel.height let path = UIBezierPath() path.moveToPoint(CGPointZero) path.addLineToPoint(CGPoint(x: width, y: 0)) path.addLineToPoint(CGPoint(x: CGFloat(width/2), y: height)) path.closePath() self.markLayer = CAShapeLayer() markLayer.path = path.CGPath markLayer.fillColor = postTitleLabel.backgroundColor!.CGColor markLayer.position = CGPoint(x: x, y: y) markLayer.actions = ["fillColor":NSNull()] contentView.layer.addSublayer(markLayer) } func updateCell(dataModel: NotificationModel) -> Void { contentLabel.text = dataModel.content dateTimeLabel.text = dataModel.smart_time let title = " " + dataModel.member.username + " 在 " + dataModel.title + " 中提到了你" as NSString let attributedStr = NSMutableAttributedString(string: title as String) let range = title.rangeOfString(dataModel.member.username) attributedStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(12), range: range) postTitleLabel.attributedText = attributedStr } func cellSelected(selected: Bool, animated: Bool) { markLayer.actions = animated ? nil : ["fillColor":NSNull()] if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.changeColor(selected) }) } else { changeColor(selected) } } func changeColor(selected: Bool) { contentView.backgroundColor = selected ? UIColor.colorWithHexString("#d9d9d9") : UIColor.whiteColor() } }
mit
2540a8f01fbb593f7ac3a703d3e51bd4
35.592593
109
0.656545
4.827362
false
false
false
false
edwellbrook/gosquared-swift
Sources/Now.swift
1
6894
// // Now.swift // GoSquaredAPI // // Created by Edward Wellbrook on 22/05/2015. // Copyright (c) 2015-2016 Edward Wellbrook. All rights reserved. // import Foundation public class Now { private let client: GoSquaredAPI private let basePath: String internal init(client: GoSquaredAPI) { self.client = client self.basePath = "/now/v3" } // // docs: // https://www.gosquared.com/docs/api/now/browsers/http/#retrieve_list_of_browsers // public func browsers() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/browsers" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/campaigns/ // public func campaigns() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/campaigns" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/concurrents/ // public func concurrents() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/concurrents" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/engagement/ // public func engagement() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/engagement" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs // https://www.gosquared.com/developer/api/now/v3/geo/ // public func geo() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/geo" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/overview/ // public func overview() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/overview" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/pages/ // public func pages() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/pages" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/sources/ // public func sources() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/sources" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/timeSeries/ // public func timeSeries() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/timeSeries" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/developer/api/now/v3/visitors/ // public func visitors() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/visitors" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // https://www.gosquared.com/docs/api/combining-functions // public func combiningFunction(functions funcs: [GoSquaredAPI.CombiningFunction]) -> URLRequest { let functions: [(name: String, params: [URLQueryItem])] = funcs.enumerated().map { index, function in let name = "\(function.endpoint):\(index)" let params = function.parameters.map({ URLQueryItem(name: "\(name):\($0)", value: $1) }) return (name, params) } let functionList = functions.map({ $0.name }).joined(separator: ",") var queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] for function in functions { queryItems.append(contentsOf: function.params) } let path = "\(self.basePath)/\(functionList)" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } }
mit
a5bd9c2f3667a060b60a5db93b15cfc7
31.828571
109
0.606179
3.932687
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
Source/SQLite/SQLiteDB.swift
1
7123
// // Copyright (C) 2015-2020 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation import SQLite3 // swiftlint:disable identifier_name /// Represents error of SQLite @objc(VSSSQLiteError) public class SQLiteError: NSObject, LocalizedError { // Code of error public let errorNum: Int32? internal init(errorNum: Int32? = nil) { self.errorNum = errorNum super.init() } /// Error description @objc public var errorDescription: String? { guard let errorNum = self.errorNum else { return "Unknown SQLite error." } return String(cString: sqlite3_errstr(errorNum)) } } /// SQLiteDB public class SQLiteDB: NSObject { /// Generates statement /// - Parameter statement: statement string /// - Throws: SQLiteError /// - Returns: generated statement public func generateStmt(statement: String) throws -> Statement { var stmt: OpaquePointer? let res = sqlite3_prepare_v2(self.handle, statement, -1, &stmt, nil) guard res == SQLITE_OK else { throw SQLiteError(errorNum: res) } guard let s = stmt else { throw SQLiteError() } return Statement(stmt: s) } private let handle: OpaquePointer /// DB file path public let path: String /// Init /// - Parameters: /// - appGroup: security application group identifier /// - prefix: file path prefix /// - userIdentifier: user identifier /// - name: db file name /// - Throws: /// - SQLiteError /// - Rethrows from `FileManager` public init(appGroup: String?, prefix: String, userIdentifier: String, name: String) throws { var url: URL if let appGroup = appGroup { guard let sharedContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else { throw NSError(domain: "FileManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "Security application group identifier is invalid"]) } url = sharedContainer } else { url = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) } url.appendPathComponent(prefix) url.appendPathComponent(userIdentifier) try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) url.appendPathComponent(name) var h: OpaquePointer? let path = url.absoluteString self.path = path let res = sqlite3_open_v2(path, &h, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_URI, nil) guard res == SQLITE_OK else { throw SQLiteError(errorNum: res) } guard let handle = h else { throw SQLiteError() } self.handle = handle } /// Executes statement without output values /// - Parameter statement: statement /// - Throws: `SQLiteError` public func executeNoResult(statement: String) throws { let stmt = try self.generateStmt(statement: statement) try self.executeNoResult(statement: stmt) } /// Executes statement without output values /// - Parameter statement: statement string /// - Throws: `SQLiteError` public func executeNoResult(statement: Statement) throws { let res = sqlite3_step(statement.stmt) guard res == SQLITE_DONE else { throw SQLiteError(errorNum: res) } } /// Executes statement with output values /// - Parameter statement: statement /// - Throws: `SQLiteError` /// - Returns: Returns true if output values are available public func executeStep(statement: Statement) throws -> Bool { let res = sqlite3_step(statement.stmt) switch res { case SQLITE_DONE: return false case SQLITE_ROW: return true default: throw SQLiteError(errorNum: res) } } /// Binds input argument /// - Parameters: /// - stmt: statement /// - index: index of input argument /// - value: value of input argument /// - Throws: `SQLiteError` public func bindIn<T>(stmt: Statement, index: Int32, value: T?) throws where T: DbInValue { guard let value = value else { let res = sqlite3_bind_null(stmt.stmt, index) guard res == SQLITE_OK else { throw SQLiteError(errorNum: res) } return } try value.dumpTo(stmt: stmt, index: index) } /// Binds output values /// - Parameters: /// - stmt: statement /// - index: output value /// - Returns: `SQLiteError` public func bindOut<T>(stmt: Statement, index: Int32) -> T? where T: DbOutValue { return T(stmt: stmt, index: index) } deinit { guard sqlite3_close(self.handle) == SQLITE_OK else { fatalError() } } }
bsd-3-clause
acda30e8fd5130b8a01129dcded8383c
30.657778
120
0.599467
4.865437
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift
25
13833
// // ShareReplayScope.swift // RxSwift // // Created by Krunoslav Zaher on 5/28/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // /// Subject lifetime scope public enum SubjectLifetimeScope { /** **Each connection will have it's own subject instance to store replay events.** **Connections will be isolated from each another.** Configures the underlying implementation to behave equivalent to. ``` source.multicast(makeSubject: { MySubject() }).refCount() ``` **This is the recommended default.** This has the following consequences: * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. * Each connection to source observable sequence will use it's own subject. * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .whileConnected) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is different and `Performing work ...` is printed each time) ``` Performing work ... next 1495998900.82141 completed Performing work ... next 1495998900.82359 completed Performing work ... next 1495998900.82444 completed ``` */ case whileConnected /** **One subject will store replay events for all connections to source.** **Connections won't be isolated from each another.** Configures the underlying implementation behave equivalent to. ``` source.multicast(MySubject()).refCount() ``` This has the following consequences: * Using `retry` or `concat` operators after this operator usually isn't advised. * Each connection to source observable sequence will share the same subject. * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will continue holding a reference to the same subject. If at some later moment a new observer initiates a new connection to source it can potentially receive some of the stale events received during previous connection. * After source sequence terminates any new observer will always immediatelly receive replayed elements and terminal event. No new subscriptions to source observable sequence will be attempted. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .forever) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is the same, replayed, and `Performing work ...` is printed only once ``` Performing work ... next 1495999013.76356 completed next 1495999013.76356 completed next 1495999013.76356 completed ``` */ case forever } extension ObservableType { /** Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. This operator is equivalent to: * `.whileConnected` ``` // Each connection will have it's own subject instance to store replay events. // Connections will be isolated from each another. source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() ``` * `.forever` ``` // One subject will store replay events for all connections to source. // Connections won't be isolated from each another. source.multicast(Replay.create(bufferSize: replay)).refCount() ``` It uses optimized versions of the operators for most common operations. - parameter replay: Maximum element count of the replay buffer. - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) -> Observable<E> { switch scope { case .forever: switch replay { case 0: return self.multicast(PublishSubject()).refCount() default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() } case .whileConnected: switch replay { case 0: return ShareWhileConnected(source: self.asObservable()) case 1: return ShareReplay1WhileConnected(source: self.asObservable()) default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() } } } } fileprivate final class ShareReplay1WhileConnectedConnection<Element> : ObserverType , SynchronizedUnsubscribeType { typealias E = Element typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareReplay1WhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() fileprivate var _element: Element? init(parent: Parent, lock: RecursiveLock) { _parent = parent _lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<E>) { _lock.lock() let observers = _synchronized_on(event) _lock.unlock() dispatch(observers, event) } final private func _synchronized_on(_ event: Event<E>) -> Observers { if _disposed { return Observers() } switch event { case .next(let element): _element = element return _observers case .error, .completed: let observers = _observers self._synchronized_dispose() return observers } } final func connect() { _subscription.setDisposable(_parent._source.subscribe(self)) } final func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock(); defer { _lock.unlock() } if let element = _element { observer.on(.next(element)) } let disposeKey = _observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } final private func _synchronized_dispose() { _disposed = true if _parent._connection === self { _parent._connection = nil } _observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() let shouldDisconnect = _synchronized_unsubscribe(disposeKey) _lock.unlock() if shouldDisconnect { _subscription.dispose() } } @inline(__always) final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return false } if _observers.count == 0 { _synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case final fileprivate class ShareReplay1WhileConnected<Element> : Observable<Element> { fileprivate typealias Connection = ShareReplay1WhileConnectedConnection<Element> fileprivate let _source: Observable<Element> fileprivate let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock() let connection = _synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) _lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Connection where O.E == E { let connection: Connection if let existingConnection = _connection { connection = existingConnection } else { connection = ShareReplay1WhileConnectedConnection<Element>( parent: self, lock: _lock) _connection = connection } return connection } } fileprivate final class ShareWhileConnectedConnection<Element> : ObserverType , SynchronizedUnsubscribeType { typealias E = Element typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareWhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() init(parent: Parent, lock: RecursiveLock) { _parent = parent _lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<E>) { _lock.lock() let observers = _synchronized_on(event) _lock.unlock() dispatch(observers, event) } final private func _synchronized_on(_ event: Event<E>) -> Observers { if _disposed { return Observers() } switch event { case .next: return _observers case .error, .completed: let observers = _observers self._synchronized_dispose() return observers } } final func connect() { _subscription.setDisposable(_parent._source.subscribe(self)) } final func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock(); defer { _lock.unlock() } let disposeKey = _observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } final private func _synchronized_dispose() { _disposed = true if _parent._connection === self { _parent._connection = nil } _observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() let shouldDisconnect = _synchronized_unsubscribe(disposeKey) _lock.unlock() if shouldDisconnect { _subscription.dispose() } } @inline(__always) final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return false } if _observers.count == 0 { _synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case final fileprivate class ShareWhileConnected<Element> : Observable<Element> { fileprivate typealias Connection = ShareWhileConnectedConnection<Element> fileprivate let _source: Observable<Element> fileprivate let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock() let connection = _synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) _lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Connection where O.E == E { let connection: Connection if let existingConnection = _connection { connection = existingConnection } else { connection = ShareWhileConnectedConnection<Element>( parent: self, lock: _lock) _connection = connection } return connection } }
mit
736820b0f3b5fbf8349d525ca0e84374
29.200873
164
0.625651
4.97733
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Money/Tests/MoneyKitTests/MoneyValuePairExchangeRateTests.swift
1
4365
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import XCTest final class MoneyValuePairExchangeRateTests: XCTestCase { func test_inverts_pair_fiat_to_crypto() { // GIVEN: The exchange rate USD-BTC let originalPair = MoneyValuePair( base: .one(currency: .USD), exchangeRate: MoneyValue( amount: 3357, currency: .crypto(.bitcoin) ) ) XCTAssertEqual(originalPair.quote.displayString, "0.00003357 BTC") // WHEN: Getting the inverse quote let inversePair = originalPair.inverseQuote // THEN: The inverted quote should be the equivalent value for BTC-USD (1 / the original quote) XCTAssertEqual(inversePair.quote.displayString, "$29,788.50") let expectedInversePair = MoneyValuePair( base: .one(currency: .crypto(.bitcoin)), exchangeRate: .init(amount: 2978850, currency: .fiat(.USD)) ) XCTAssertEqual(inversePair, expectedInversePair) } func test_inverts_pair_crypto_to_fiat() { // GIVEN: The exchange rate BTC-USD let originalPair = MoneyValuePair( base: .one(currency: .crypto(.bitcoin)), exchangeRate: MoneyValue( amount: 2978850, currency: .fiat(.USD) ) ) XCTAssertEqual(originalPair.quote.displayString, "$29,788.50") // WHEN: Getting the inverse quote let inversePair = originalPair.inverseQuote // THEN: The inverted quote should be the equivalent value for USD-BTC (1 / the original quote) XCTAssertEqual(inversePair.quote.displayString, "0.00003357 BTC") let expectedInversePair = MoneyValuePair( base: .one(currency: .USD), exchangeRate: .init( amount: 000003357, currency: .crypto(.bitcoin) ) ) XCTAssertEqual(inversePair, expectedInversePair) } func test_inverts_with_non_one_base() { // GIVEN: A FX where the bsse is non-1 let originalPair = MoneyValuePair( base: CryptoValue.create(major: "5", currency: .ethereum)!, exchangeRate: FiatValue.create(major: "800", currency: .USD)! ) XCTAssertEqual(originalPair.quote.displayString, "$4,000.00") // WHEN: Getting the inverse quote let inversePair = originalPair.inverseQuote // THEN: The inverse should return a 1 based FX anyway let expectedInversePair = MoneyValuePair( base: .one(currency: .fiat(.USD)), quote: .create(major: "0.00125", currency: .crypto(.ethereum))! ) XCTAssertEqual(inversePair, expectedInversePair) } func test_inverting_a_zero_based_pair_returns_zero() { // GIVEN: A FX where the bsse is 0 let originalPair = MoneyValuePair( base: .zero(currency: .ethereum), // doesn't matter what the exchange rate is: the pair is invalid exchangeRate: FiatValue.create(major: "800", currency: .USD)! ) XCTAssertEqual(originalPair.quote.displayString, "$0.00") // WHEN: Getting the inverse quote let inversePair = originalPair.inverseExchangeRate // THEN: The inverse should return a 1 based FX anyway let expectedInversePair: MoneyValuePair = .zero( baseCurrency: .fiat(.USD), quoteCurrency: .crypto(.ethereum) ) XCTAssertEqual(inversePair, expectedInversePair) } func test_inverting_a_zero_quoted_pair_returns_zero() { // GIVEN: A FX where the bsse is 0 let originalPair = MoneyValuePair( base: .one(currency: .ethereum), // doesn't matter what the exchange rate is: the pair is invalid exchangeRate: .zero(currency: .fiat(.USD)) ) XCTAssertEqual(originalPair.quote.displayString, "$0.00") // WHEN: Getting the inverse quote let inversePair = originalPair.inverseExchangeRate // THEN: The inverse should return a 1 based FX anyway let expectedInversePair: MoneyValuePair = .zero( baseCurrency: .fiat(.USD), quoteCurrency: .crypto(.ethereum) ) XCTAssertEqual(inversePair, expectedInversePair) } }
lgpl-3.0
3d1cf1d4175179b75e58b6cb0bdf9009
36.947826
103
0.617553
4.541103
false
true
false
false
jopamer/swift
test/ClangImporter/objc_redeclared_properties.swift
2
1807
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -typecheck -I %S/Inputs/custom-modules -D ONE_MODULE %s -verify // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -typecheck -I %S/Inputs/custom-modules -D SUB_MODULE %s -verify // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -typecheck -I %S/Inputs/custom-modules -D TWO_MODULES %s -verify #if ONE_MODULE import RedeclaredProperties #elseif SUB_MODULE import RedeclaredPropertiesSub import RedeclaredPropertiesSub.Private #elseif TWO_MODULES import RedeclaredPropertiesSplit import RedeclaredPropertiesSplit2 #endif func test(obj: RPFoo) { if let _ = obj.nonnullToNullable {} // expected-error {{initializer for conditional binding must have Optional type}} obj.nonnullToNullable = obj // expected-error {{cannot assign to property: 'nonnullToNullable' is a get-only property}} if let _ = obj.nullableToNonnull {} // okay obj.nullableToNonnull = obj // expected-error {{cannot assign to property: 'nullableToNonnull' is a get-only property}} let _: RPFoo = obj.typeChangeMoreSpecific // expected-error {{cannot convert value of type 'Any' to specified type 'RPFoo'}} obj.typeChangeMoreSpecific = obj // expected-error {{cannot assign to property: 'typeChangeMoreSpecific' is a get-only property}} let _: RPFoo = obj.typeChangeMoreGeneral obj.typeChangeMoreGeneral = obj // expected-error {{cannot assign to property: 'typeChangeMoreGeneral' is a get-only property}} if let _ = obj.accessorRedeclaredAsNullable {} // expected-error {{initializer for conditional binding must have Optional type}} if let _ = obj.accessorDeclaredFirstAsNullable {} // expected-error {{initializer for conditional binding must have Optional type}} }
apache-2.0
f3f3751d3b8ecdf84f37c9b597de7d13
59.233333
147
0.76591
3.836518
false
false
false
false
alblue/swift-corelibs-foundation
Foundation/HTTPCookieStorage.swift
1
16177
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import Dispatch import CoreFoundation /*! @enum HTTPCookie.AcceptPolicy @abstract Values for the different cookie accept policies @constant HTTPCookie.AcceptPolicy.always Accept all cookies @constant HTTPCookie.AcceptPolicy.never Reject all cookies @constant HTTPCookie.AcceptPolicy.onlyFromMainDocumentDomain Accept cookies only from the main document domain */ extension HTTPCookie { public enum AcceptPolicy : UInt { case always case never case onlyFromMainDocumentDomain } } /*! @class HTTPCookieStorage @discussion HTTPCookieStorage implements a singleton object (shared instance) which manages the shared cookie store. It has methods to allow clients to set and remove cookies, and get the current set of cookies. It also has convenience methods to parse and generate cookie-related HTTP header fields. */ open class HTTPCookieStorage: NSObject { /* both sharedStorage and sharedCookieStorages are synchronized on sharedSyncQ */ private static var sharedStorage: HTTPCookieStorage? private static var sharedCookieStorages: [String: HTTPCookieStorage] = [:] //for group storage containers private static let sharedSyncQ = DispatchQueue(label: "org.swift.HTTPCookieStorage.sharedSyncQ") /* only modified in init */ private var cookieFilePath: String! /* synchronized on syncQ, please don't use _allCookies directly outside of init/deinit */ private var _allCookies: [String: HTTPCookie] private var allCookies: [String: HTTPCookie] { get { if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { dispatchPrecondition(condition: DispatchPredicate.onQueue(self.syncQ)) } return self._allCookies } set { if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { dispatchPrecondition(condition: DispatchPredicate.onQueue(self.syncQ)) } self._allCookies = newValue } } private let syncQ = DispatchQueue(label: "org.swift.HTTPCookieStorage.syncQ") private init(cookieStorageName: String) { _allCookies = [:] cookieAcceptPolicy = .always super.init() let bundlePath = Bundle.main.bundlePath var bundleName = bundlePath.components(separatedBy: "/").last! if let range = bundleName.range(of: ".", options: .backwards, range: nil, locale: nil) { bundleName = String(bundleName[..<range.lowerBound]) } let cookieFolderPath = _CFXDGCreateDataHomePath()._swiftObject + "/" + bundleName cookieFilePath = filePath(path: cookieFolderPath, fileName: "/.cookies." + cookieStorageName, bundleName: bundleName) loadPersistedCookies() } private func loadPersistedCookies() { guard let cookiesData = try? Data(contentsOf: URL(fileURLWithPath: cookieFilePath)) else { return } guard let cookies = try? PropertyListSerialization.propertyList(from: cookiesData, format: nil) else { return } var cookies0 = cookies as? [String: [String: Any]] ?? [:] self.syncQ.sync { for key in cookies0.keys { if let cookie = createCookie(cookies0[key]!) { allCookies[key] = cookie } } } } private func directory(with path: String) -> Bool { guard !FileManager.default.fileExists(atPath: path) else { return true } do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) return true } catch { return false } } private func filePath(path: String, fileName: String, bundleName: String) -> String { if directory(with: path) { return path + fileName } //if we were unable to create the desired directory, create the cookie file //in a subFolder (named after the bundle) of the `pwd` return FileManager.default.currentDirectoryPath + "/" + bundleName + fileName } open var cookies: [HTTPCookie]? { return Array(self.syncQ.sync { self.allCookies.values }) } /*! @method sharedHTTPCookieStorage @abstract Get the shared cookie storage in the default location. @result The shared cookie storage @discussion Starting in OS X 10.11, each app has its own sharedHTTPCookieStorage singleton, which will not be shared with other applications. */ open class var shared: HTTPCookieStorage { get { return sharedSyncQ.sync { if sharedStorage == nil { sharedStorage = HTTPCookieStorage(cookieStorageName: "shared") } return sharedStorage! } } } /*! @method sharedCookieStorageForGroupContainerIdentifier: @abstract Get the cookie storage for the container associated with the specified application group identifier @param identifier The application group identifier @result A cookie storage with a persistent store in the application group container @discussion By default, applications and associated app extensions have different data containers, which means that the sharedHTTPCookieStorage singleton will refer to different persistent cookie stores in an application and any app extensions that it contains. This method allows clients to create a persistent cookie storage that can be shared among all applications and extensions with access to the same application group. Subsequent calls to this method with the same identifier will return the same cookie storage instance. */ open class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage { return sharedSyncQ.sync { guard let cookieStorage = sharedCookieStorages[identifier] else { let newCookieStorage = HTTPCookieStorage(cookieStorageName: identifier) sharedCookieStorages[identifier] = newCookieStorage return newCookieStorage } return cookieStorage } } /*! @method setCookie: @abstract Set a cookie @discussion The cookie will override an existing cookie with the same name, domain and path, if any. */ open func setCookie(_ cookie: HTTPCookie) { self.syncQ.sync { guard cookieAcceptPolicy != .never else { return } //add or override let key = cookie.domain + cookie.path + cookie.name if let _ = allCookies.index(forKey: key) { allCookies.updateValue(cookie, forKey: key) } else { allCookies[key] = cookie } //remove stale cookies, these may include the one we just added let expired = allCookies.filter { (_, value) in value.expiresDate != nil && value.expiresDate!.timeIntervalSinceNow < 0 } for (key,_) in expired { self.allCookies.removeValue(forKey: key) } updatePersistentStore() } } open override var description: String { return "<NSHTTPCookieStorage cookies count:\(cookies?.count ?? 0)>" } private func createCookie(_ properties: [String: Any]) -> HTTPCookie? { var cookieProperties: [HTTPCookiePropertyKey: Any] = [:] for (key, value) in properties { if key == "Expires" { guard let timestamp = value as? NSNumber else { continue } cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = Date(timeIntervalSince1970: timestamp.doubleValue) } else { cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = properties[key] } } return HTTPCookie(properties: cookieProperties) } private func updatePersistentStore() { if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { dispatchPrecondition(condition: DispatchPredicate.onQueue(self.syncQ)) } //persist cookies var persistDictionary: [String : [String : Any]] = [:] let persistable = self.allCookies.filter { (_, value) in value.expiresDate != nil && value.isSessionOnly == false && value.expiresDate!.timeIntervalSinceNow > 0 } for (key,cookie) in persistable { persistDictionary[key] = cookie.persistableDictionary() } let nsdict = _SwiftValue.store(persistDictionary) as! NSDictionary _ = nsdict.write(toFile: cookieFilePath, atomically: true) } /*! @method lockedDeleteCookie: @abstract Delete the specified cookie, for internal callers already on syncQ. */ private func lockedDeleteCookie(_ cookie: HTTPCookie) { let key = cookie.domain + cookie.path + cookie.name self.allCookies.removeValue(forKey: key) updatePersistentStore() } /*! @method deleteCookie: @abstract Delete the specified cookie */ open func deleteCookie(_ cookie: HTTPCookie) { self.syncQ.sync { self.lockedDeleteCookie(cookie) } } /*! @method removeCookiesSince: @abstract Delete all cookies from the cookie storage since the provided date. */ open func removeCookies(since date: Date) { self.syncQ.sync { let cookiesSinceDate = self.allCookies.values.filter { $0.properties![.created] as! Double > date.timeIntervalSinceReferenceDate } for cookie in cookiesSinceDate { lockedDeleteCookie(cookie) } updatePersistentStore() } } /*! @method cookiesForURL: @abstract Returns an array of cookies to send to the given URL. @param URL The URL for which to get cookies. @result an Array of HTTPCookie objects. @discussion The cookie manager examines the cookies it stores and includes those which should be sent to the given URL. You can use <tt>+[NSCookie requestHeaderFieldsWithCookies:]</tt> to turn this array into a set of header fields to add to a request. */ open func cookies(for url: URL) -> [HTTPCookie]? { guard let host = url.host?.lowercased() else { return nil } return Array(self.syncQ.sync(execute: {allCookies}).values.filter{ $0.validFor(host: host) }) } /*! @method setCookies:forURL:mainDocumentURL: @abstract Adds an array cookies to the cookie store, following the cookie accept policy. @param cookies The cookies to set. @param URL The URL from which the cookies were sent. @param mainDocumentURL The main document URL to be used as a base for the "same domain as main document" policy. @discussion For mainDocumentURL, the caller should pass the URL for an appropriate main document, if known. For example, when loading a web page, the URL of the main html document for the top-level frame should be passed. To save cookies based on a set of response headers, you can use <tt>+[NSCookie cookiesWithResponseHeaderFields:forURL:]</tt> on a header field dictionary and then use this method to store the resulting cookies in accordance with policy settings. */ open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) { //if the cookieAcceptPolicy is `never` we don't have anything to do guard cookieAcceptPolicy != .never else { return } //if the urls don't have a host, we cannot do anything guard let urlHost = url?.host?.lowercased() else { return } if mainDocumentURL != nil && cookieAcceptPolicy == .onlyFromMainDocumentDomain { guard let mainDocumentHost = mainDocumentURL?.host?.lowercased() else { return } //the url.host must be a suffix of manDocumentURL.host, this is based on Darwin's behaviour guard mainDocumentHost.hasSuffix(urlHost) else { return } } //save only those cookies whose domain matches with the url.host let validCookies = cookies.filter { $0.validFor(host: urlHost) } for cookie in validCookies { setCookie(cookie) } } /*! @method cookieAcceptPolicy @abstract The cookie accept policy preference of the receiver. */ open var cookieAcceptPolicy: HTTPCookie.AcceptPolicy /*! @method sortedCookiesUsingDescriptors: @abstract Returns an array of all cookies in the store, sorted according to the key value and sorting direction of the NSSortDescriptors specified in the parameter. @param sortOrder an array of NSSortDescriptors which represent the preferred sort order of the resulting array. @discussion proper sorting of cookies may require extensive string conversion, which can be avoided by allowing the system to perform the sorting. This API is to be preferred over the more generic -[HTTPCookieStorage cookies] API, if sorting is going to be performed. */ open func sortedCookies(using sortOrder: [NSSortDescriptor]) -> [HTTPCookie] { NSUnimplemented() } } extension Notification.Name { /*! @const NSHTTPCookieManagerCookiesChangedNotification @abstract Notification sent when the set of cookies changes */ public static let NSHTTPCookieManagerCookiesChanged = Notification.Name(rawValue: "NSHTTPCookieManagerCookiesChangedNotification") } extension HTTPCookie { internal func validFor(host: String) -> Bool { // RFC6265 - HTTP State Management Mechanism // https://tools.ietf.org/html/rfc6265#section-5.1.3 // // 5.1.3. Domain Matching // A string domain-matches a given domain string if at least one of the // following conditions hold: // // 1) The domain string and the string are identical. (Note that both // the domain string and the string will have been canonicalized to // lower case at this point.) // // 2) All of the following conditions hold: // * The domain string is a suffix of the string. // * The last character of the string that is not included in the // domain string is a %x2E (".") character. // * The string is a host name (i.e., not an IP address). guard domain.hasPrefix(".") else { return host == domain } return host == domain.dropFirst() || host.hasSuffix(domain) } internal func persistableDictionary() -> [String: Any] { var properties: [String: Any] = [:] properties[HTTPCookiePropertyKey.name.rawValue] = name properties[HTTPCookiePropertyKey.path.rawValue] = path properties[HTTPCookiePropertyKey.value.rawValue] = _value properties[HTTPCookiePropertyKey.secure.rawValue] = _secure properties[HTTPCookiePropertyKey.version.rawValue] = _version properties[HTTPCookiePropertyKey.expires.rawValue] = _expiresDate?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 //OK? properties[HTTPCookiePropertyKey.domain.rawValue] = _domain if let commentURL = _commentURL { properties[HTTPCookiePropertyKey.commentURL.rawValue] = commentURL.absoluteString } if let comment = _comment { properties[HTTPCookiePropertyKey.comment.rawValue] = comment } properties[HTTPCookiePropertyKey.port.rawValue] = portList return properties } }
apache-2.0
c9bc936481ff3c75be88df6c62ce2982
41.909814
274
0.654077
5.050578
false
false
false
false
coinbase/coinbase-ios-sdk
Source/Utils/Logging.swift
1
3639
// // Logging.swift // Coinbase // // Copyright © 2018 Coinbase, Inc. All rights reserved. // import Foundation /// Logging message category. /// /// - Important: /// For **Release** Build Configuration only `LoggingCategory.error` can be enabled. /// /// - info: Verbose information. /// /// Available only in `Debug` Build Configuration. /// /// - `warning`: Warning messages to notify the developer of best practices, /// implementation suggestions or deprecation. /// /// Available only in `Debug` Build Configuration. /// /// - error: Error message. /// /// Available in both `Debug` and `Release` Build Configurations. /// public enum LoggingCategory: String { /// Verbose information. /// /// Available only in `Debug` Build Configuration. /// case info /// Warning messages to notify the developer of best practices, /// implementation suggestions or deprecation. /// /// Available only in `Debug` Build Configuration. /// case warning /// Error message. /// /// Available in both `Debug` and `Release` Build Configurations. /// case error internal var canBeEnabled: Bool { #if DEBUG return true #else return self == .error #endif } } /// Responsible for SDK's logging functionality. public struct CoinbaseLogger { /// Set of enabled categories. /// /// - Note: /// Default value depends on `Debug/Release` Build Configuration flag: /// - For **Debug** configuration: it is `LoggingCategory.warning` and `LoggingCategory.error`. /// - For **Release** configuration: it is `LoggingCategory.error`. /// public static var enabled: Set<LoggingCategory> = { #if DEBUG return [.warning, .error] #else return [.error] #endif }() { didSet { enabled = enabled.filter { category -> Bool in guard category.canBeEnabled else { log("\(self) | Category \"LoggingCategory.\(category)\" wasn't enabled. This category is supported only in Debug Configuration.", category: .error) return false } return true } } } } /// Logs message. /// /// - Note: /// Mesage will be printed only if provided logging category is enabled. /// /// - Parameters: /// - message: Message to print. /// - category: Log category for message. /// internal func log(_ message: String, category: LoggingCategory = LoggingCategory.info) { if CoinbaseLogger.enabled.contains(category) { let output = "\(NSDate()) CoinbaseSDK[\(category.rawValue)] \(message)" print(output) } } // MARK: - Extensions with log discription property internal extension URLRequest { var logDiscription: String { return "\(httpMethod ?? "") \(url?.absoluteString ?? "")" } } internal extension ResourceAPIProtocol { var logDiscription: String { return "method: \"\(method.rawValue.uppercased())\" path: \"..\(path)\"" } var nameDiscription: String { return "\(type(of: self)) \(String(describing: self))" } } internal extension Warning { func log(with api: ResourceAPIProtocol) -> String { let reference: String if let url = url { reference = ". More info can be found at: \"\(url)\"" } else { reference = "" } return "Server Warning | \(api.logDiscription) | id: \"\(id)\", message: \"\(message)\"\(reference)" } }
apache-2.0
13ae936d22170245d52c60cafb4b83d0
25.948148
167
0.586861
4.502475
false
true
false
false
alexandreblin/ios-car-dashboard
CarDash/BlurredView.swift
1
1816
// // BlurredView.swift // CarDash // // Created by Alexandre Blin on 03/07/2016. // Copyright © 2016 Alexandre Blin. All rights reserved. // import UIKit /// A view with rounded corners and a blurred translucent background class BlurredView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } func setupView() { translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.clear let blurEffect = UIBlurEffect(style: .light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] blurEffectView.frame = bounds addSubview(blurEffectView) sendSubview(toBack: blurEffectView) layer.cornerRadius = 10 layer.masksToBounds = true } /// Adds the view to a superview and add constraints to /// center it vertically and horizontally /// /// - Parameter view: The superview to add the view to func addToView(_ view: UIView) { translatesAutoresizingMaskIntoConstraints = false view.addSubview(self) view.addConstraint(NSLayoutConstraint( item: self, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0 )) view.addConstraint(NSLayoutConstraint( item: self, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0.0 )) } }
mit
12d449d705f540c9498ba49f35b28b15
24.208333
75
0.602204
5.069832
false
false
false
false
khanlou/NonEmptyArray
NonEmptyArrayTests/NonEmptyArrayTests.swift
1
2388
// // NonEmptyArrayTests.swift // NonEmptyArrayTests // // Created by Soroush Khanlou on 10/15/16. // Copyright © 2016 Soroush Khanlou. All rights reserved. // import XCTest import NonEmptyArray class NonEmptyArrayTests: XCTestCase { let nilArray = NonEmptyArray(array: []) let notNilArray = NonEmptyArray(array: [1, 2, 3]) let array = NonEmptyArray(elements: 1, 2, 3) func testEmptyArrayInitializers() { XCTAssertNil(nilArray) XCTAssertNotNil(notNilArray) XCTAssertNil(NonEmptyArray<Int>()) } func testSequenceInitializer() { let sequenceInitalized = NonEmptyArray(AnySequence([1, 2, 3])) if let nonEmptyArray = sequenceInitalized { XCTAssertTrue(array == nonEmptyArray) } else { XCTFail() } XCTAssertNil(NonEmptyArray(AnySequence([]))) } func testArray() { XCTAssertEqual(array.count, 3) } func testNonOptionalMethods() { XCTAssert(type(of: array.min()) == Int.self) XCTAssert(type(of: array.min()) != Optional<Int>.self) XCTAssert(type(of: array.max()) == Int.self) XCTAssert(type(of: array.max()) != Optional<Int>.self) XCTAssert(type(of: array.first) == Int.self) XCTAssert(type(of: array.first) != Optional<Int>.self) XCTAssert(type(of: array.last) == Int.self) XCTAssert(type(of: array.last) != Optional<Int>.self) } func testDescriptions() { XCTAssertEqual(array.description, "[1, 2, 3]") XCTAssertEqual(array.debugDescription, "[1, 2, 3]") } func testSubscripting() { XCTAssertEqual(array[0], 1) XCTAssertEqual(array[1], 2) XCTAssertEqual(array[2], 3) XCTAssertEqual(array[1..<2].first, 2) } func testSubscriptMutation() { var copy = array copy[0] = 0 XCTAssertEqual(copy[0], 0, "A mutable Array should support subscript set operation.") } func testSequence() { let anySequence = AnySequence(array) let count = anySequence.reduce(0, { $0.0 + 1 }) XCTAssertEqual(count, array.count) } func testCollection() { let anyCollection = AnyCollection(array) let count = anyCollection.reduce(0, { $0.0 + 1 }) XCTAssertEqual(count, array.count) } }
mit
08fef9adf9746a30c339d1f0e1f6caf8
26.755814
93
0.60243
4.187719
false
true
false
false
rsyncOSX/RsyncOSX
RsyncOSX/Notifications.swift
1
747
// // Notifications.swift // RsyncOSXsched // // Created by Thomas Evensen on 21.02.2018. // Copyright © 2018 Maxim. All rights reserved. // import Foundation import UserNotifications struct Notifications { func showNotification(_ message: String) { let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = "A notifiction from RsyncOSX" content.subtitle = message content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) center.add(request) } }
mit
e618737bcfe328ae8f8cdad3ea11b1ed
31.434783
110
0.710456
4.940397
false
false
false
false
FirebaseExtended/codelab-contentrecommendation-ios
start/ContentRecommendations/RecommendationsViewController.swift
1
3235
// Copyright 2020 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit class RecommendationsViewController: UITableViewController { private let reuseIdentifier = "RecommendationCell" private var recommendations = [Recommendation]() //DEFINE INTERPRETER HERE func loadModel() { // LOAD MODEL HERE } // GET MOVIES HERE func getLikedMovies() -> [MovieItem] { let barController = self.tabBarController as! TabBarController return barController.movies.filter { $0.liked == true } } // PREPROCESS HERE // LOAD INTERPRETER HERE // POSTPROCESS HERE override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadModel() } override func viewDidLoad() { super.viewDidLoad() loadModel() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return recommendations.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) let recommendation = recommendations[indexPath.row] let displayText = "Title: \(recommendation.title)\nConfidence: \(recommendation.confidence)\n" cell.textLabel?.text = displayText.trimmingCharacters(in: .whitespacesAndNewlines) cell.textLabel?.numberOfLines = 0 return cell } } struct Recommendation { let title: String let confidence: Float32 } extension Int32 { var data: Data { var int = self return Data(bytes: &int, count: MemoryLayout<Int>.size) } } extension Data { /// Creates a new buffer by copying the buffer pointer of the given array. /// /// - Warning: The given array's element type `T` must be trivial in that it can be copied bit /// for bit with no indirection or reference-counting operations; otherwise, reinterpreting /// data from the resulting buffer has undefined behavior. /// - Parameter array: An array with elements of type `T`. init<T>(copyingBufferOf array: [T]) { self = array.withUnsafeBufferPointer(Data.init) } /// Convert a Data instance to Array representation. func toArray<T>(type: T.Type) -> [T] where T: AdditiveArithmetic { var array = [T](repeating: T.zero, count: self.count / MemoryLayout<T>.stride) _ = array.withUnsafeMutableBytes { self.copyBytes(to: $0) } return array } }
apache-2.0
a4acde996c26784465ad21b43e0ad2a9
30.407767
107
0.71932
4.480609
false
false
false
false
bppr/Swiftest
src/Swiftest/Client/Run.swift
1
615
@_exported import OS func runSpec(spec: Specification) throws { Swiftest.reporter.started(spec) for example in spec.examples { try context.withExample(example, fn: Example.run(example, spec: spec)) } for child in spec.children { try runSpec(child) } Swiftest.reporter.finished(spec) } public func run() throws { for hook in context.beforeHooks { hook() } Swiftest.reporter.suiteStarted() let failures = try context.currentSpec.children.filter { spec in try runSpec(spec) return spec.status == .Fail } Swiftest.reporter.suiteFinished() exit(failures.count == 0 ? 0 : 1) }
mit
503f5b3baaadd139347fbb843e35c123
20.206897
74
0.705691
3.596491
false
true
false
false
aleph7/BrainCore
Source/Layers/LSTMLayer.swift
1
6478
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of BrainCore. The full BrainCore copyright notice, // including terms governing use, modification, and redistribution, is // contained in the file LICENSE at the root of the source code distribution // tree. import Foundation import Metal import Upsurge /// Long short-term memory unit (LSTM) recurrent network cell. public class LSTMLayer: ForwardLayer { struct Parameters { let batchSize: UInt16 let unitCount: UInt16 let inputSize: UInt16 let clipTo: Float } public let id = UUID() public let name: String? public let weights: Matrix<Float> public let biases: ValueArray<Float> public let clipTo: Float public let unitCount: Int public let inputSize: Int public var outputSize: Int { return unitCount } public var stateSize: Int { return 2 * unitCount } var currentState = 0 var forwardInvocation0: Invocation? var forwardInvocation1: Invocation? var reset0Invocation: Invocation? var reset1Invocation: Invocation? var weightsBuffer: Buffer? var biasesBuffer: Buffer? var state0Buffer: Buffer? var state1Buffer: Buffer? public var stateBuffer: Buffer? { if currentState == 0 { return state0Buffer } else { return state1Buffer } } public var forwardInvocations: [Invocation] { guard let forwardInvocation0 = forwardInvocation0, let forwardInvocation1 = forwardInvocation1 else { fatalError("initializeForward needs to be called first") } let invocation = currentState == 0 ? forwardInvocation0 : forwardInvocation1 currentState = (currentState + 1) % 2 return [invocation] } /// Creates an LSTM layer with a weights matrix and a biases array. /// /// - parameter weights: weight matrix with `4*unitCount` columns and `inputSize + unitCount` rows with the weights for input, input activation, forget, and output in that order and with input weights `W` before recurrent weights `U`. /// - parameter biases: the array of biases of size `4*unitCount` with the biases for input, input activation, forget, and output in that order. /// - parameter batchSize: the batch size. /// - parameter name: the layer name. /// - parameter clipTo: optional value to clip activations to. /// /// - seealso: makeWeightsFromComponents public init(weights: Matrix<Float>, biases: ValueArray<Float>, batchSize: Int, name: String? = nil, clipTo: Float? = nil) { self.name = name self.weights = weights self.biases = biases self.clipTo = clipTo ?? 0 self.unitCount = biases.count / 4 self.inputSize = weights.rows - unitCount precondition(weights.columns == 4 * unitCount) } /// Make an LSTM weight matrix from separate W and U component matrices. public static func makeWeightsFromComponents(Wc: Matrix<Float>, Wf: Matrix<Float>, Wi: Matrix<Float>, Wo: Matrix<Float>, Uc: Matrix<Float>, Uf: Matrix<Float>, Ui: Matrix<Float>, Uo: Matrix<Float>) -> Matrix<Float> { let unitCount = Uc.rows let inputSize = Wc.rows let elements = ValueArray<Float>(count: (inputSize + unitCount) * 4 * unitCount) for i in 0..<inputSize { let start = i * 4 * unitCount elements[0 * unitCount + start..<0 * unitCount + start + unitCount] = Wi.row(i) elements[1 * unitCount + start..<1 * unitCount + start + unitCount] = Wc.row(i) elements[2 * unitCount + start..<2 * unitCount + start + unitCount] = Wf.row(i) elements[3 * unitCount + start..<3 * unitCount + start + unitCount] = Wo.row(i) } for i in 0..<unitCount { let start = (inputSize + i) * 4 * unitCount elements[0 * unitCount + start..<0 * unitCount + start + unitCount] = Ui.row(i) elements[1 * unitCount + start..<1 * unitCount + start + unitCount] = Uc.row(i) elements[2 * unitCount + start..<2 * unitCount + start + unitCount] = Uf.row(i) elements[3 * unitCount + start..<3 * unitCount + start + unitCount] = Uo.row(i) } return Matrix<Float>(rows: inputSize + unitCount, columns: 4 * unitCount, elements: elements) } public func initializeForward(builder: ForwardInvocationBuilder, batchSize: Int) throws { let params = Parameters(batchSize: UInt16(batchSize), unitCount: UInt16(unitCount), inputSize: UInt16(inputSize), clipTo: clipTo) weightsBuffer = builder.createBuffer(name: "weights", elements: weights) biasesBuffer = builder.createBuffer(name: "biases", elements: biases) state0Buffer = builder.createBuffer(name: "state0", size: batchSize * stateSize * MemoryLayout<Float>.size) state1Buffer = builder.createBuffer(name: "state1", size: batchSize * stateSize * MemoryLayout<Float>.size) let buffers0 = [ builder.inputBuffer, weightsBuffer!, biasesBuffer!, builder.outputBuffer, state0Buffer!, state1Buffer! ] forwardInvocation0 = try builder.createInvocation( functionName: "lstm_forward_simple", buffers: buffers0, values: [params], width: unitCount, height: batchSize ) let buffers1 = [ builder.inputBuffer, weightsBuffer!, biasesBuffer!, builder.outputBuffer, state1Buffer!, state0Buffer! ] forwardInvocation1 = try builder.createInvocation( functionName: "lstm_forward_simple", buffers: buffers1, values: [params], width: unitCount, height: batchSize) reset0Invocation = try builder.createInvocation( functionName: "reset_buffer", buffers: [state0Buffer!], values: [], width: stateSize * batchSize) reset1Invocation = try builder.createInvocation( functionName: "reset_buffer", buffers: [state1Buffer!], values: [], width: stateSize * batchSize) } /// Reset the internal LSTM state public var resetInvocations: [Invocation] { return [reset0Invocation!, reset1Invocation!] } }
mit
303e5b908a527c9eef01f5afb8c565f7
37.784431
240
0.628069
4.418145
false
false
false
false
yonekawa/SwiftFlux
SwiftFluxTests/Utils/StoreBaseSpec.swift
1
2434
// // StoreBaseSpec.swift // SwiftFlux // // Created by Kenichi Yonekawa on 11/20/15. // Copyright © 2015 mog2dev. All rights reserved. // import Foundation import Quick import Nimble import Result import SwiftFlux class StoreBaseSpec: QuickSpec { struct CalculateActions { struct Plus: Action { typealias Payload = Int let number: Int func invoke(dispatcher: Dispatcher) { dispatcher.dispatch(self, result: Result(value: number)) } } struct Minus: Action { typealias Payload = Int let number: Int func invoke(dispatcher: Dispatcher) { dispatcher.dispatch(self, result: Result(value: number)) } } } class CalculateStore: StoreBase { private(set) var number: Int = 0 override init() { super.init() self.register(CalculateActions.Plus.self) { (result) in switch result { case .Success(let value): self.number += value self.emitChange() default: break } } self.register(CalculateActions.Minus.self) { (result) in switch result { case .Success(let value): self.number -= value self.emitChange() default: break } } } } override func spec() { let store = CalculateStore() var results = [Int]() beforeEach { () in results = [] store.subscribe { () in results.append(store.number) } } afterEach { () in store.unregister() } it("should calculate state with number") { ActionCreator.invoke(CalculateActions.Plus(number: 3)) ActionCreator.invoke(CalculateActions.Plus(number: 3)) ActionCreator.invoke(CalculateActions.Minus(number: 2)) ActionCreator.invoke(CalculateActions.Minus(number: 1)) expect(results.count).to(equal(4)) expect(results[0]).to(equal(3)) expect(results[1]).to(equal(6)) expect(results[2]).to(equal(4)) expect(results[3]).to(equal(3)) } } }
mit
bcbadde9e4e2b247a606f7f12517ae62
26.337079
72
0.505138
4.846614
false
false
false
false
jverdi/Gramophone
Source/Model/Like.swift
1
1972
// // Like.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. All Rights Reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import protocol Decodable.Decodable import Decodable public struct Like { public let ID: String public let username: String public let fullName: String public let profilePictureURL: URL public init(ID: String, username: String, fullName: String, profilePictureURL: URL) { self.ID = ID self.username = username self.fullName = fullName self.profilePictureURL = profilePictureURL } } // MARK: Decodable extension Like: Decodable { public static func decode(_ json: Any) throws -> Like { return try Like( ID: json => "id", username: json => "username", fullName: json => "full_name", profilePictureURL: json => "profile_picture" ) } }
mit
869f255a01e8d6ab4b209bf8beb81b63
34.854545
89
0.69929
4.471655
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/TimelineCells/KeyVerification/KeyVerificationBaseCell.swift
1
8875
/* Copyright 2019 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 @objcMembers class KeyVerificationBaseCell: MXKRoomBubbleTableViewCell { // MARK: - Constants private enum Sizing { static var sizes = Set<SizingViewHeight>() } // MARK: - Properties // MARK: Public weak var keyVerificationCellInnerContentView: KeyVerificationCellInnerContentView? weak var roomCellContentView: RoomCellContentView? override var bubbleInfoContainer: UIView! { get { guard let infoContainer = self.roomCellContentView?.bubbleInfoContainer else { fatalError("[KeyVerificationBaseBubbleCell] bubbleInfoContainer should not be used before set") } return infoContainer } set { super.bubbleInfoContainer = newValue } } override var bubbleOverlayContainer: UIView! { get { guard let overlayContainer = self.roomCellContentView?.bubbleOverlayContainer else { fatalError("[KeyVerificationBaseBubbleCell] bubbleOverlayContainer should not be used before set") } return overlayContainer } set { super.bubbleInfoContainer = newValue } } override var bubbleInfoContainerTopConstraint: NSLayoutConstraint! { get { guard let infoContainerTopConstraint = self.roomCellContentView?.bubbleInfoContainerTopConstraint else { fatalError("[KeyVerificationBaseBubbleCell] bubbleInfoContainerTopConstraint should not be used before set") } return infoContainerTopConstraint } set { super.bubbleInfoContainerTopConstraint = newValue } } // MARK: - Setup override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { self.selectionStyle = .none self.setupContentView() self.update(theme: ThemeService.shared().theme) super.setupViews() } // MARK: - Public func update(theme: Theme) { self.roomCellContentView?.update(theme: theme) self.keyVerificationCellInnerContentView?.update(theme: theme) } func buildUserInfoText(with userId: String, userDisplayName: String?) -> String { let userInfoText: String if let userDisplayName = userDisplayName { userInfoText = "\(userId) (\(userDisplayName))" } else { userInfoText = userId } return userInfoText } func senderId(from bubbleCellData: MXKRoomBubbleCellData) -> String { return bubbleCellData.senderId ?? "" } func senderDisplayName(from bubbleCellData: MXKRoomBubbleCellData) -> String? { let senderId = self.senderId(from: bubbleCellData) guard let senderDisplayName = bubbleCellData.senderDisplayName, senderId != senderDisplayName else { return nil } return senderDisplayName } class func sizingView() -> KeyVerificationBaseCell { fatalError("[KeyVerificationBaseBubbleCell] Subclass should implement this method") } class func sizingViewHeightHashValue(from bubbleCellData: MXKRoomBubbleCellData) -> Int { var hasher = Hasher() let sizingView = self.sizingView() sizingView.render(bubbleCellData) // Add cell class name hasher.combine(self.defaultReuseIdentifier()) if let keyVerificationCellInnerContentView = sizingView.keyVerificationCellInnerContentView { // Add other user info if let otherUserInfo = keyVerificationCellInnerContentView.otherUserInfo { hasher.combine(otherUserInfo) } // Add request status text if keyVerificationCellInnerContentView.isRequestStatusHidden == false, let requestStatusText = sizingView.keyVerificationCellInnerContentView?.requestStatusText { hasher.combine(requestStatusText) } } return hasher.finalize() } // MARK: - Overrides override class func defaultReuseIdentifier() -> String! { return String(describing: self) } override func didEndDisplay() { super.didEndDisplay() self.removeReadReceiptsView() } override class func height(for cellData: MXKCellData!, withMaximumWidth maxWidth: CGFloat) -> CGFloat { guard let cellData = cellData else { return 0 } guard let roomBubbleCellData = cellData as? MXKRoomBubbleCellData else { return 0 } let height: CGFloat let sizingViewHeight = self.findOrCreateSizingViewHeight(from: roomBubbleCellData) if let cachedHeight = sizingViewHeight.heights[maxWidth] { height = cachedHeight } else { height = self.contentViewHeight(for: roomBubbleCellData, fitting: maxWidth) sizingViewHeight.heights[maxWidth] = height } return height } override func render(_ cellData: MXKCellData!) { super.render(cellData) if let bubbleData = self.bubbleData, let roomCellContentView = self.roomCellContentView, let paginationDate = bubbleData.date, roomCellContentView.showPaginationTitle { roomCellContentView.paginationLabel.text = bubbleData.eventFormatter.dateString(from: paginationDate, withTime: false)?.uppercased() } } // MARK: - Private private func setupContentView() { if self.roomCellContentView == nil { let roomCellContentView = RoomCellContentView.instantiate() let innerContentView = KeyVerificationCellInnerContentView.instantiate() roomCellContentView.innerContentView.vc_addSubViewMatchingParent(innerContentView) self.contentView.vc_addSubViewMatchingParent(roomCellContentView) self.roomCellContentView = roomCellContentView self.keyVerificationCellInnerContentView = innerContentView } } private static func findOrCreateSizingViewHeight(from bubbleData: MXKRoomBubbleCellData) -> SizingViewHeight { let sizingViewHeight: SizingViewHeight let bubbleDataHashValue = bubbleData.hashValue if let foundSizingViewHeight = self.Sizing.sizes.first(where: { (sizingViewHeight) -> Bool in return sizingViewHeight.uniqueIdentifier == bubbleDataHashValue }) { sizingViewHeight = foundSizingViewHeight } else { sizingViewHeight = SizingViewHeight(uniqueIdentifier: bubbleDataHashValue) } return sizingViewHeight } private static func contentViewHeight(for cellData: MXKCellData, fitting width: CGFloat) -> CGFloat { let sizingView = self.sizingView() sizingView.render(cellData) sizingView.layoutIfNeeded() let fittingSize = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height) var height = sizingView.systemLayoutSizeFitting(fittingSize).height if let roomBubbleCellData = cellData as? RoomBubbleCellData, let readReceipts = roomBubbleCellData.readReceipts, readReceipts.count > 0 { height+=PlainRoomCellLayoutConstants.readReceiptsViewHeight } return height } } // MARK: - RoomCellReadReceiptsDisplayable extension KeyVerificationBaseCell: RoomCellReadReceiptsDisplayable { func addReadReceiptsView(_ readReceiptsView: UIView) { self.roomCellContentView?.addReadReceiptsView(readReceiptsView) } func removeReadReceiptsView() { self.roomCellContentView?.removeReadReceiptsView() } }
apache-2.0
8658caa9adcf831b3b9a81a61d277067
33.003831
145
0.648
5.689103
false
false
false
false
coinbase/coinbase-ios-sdk
Source/OAuth/OAuthConstants.swift
1
745
// // OAuthConstants.swift // Coinbase iOS // // Copyright © 2018 Coinbase. All rights reserved. // import Foundation /// OAuth related constants. internal struct OAuthConstants { /// Length of default generated `state` parameter. static let defaultStateLength = 8 /// Authorization URL related constants. struct AuthorizationURL { static let scheme = "https" static let host = "www.coinbase.com" static let path = "/oauth/authorize" } } /// Layout related constants. /// /// For logged out users, it is recommended to shown log in page. /// You can show the sign up page instead. /// public struct Layout { /// Show the sign up page. public static let signup = "signup" }
apache-2.0
2880fb7fe408c161f7bf2a26d7766866
20.257143
65
0.657258
4.20339
false
false
false
false
Karumi/MarvelApiClient
MarvelAPIClientPlayground.playground/Contents.swift
1
951
//: MarvelAPIClientPlayground import UIKit import XCPlayground import MarvelAPIClient MarvelAPIClient.configureCredentials( publicKey: "PUT_YOUR_PUBLIC_KEY_HERE", privateKey: "PUT_YOUR_PRIVATE_KEY_HERE") let charactersAPIClient = MarvelAPIClient.charactersAPIClient charactersAPIClient.getAll(offset: 0, limit: 10) { response in print("Get characters by offset and limit:") let characters = response.value?.characters print(characters?[0].name) } let seriesAPIClient = MarvelAPIClient.seriesAPIClient seriesAPIClient.getAll(offset: 0, limit: 1) { response in print("Get series by offset and limit:") let series = response.value?.series print(series?[0].title) } seriesAPIClient.getComics(seriesId: "18454", offset: 0, limit: 1) { response in print("Get comics by series id:") let comics = response.value?.comics print(comics?[0].title) } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
apache-2.0
1266c4a53a1a9f63c6fd96d0447d9e12
27.818182
79
0.752892
4.116883
false
false
false
false
ejeinc/MetalScope
Sources/ViewerParameters.swift
1
2947
// // ViewerParameters.swift // MetalScope // // Created by Jun Tanaka on 2017/01/23. // Copyright © 2017 eje Inc. All rights reserved. // public protocol ViewerParametersProtocol { var lenses: Lenses { get } var distortion: Distortion { get } var maximumFieldOfView: FieldOfView { get } } public struct ViewerParameters: ViewerParametersProtocol { public var lenses: Lenses public var distortion: Distortion public var maximumFieldOfView: FieldOfView public init(lenses: Lenses, distortion: Distortion, maximumFieldOfView: FieldOfView) { self.lenses = lenses self.distortion = distortion self.maximumFieldOfView = maximumFieldOfView } public init(_ parameters: ViewerParametersProtocol) { self.lenses = parameters.lenses self.distortion = parameters.distortion self.maximumFieldOfView = parameters.maximumFieldOfView } } public struct Lenses { public enum Alignment: Int { case top = -1 case center = 0 case bottom = 1 } public let separation: Float public let offset: Float public let alignment: Alignment public let screenDistance: Float public init(separation: Float, offset: Float, alignment: Alignment, screenDistance: Float) { self.separation = separation self.offset = offset self.alignment = alignment self.screenDistance = screenDistance } } public struct FieldOfView { public let outer: Float // in degrees public let inner: Float // in degrees public let upper: Float // in degrees public let lower: Float // in degrees public init(outer: Float, inner: Float, upper: Float, lower: Float) { self.outer = outer self.inner = inner self.upper = upper self.lower = lower } public init(values: [Float]) { guard values.count == 4 else { fatalError("The values must contain 4 elements") } outer = values[0] inner = values[1] upper = values[2] lower = values[3] } } public struct Distortion { public var k1: Float public var k2: Float public init(k1: Float, k2: Float) { self.k1 = k1 self.k2 = k2 } public init(values: [Float]) { guard values.count == 2 else { fatalError("The values must contain 2 elements") } k1 = values[0] k2 = values[1] } public func distort(_ r: Float) -> Float { let r2 = r * r return ((k2 * r2 + k1) * r2 + 1) * r } public func distortInv(_ r: Float) -> Float { var r0: Float = 0 var r1: Float = 1 var dr0 = r - distort(r0) while abs(r1 - r0) > Float(0.0001) { let dr1 = r - distort(r1) let r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0)) r0 = r1 r1 = r2 dr0 = dr1 } return r1 } }
mit
77ce2acf829c9032cafa66bb8c14aa4d
25.303571
96
0.596062
3.933244
false
false
false
false
chenchangqing/learniosanimation
example01/example01/ViewController.swift
1
11829
// // ViewController.swift // example01 // // Created by green on 15/8/12. // Copyright (c) 2015年 com.chenchangqing. All rights reserved. // import UIKit class ViewController: UIViewController { // 视图01 var view01 : UIView! let view01OriginalRect = CGRectMake(16, 32, 100, 100) let view01OriginalColor = UIColor.redColor() var view01OriginalCenter: CGPoint! // 视图01的子视图 var view01Subview : UIView! let view01SubviewRect = CGRectMake(16, 16, 32, 32) let view01SubviewOriginalColor = UIColor.purpleColor() var view01SubviewOriginalCenter : CGPoint! // 视图02 var view02 : UIView! let view02OriginalRect = CGRectMake(16, CGRectGetHeight(UIScreen.mainScreen().bounds) - 148, 100, 100) let view02OriginalColor = UIColor.magentaColor() var view02OriginalCenter: CGPoint! // 视图03,04 var view03 : UIView! var view04 : UIView! // 子layer var layer : CALayer! // MARK: - override func viewDidLoad() { super.viewDidLoad() // 设置view01 view01 = UIView(frame: view01OriginalRect) view01.backgroundColor = view01OriginalColor view01OriginalCenter = view01.center view.addSubview(view01) // 设置view01的子视图 view01Subview = UIView(frame: view01SubviewRect) view01Subview.backgroundColor = view01SubviewOriginalColor view01SubviewOriginalCenter = view01Subview.center view01.addSubview(view01Subview) // 设置view02 view02 = UIView(frame: view02OriginalRect) view02.backgroundColor = view02OriginalColor view02OriginalCenter = view02.center view.addSubview(view02) // 设置view03,04 view03 = UIView(frame: CGRectMake(16, CGRectGetMaxY(view01.frame) + 16, 100, 100)) view03.backgroundColor = UIColor.greenColor() view04 = UIView(frame: CGRectMake(16, CGRectGetMaxY(view03.frame) + 16, 100, 100)) view04.backgroundColor = UIColor.grayColor() view.addSubview(view03) // 设置layer addSublayer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - 结束动画 /** * 结束动画 */ @IBAction func endAnimation() { // 恢复view01 view01.layer.removeAllAnimations() view01.center = view01OriginalCenter view01.backgroundColor = view01OriginalColor view01.transform = CGAffineTransformMakeScale(1, 1) view01.alpha = 1 // 恢复view02 view02.layer.removeAllAnimations() view02.center = view02OriginalCenter view02.backgroundColor = view02OriginalColor view02.transform = CGAffineTransformMakeScale(1, 1) view02.alpha = 1 // 恢复view01Subview view01Subview.layer.removeAllAnimations() self.view01Subview.center = view01SubviewOriginalCenter self.view01Subview.backgroundColor = view01SubviewOriginalColor self.view01Subview.alpha = 1 // 恢复view03 for view in self.view.subviews { if view as! NSObject == view04 { view04.removeFromSuperview() self.view.addSubview(view03) } } // 恢复layer layer.removeAllAnimations() layer.frame = CGRectMake(CGRectGetMaxX(view03.frame) + 16, CGRectGetMaxY(view01.frame) + 16, 100, 100) } // MARK: - 操作视图 private func view01Operation() { self.view01.center = self.view.center self.view01.backgroundColor = UIColor.magentaColor() self.view01.transform = CGAffineTransformMakeScale(2, 2) self.view01.alpha = 0.5 } private func view02Operation() { self.view02.center = self.view.center self.view02.backgroundColor = UIColor.redColor() self.view02.transform = CGAffineTransformMakeScale(2, 2) self.view02.alpha = 0.5 } private func view01SubviewOperation() { self.view01Subview.center = CGPointMake(CGRectGetMidX(view01.frame) - CGRectGetMinX(view01.frame), CGRectGetMidY(view01.frame) - CGRectGetMinY(view01.frame)) self.view01Subview.backgroundColor = UIColor.greenColor() self.view01Subview.alpha = 0.5 } /** * 增加一个layer */ private func addSublayer() { layer = CALayer() layer.backgroundColor = UIColor.magentaColor().CGColor layer.borderColor = UIColor.grayColor().CGColor layer.borderWidth = 5 layer.cornerRadius = 10 layer.shadowColor = UIColor.blackColor().CGColor layer.shadowOpacity = 0.5 layer.shadowOffset = CGSizeMake(10, 10) layer.frame = CGRectMake(CGRectGetMaxX(view03.frame) + 16, CGRectGetMaxY(view01.frame) + 16, 100, 100) view.layer.addSublayer(layer) } // MARK: - 开始动画 /** * 执行动画方式01 * 基本动画 */ @IBAction func typeOne() { UIView.animateWithDuration(2, animations: { () -> Void in self.view01Operation() }) } /** * 执行动画方式02 * 使用UIViewAnimationOptions执行动画 */ @IBAction func typeTwo() { UIView.animateWithDuration(2, delay: 0, options: [UIViewAnimationOptions.CurveLinear , UIViewAnimationOptions.Repeat , UIViewAnimationOptions.Autoreverse], animations: { () -> Void in self.view01Operation() }) { (finished) -> Void in print("view01Operation是否完成:\(finished)") } } /** * 执行动画方式03 * 使用Begin/Commit执行动画 */ @IBAction func typeThree() { // 开始动画并设置动画属性 UIView.beginAnimations("begincommitAnimation", context: nil) UIView.setAnimationDuration(2) UIView.setAnimationRepeatAutoreverses(true) UIView.setAnimationRepeatCount(MAXFLOAT) UIView.setAnimationDelegate(self) UIView.setAnimationWillStartSelector(Selector("animationDidStart:")) UIView.setAnimationDidStopSelector(Selector("animationDidStop:finished:")) // 操作视图 self.view01Operation() // 提交动画 UIView.commitAnimations() } /** * 执行动画方式04 * Nest嵌套动画执行 */ @IBAction func typeFour() { UIView.animateWithDuration(2, delay: 0, options: [UIViewAnimationOptions.CurveLinear , UIViewAnimationOptions.Repeat , UIViewAnimationOptions.Autoreverse], animations: { () -> Void in self.view01Operation() UIView.animateWithDuration(6, delay: 0, options: [UIViewAnimationOptions.CurveLinear , UIViewAnimationOptions.Repeat , UIViewAnimationOptions.Autoreverse , UIViewAnimationOptions.OverrideInheritedDuration], animations: { () -> Void in self.view02Operation() }) { (finished) -> Void in print("view02Operation是否完成:\(finished)") } }) { (finished) -> Void in print("view01Operation是否完成:\(finished)") } } /** * 执行动画方式05 * 操作子视图执行转场动画 */ @IBAction func typeFive() { UIView.transitionWithView(self.view01Subview, duration: 2, options: [UIViewAnimationOptions.TransitionCrossDissolve , UIViewAnimationOptions.AllowAnimatedContent], animations: { () -> Void in self.view01SubviewOperation() }) { (finished) -> Void in print("view01SubviewOperation是否完成:\(finished)") } } /** * 执行动画方式06 * 替换子视图 */ @IBAction func typeSix() { UIView.transitionFromView(view03, toView: view04, duration: 1, options: UIViewAnimationOptions.TransitionCrossDissolve) { (finished) -> Void in print("view04 replace view03 是否完成:\(finished)") } } /** * 执行动画方式07 * 隐式动画 */ @IBAction func typeSeven() { layer.position.y += 116 } /** * 执行动画方式08 * 放大缩小显示动画 */ @IBAction func typeEight() { // 放大缩小动画类 let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.fromValue = 1 scaleAnimation.toValue = 1.5 scaleAnimation.autoreverses = true scaleAnimation.repeatCount = MAXFLOAT scaleAnimation.duration = 2 // 透明度动画类 let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.fromValue = 0.0 opacityAnimation.toValue = 1.0 opacityAnimation.autoreverses = true opacityAnimation.repeatCount = MAXFLOAT opacityAnimation.duration = 2 // 增加动画 layer.addAnimation(scaleAnimation, forKey: "scaleAnimation") layer.addAnimation(opacityAnimation, forKey: "opacityAnimation") } /** * 执行动画方式09 * 关键帧动画 */ @IBAction func typeNine() { let layer = view01.layer // 关键帧动画类 let keyFrameAnimation = CAKeyframeAnimation(keyPath: "position") // 关键轨迹 let value01 = NSValue(CGPoint: layer.position) let value02 = NSValue(CGPoint: CGPointMake(CGRectGetMaxX(layer.frame) + 100, layer.position.y)) let value03 = NSValue(CGPoint: CGPointMake(CGRectGetMaxX(layer.frame) + 100, CGRectGetMaxY(layer.frame) + 100)) let value04 = NSValue(CGPoint: CGPointMake(layer.position.x, CGRectGetMaxY(layer.frame) + 100)) let value05 = value01 // 时间曲线 let tf01 = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) let tf02 = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let tf03 = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) let tf04 = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) // 轨迹时间 keyFrameAnimation.keyTimes = [0.0,0.5,0.6,0.7,1] keyFrameAnimation.timingFunctions = [tf01,tf02,tf03,tf04] keyFrameAnimation.values = [value01,value02,value03,value04,value05] keyFrameAnimation.duration = 3 keyFrameAnimation.autoreverses = false keyFrameAnimation.repeatCount = MAXFLOAT layer.addAnimation(keyFrameAnimation, forKey: "keyFrameAnimation") } // MARK: - begin/commit animation delegate override func animationDidStart(anim: CAAnimation) { print("animationDidStart") } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { print("animationDidStop") } }
apache-2.0
2523d81b1b66b31e104a70bedceda6a0
31.207386
246
0.584458
4.882429
false
false
false
false
silt-lang/silt
Sources/InnerCore/IRGenFunction.swift
1
13605
/// IRGenFunction.swift /// /// Copyright 2019, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import LLVM import Seismography import OuterCore import PrettyStackTrace enum LoweredValue { case address(Address) case stackAddress(StackAddress) case explosion([IRValue]) case functionPointer(Function) case box(OwnedAddress) /// Produce an explosion for this lowered value. Note that many /// different storage kinds can be turned into an explosion. func explode(_ IGF: IRGenFunction, _ type: GIRType) -> Explosion { let e = Explosion() switch self { case .address(_): fatalError("not a value") case .stackAddress(_): fatalError("not a value") case let .explosion(explosion): e.append(contentsOf: explosion) case let .box(ownedAddr): e.append(ownedAddr.owner) case let .functionPointer(fptr): // Bitcast to an opaque pointer type. let fnPtr = IGF.B.buildBitCast(fptr, type: PointerType.toVoid) e.append(fnPtr) } return e } func asAnyAddress() -> Address { switch self { case let .address(addr): return addr case let .stackAddress(stackAddr): return stackAddr.address case let .box(ownedAddr): return ownedAddr.address default: fatalError("not an address") } } } /// A continuation lowered as the pair of a basic block and a vector of PHI /// nodes - one for each parameter. struct LoweredBB { let bb: BasicBlock let phis: [PhiNode] init(_ bb: BasicBlock, _ phis: [PhiNode]) { self.bb = bb self.phis = phis } } class IRGenFunction { unowned let IGM: IRGenModule let function: Function let functionType: LLVM.FunctionType lazy var GR: IRGenRuntime = IRGenRuntime(irGenFunction: self) let B: IRBuilder init(_ IGM: IRGenModule, _ function: Function, _ fty: LLVM.FunctionType) { self.IGM = IGM self.function = function self.functionType = fty self.B = IRBuilder(module: IGM.module) self.GR = IRGenRuntime(irGenFunction: self) let entryBB = self.function.appendBasicBlock(named: "entry") self.B.positionAtEnd(of: entryBB) } func getTypeInfo(_ ty: GIRType) -> TypeInfo { return self.IGM.getTypeInfo(ty) } } final class IRGenGIRFunction: IRGenFunction { let scope: OuterCore.Scope let schedule: Schedule var blockMap = [Continuation: LoweredBB]() var loweredValues = [Value: LoweredValue]() var indirectReturn: Address? lazy var trapBlock: BasicBlock = { let insertBlock = B.insertBlock! let block = function.appendBasicBlock(named: "trap") B.positionAtEnd(of: block) B.buildUnreachable() B.positionAtEnd(of: insertBlock) return block }() init(irGenModule: IRGenModule, scope: OuterCore.Scope) { self.schedule = Schedule(scope, .early) self.scope = scope let (f, fty) = irGenModule.function(for: scope.entry) super.init(irGenModule, f, fty) } private func emitEntryReturnPoint( _ entry: Continuation, _ params: Explosion, _ funcTy: Seismography.FunctionType, _ requiresIndirectResult: (GIRType) -> Bool ) -> [Seismography.Parameter] { let directResultType = funcTy.returnType if requiresIndirectResult(directResultType) { let retTI = self.IGM.getTypeInfo(directResultType) self.indirectReturn = retTI.address(for: params.claimSingle()) } // Fast-path: We're not going out by indirect return. guard let indirectRet = entry.indirectReturnParameter else { return entry.parameters } let retTI = self.IGM.getTypeInfo(indirectRet.type) let retAddr = retTI.address(for: params.claimSingle()) self.loweredValues[indirectRet] = .address(retAddr) return entry.parameters } func bindParameter(_ param: Seismography.Parameter, _ allParamValues: Explosion) { // Pull out the parameter value and its formal type. let paramTI = self.getTypeInfo(param.type) switch param.type.category { case .address: let paramAddr = paramTI.address(for: allParamValues.claimSingle()) self.loweredValues[param] = .address(paramAddr) case .object: let paramValues = Explosion() // If the explosion must be passed indirectly, load the value from the // indirect address. guard let loadableTI = paramTI as? LoadableTypeInfo else { fatalError() } let nativeSchema = self.IGM.typeConverter .parameterConvention(for: param.type) if nativeSchema.isIndirect { let paramAddr = loadableTI.address(for: allParamValues.claimSingle()) loadableTI.loadAsTake(self, paramAddr, paramValues) } else { if !nativeSchema.isEmpty { allParamValues.transfer(into: paramValues, nativeSchema.count) } else { assert(paramTI.schema.isEmpty) } } self.loweredValues[param] = .explosion([IRValue](paramValues.claim())) } } func emitBody() { trace("emitting LLVM IR declaration for function '\(scope.entry.name)'") { guard let entryBlock = schedule.blocks.first else { fatalError("Scheduled blocks without an entry?") } for block in schedule.blocks { let name = IGM.mangler.mangle(block.parent) let basicBlock = function.appendBasicBlock(named: name) let phis = self.emitPHINodesForBBArgs(block.parent, basicBlock) self.blockMap[block.parent] = LoweredBB(basicBlock, phis) } let expl = getPrologueExplosion() let entry = self.scope.entry // swiftlint:disable force_cast let funcTy = entry.type as! Seismography.FunctionType // Map the indirect return if present. let params = self.emitEntryReturnPoint(entry, expl, funcTy) { retType in let schema = self.IGM.typeConverter.returnConvention(for: retType) return schema.isIndirect } // Map remaining parameters to LLVM parameters. for param in params.dropLast() { self.bindParameter(param, expl) } self.B.positionAtEnd(of: self.function.entryBlock!) let entryLBB = blockMap[entryBlock.parent]! let properEntry = self.function.entryBlock! self.B.buildBr(entryLBB.bb) assert(expl.isEmpty || params.count == 1, "didn't claim all parameters!") for block in schedule.blocks { let bb = self.blockMap[block.parent]! B.positionAtEnd(of: bb.bb) for primop in block.primops { _ = emit(primop) } } for (phi, param) in zip(entryLBB.phis, self.function.parameters) { param.replaceAllUses(with: phi) phi.addIncoming([ (param, properEntry) ]) } } } /// Initialize an Explosion with the parameters of the current /// function. All of the objects will be added unmanaged. This is /// really only useful when writing prologue code. func getPrologueExplosion() -> Explosion { let params = Explosion() for param in self.function.parameters { params.append(param) } return params } private func emitPHINodesForType( _ type: GIRType, _ ti: TypeInfo, _ phis: inout [PhiNode] ) { switch type.category { case .address: phis.append(self.B.buildPhi(PointerType(pointee: ti.llvmType))) case .object: for elt in ti.schema.elements { if elt.isScalar { phis.append(self.B.buildPhi(elt.scalarType)) } else { phis.append(self.B.buildPhi(elt.getAggregateType)) } } } } private func emitPHINodesForBBArgs( _ continuation: Continuation, _ bb: BasicBlock ) -> [PhiNode] { var phis = [PhiNode]() self.B.positionAtEnd(of: bb) for param in continuation.formalParameters { let first = phis.count let ti = self.getTypeInfo(param.type) self.emitPHINodesForType(param.type, ti, &phis) switch param.type.category { case .address: self.loweredValues[param] = .address(ti.address(for: phis.last!)) case .object: let argValue = Explosion() for phi in phis[first..<phis.endIndex] { argValue.append(phi) } self.loweredValues[param] = .explosion([IRValue](argValue.claim())) } } return phis } func emit(_ continuation: Continuation) { } func emit(_ primOp: PrimOp) { _ = visitPrimOp(primOp) } func getLoweredExplosion(_ key: Value) -> Explosion { return self.loweredValues[key]!.explode(self, key.type) } func datatypeStrategy(for ty: GIRType) -> DataTypeStrategy { let ti = self.getTypeInfo(ty) switch ti { case let ti as LoadableDataTypeTypeInfo: return ti.strategy case let ti as FixedDataTypeTypeInfo: return ti.strategy case let ti as DynamicDataTypeTypeInfo: return ti.strategy default: fatalError() } } } extension IRGenFunction { func coerceValue(_ value: IRValue, to toTy: IRType) -> IRValue { let fromTy = value.type // Use the pointer/pointer and pointer/int casts if we can. if let toAsPtr = toTy as? PointerType { if fromTy is PointerType { return self.B.buildBitCast(value, type: toTy) } let intPtr = self.B.module.dataLayout.intPointerType() if fromTy.asLLVM() == intPtr.asLLVM() { return self.B.buildIntToPtr(value, type: toAsPtr) } } else if fromTy is PointerType { let intPtr = self.B.module.dataLayout.intPointerType() if toTy.asLLVM() == intPtr.asLLVM() { return self.B.buildPtrToInt(value, type: intPtr) } } // Otherwise we need to store, bitcast, and load. let DL = self.IGM.module.dataLayout let fromSize = DL.sizeOfTypeInBits(fromTy) let toSize = DL.sizeOfTypeInBits(toTy) let bufferTy = fromSize >= toSize ? fromTy : toTy let alignment: Alignment = max(DL.abiAlignment(of: fromTy), DL.abiAlignment(of: toTy)) let address = self.B.createAlloca(bufferTy, alignment: alignment) let size = Size(UInt64(max(fromSize, toSize))) _ = self.B.createLifetimeStart(address, size) let orig = self.B.createPointerBitCast(of: address, to: PointerType(pointee: fromTy)) self.B.buildStore(value, to: orig.address) let coerced = self.B.createPointerBitCast(of: address, to: PointerType(pointee: toTy)) let loaded = self.B.createLoad(coerced) _ = self.B.createLifetimeEnd(address, size) return loaded } } extension IRGenFunction { /// Cast the base to i8*, apply the given inbounds offset (in bytes, /// as a size_t), and create an address in the given type. func emitByteOffsetGEP( _ base: IRValue, _ offset: IRValue, _ type: TypeInfo, _ name: String ) -> Address { let castBase = self.B.buildBitCast(base, type: PointerType.toVoid) let gep = self.B.buildInBoundsGEP(castBase, type: PointerType.toVoid, indices: [ offset ]) let addr = self.B.buildBitCast(gep, type: PointerType(pointee: type.llvmType), name: name) return type.address(for: addr) } } extension IRGenFunction { func emitAllocEmptyBoxCall() -> IRValue { var call = self.B.buildCall(self.IGM.getAllocEmptyBoxFn(), args: []) call.callingConvention = CallingConvention.c return call } func emitAllocBoxCall(_ metadata: IRValue) -> (IRValue, Address) { var call = self.B.buildCall(self.IGM.getAllocBoxFn(), args: [metadata]) call.callingConvention = CallingConvention.c let box = self.B.buildExtractValue(call, index: 0) let addr = Address(self.B.buildExtractValue(call, index: 1), self.IGM.getPointerAlignment(), self.IGM.refCountedPtrTy) return (box, addr) } func emitDeallocBoxCall(_ box: IRValue, _ metadata: IRValue) { var call = self.B.buildCall(self.IGM.getDeallocBoxFn(), args: [box]) call.callingConvention = CallingConvention.c } func emitProjectBoxCall(_ box: IRValue, _ metadata: IRValue) -> IRValue { var call = self.B.buildCall(self.IGM.getProjectBoxFn(), args: [box]) call.callingConvention = CallingConvention.c return call } } extension IRGenModule { func getAllocEmptyBoxFn() -> Function { guard let fn = self.module.function(named: "silt_allocEmptyBox") else { let fnTy = FunctionType([], self.refCountedPtrTy) return self.B.addFunction("silt_allocEmptyBox", type: fnTy) } return fn } func getAllocBoxFn() -> Function { guard let fn = self.module.function(named: "silt_allocBox") else { let retTy = StructType(elementTypes: [ self.refCountedPtrTy, // Addr self.opaquePtrTy, // Metadata ]) let fnTy = FunctionType([ self.typeMetadataPtrTy ], retTy) return self.B.addFunction("silt_allocBox", type: fnTy) } return fn } func getDeallocBoxFn() -> Function { guard let fn = self.module.function(named: "silt_deallocBox") else { let fnTy = FunctionType([ self.refCountedPtrTy ], VoidType()) return self.B.addFunction("silt_deallocBox", type: fnTy) } return fn } func getProjectBoxFn() -> Function { guard let fn = self.module.function(named: "silt_deallocBox") else { let fnTy = FunctionType([ self.refCountedPtrTy ], self.refCountedPtrTy) return self.B.addFunction("silt_deallocBox", type: fnTy) } return fn } }
mit
05caa9dccdd67e6a9404a3c05ef2dfea
31.087264
78
0.653951
3.819483
false
false
false
false
NobodyNada/SwiftChatSE
Sources/SwiftChatSE/Utilites.swift
1
3498
// // Utilites.swift // FireAlarm // // Created by Jonathan Keller on 11/28/16. // Copyright © 2016 NobodyNada. All rights reserved. // import Foundation import Dispatch public var userLocation = "<unknown>" public enum FileLoadingError: Error { case notUFT8 } public func loadFile(_ path: String) throws -> String { let data = try Data(contentsOf: URL(fileURLWithPath: path)) guard let str = String(data: data, encoding: .utf8) else { throw FileLoadingError.notUFT8 } return str } public func formatArray<T>(_ array: [T], conjunction: String, separator: String = ",") -> String { var string = "" if array.count == 1 { string = "\(array.first!)" } else { for (index, item) in array.enumerated() { if index == array.count - 1 { string.append("\(conjunction) \(item)") } else { string.append("\(item)\(array.count == 2 ? "" : ",") ") } } } return string } public func pluralize(_ n: Int, _ singular: String, _ plural: String? = nil) -> String { let resultPlural: String if let p = plural { resultPlural = p } else { resultPlural = singular + "s" } if n == 1 { return singular } else { return resultPlural } } #if os(macOS) public func clearCookies(_ storage: HTTPCookieStorage) { if let cookies = storage.cookies { for cookie in cookies { storage.deleteCookie(cookie) } } } #endif public func makeTable(_ heading: [String], contents: [String]...) -> String { if heading.count != contents.count { fatalError("heading and contents have different counts") } let cols = heading.count var alignedHeading = [String]() var alignedContents = [[String]]() var maxLength = [Int]() var rows = 0 var tableWidth = 0 for col in 0..<cols { maxLength.append(heading[col].count) for row in contents[col] { maxLength[col] = max(row.count, maxLength[col]) } rows = max(contents[col].count, rows) alignedHeading.append(heading[col].padding(toLength: maxLength[col], withPad: " ", startingAt: 0)) alignedContents.append(contents[col].map { $0.padding(toLength: maxLength[col], withPad: " ", startingAt: 0) } ) tableWidth += maxLength[col] } tableWidth += (cols - 1) * 3 let head = alignedHeading.joined(separator: " | ") let divider = String([Character](repeating: "-", count: tableWidth)) var table = [String]() for row in 0..<rows { var columns = [String]() for col in 0..<cols { columns.append( alignedContents[col].count > row ? alignedContents[col][row] : String([Character](repeating: " ", count: maxLength[col]))) } table.append(columns.joined(separator: " | ")) } return " " + [head,divider,table.joined(separator: "\n ")].joined(separator: "\n ") } public func postIDFromURL(_ url: URL, isUser: Bool = false) -> Int? {let componentIndex: Int let component: String if url.pathComponents.first == "/" { if url.pathComponents.count < 3 { return nil } componentIndex = 1 } else { if url.pathComponents.count < 2 { return nil } componentIndex = 0 } component = url.pathComponents[componentIndex] if (isUser && (component == "u" || component == "users")) || (!isUser && (component == "q" || component == "questions" || component == "a" || component == "answers" || component == "p" || component == "posts")) { return Int(url.pathComponents[componentIndex + 1]) } return nil } public var saveURL: URL! public func saveFileNamed(_ name: String) -> URL { return saveURL.appendingPathComponent(name) }
mit
09584e4bd909800bc567743d51e427a1
22.628378
100
0.64827
3.256052
false
false
false
false
wei18810109052/CWWeChat
CWWeChat/MainClass/Base/CWTableViewManager/CWTableViewManager.swift
2
6131
// // CWTableViewManager.swift // CWWeChat // // Created by wei chen on 2017/2/11. // Copyright © 2017年 chenwei. All rights reserved. // import UIKit public protocol CWTableViewManagerDelegate: UITableViewDelegate { } public protocol CWTableViewManagerDataSource: NSObjectProtocol { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell? } extension CWTableViewManagerDelegate { } extension CWTableViewManagerDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell? { return nil } } /// table 管理的 // 主要用来 创建统一的设置界面 // 参考 https://github.com/romaonthego/RETableViewManager 根据自己的项目进行简化 public class CWTableViewManager: NSObject { public weak var tableView: UITableView? public weak var delegate: CWTableViewManagerDelegate? public weak var dataSource: CWTableViewManagerDataSource? public var style: CWTableViewStyle? public private(set) var sections: [CWTableViewSection] /// 初始化方法 /// /// - Parameter tableView: tableView实例 init(tableView: UITableView) { self.sections = [CWTableViewSection]() self.tableView = tableView super.init() self.tableView?.dataSource = self self.tableView?.delegate = self registerCellClass() } func registerCellClass() { tableView?.register(CWTableHeaderTitleView.self, forHeaderFooterViewReuseIdentifier: CWTableHeaderTitleView.identifier) tableView?.register(CWTableFooterTitleView.self, forHeaderFooterViewReuseIdentifier: CWTableFooterTitleView.identifier) self.register(cellClass: CWTableViewCell.self, forCellReuseIdentifier: CWTableViewItem.self) self.register(cellClass: CWTableViewBoolCell.self, forCellReuseIdentifier: CWBoolItem.self) self.register(cellClass: CWTableViewButtonCell.self, forCellReuseIdentifier: CWButtonItem.self) } func register(cellClass: Swift.AnyClass, forCellReuseIdentifier itemClass: Swift.AnyClass) { self.tableView?.register(cellClass, forCellReuseIdentifier: String(describing: itemClass)) } func identifierForCell(at indexPath: IndexPath) -> String { let item = sections[indexPath.section][indexPath.row] return String(describing: item.classForCoder) } // MARK: 操作item public func addSection(itemsOf items: [CWTableViewItem]) { let section = CWTableViewSection(items: items) self.addSection(section) } // MARK: 操作section public func addSection(contentsOf sections: [CWTableViewSection]) { for section in sections { self.addSection(section) } } public func addSection(_ section: CWTableViewSection) { section.tableViewManager = self sections.append(section) } } // MARK: UITableViewDataSource extension CWTableViewManager: UITableViewDataSource { public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = self.dataSource?.tableView(tableView, cellForRowAt: indexPath) { return cell } let identifier = identifierForCell(at: indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! CWTableViewCell cell.item = sections[indexPath.section][indexPath.row] cell.cellWillAppear() return cell; } public func numberOfSections(in tableView: UITableView) -> Int { return sections.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].items.count } } // MARK: UITableViewDelegate extension CWTableViewManager: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //默认取消选中 tableView.deselectRow(at: indexPath, animated: true) let item = sections[indexPath.section][indexPath.row] if let selectionAction = item.selectionAction { selectionAction(item) } // 不明白 为什么需要添加? delegate?.tableView?(tableView, didSelectRowAt: indexPath) } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let cellHeight = delegate?.tableView?(tableView, heightForRowAt: indexPath) { return cellHeight } let item = sections[indexPath.section][indexPath.row] return item.cellHeight } // MARK: header and footreView public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return sections[section].footerHeight } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sections[section].headerHeight } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let headerTitle = sections[section].headerTitle else { return nil } let headerTitleView = tableView.dequeueReusableHeaderFooterView(withIdentifier: CWTableHeaderTitleView.identifier) as! CWTableHeaderTitleView headerTitleView.text = headerTitle return headerTitleView } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let footerTitle = sections[section].footerTitle else { return nil } let footerTitleView = tableView.dequeueReusableHeaderFooterView(withIdentifier: CWTableFooterTitleView.identifier) as! CWTableFooterTitleView footerTitleView.text = footerTitle return footerTitleView } }
mit
24d477956b939815942a54348ce85ca1
31.684783
149
0.682574
5.360071
false
false
false
false
UIKit0/SwiftSpinner
SwiftSpinner/SwiftSpinner.swift
6
14256
// // Copyright (c) 2015 Marin Todorov, Underplot ltd. // This code is distributed under the terms and conditions of the MIT license. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit public class SwiftSpinner: UIView { // MARK: - Singleton // // Access the singleton instance // public class var sharedInstance: SwiftSpinner { struct Singleton { static let instance = SwiftSpinner(frame: CGRect.zeroRect) } return Singleton.instance } // MARK: - Init // // Custom init to build the spinner UI // public override init(frame: CGRect) { super.init(frame: frame) blurEffect = UIBlurEffect(style: blurEffectStyle) blurView = UIVisualEffectView(effect: blurEffect) addSubview(blurView) vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect)) addSubview(vibrancyView) let titleScale: CGFloat = 0.85 titleLabel.frame.size = CGSize(width: frameSize.width * titleScale, height: frameSize.height * titleScale) titleLabel.font = defaultTitleFont titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Center titleLabel.lineBreakMode = .ByWordWrapping titleLabel.adjustsFontSizeToFitWidth = true vibrancyView.contentView.addSubview(titleLabel) blurView.contentView.addSubview(vibrancyView) outerCircleView.frame.size = frameSize outerCircle.path = UIBezierPath(ovalInRect: CGRect(x: 0.0, y: 0.0, width: frameSize.width, height: frameSize.height)).CGPath outerCircle.lineWidth = 8.0 outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 0.45 outerCircle.lineCap = kCALineCapRound outerCircle.fillColor = UIColor.clearColor().CGColor outerCircle.strokeColor = UIColor.whiteColor().CGColor outerCircleView.layer.addSublayer(outerCircle) outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 1.0 vibrancyView.contentView.addSubview(outerCircleView) innerCircleView.frame.size = frameSize let innerCirclePadding: CGFloat = 12 innerCircle.path = UIBezierPath(ovalInRect: CGRect(x: innerCirclePadding, y: innerCirclePadding, width: frameSize.width - 2*innerCirclePadding, height: frameSize.height - 2*innerCirclePadding)).CGPath innerCircle.lineWidth = 4.0 innerCircle.strokeStart = 0.5 innerCircle.strokeEnd = 0.9 innerCircle.lineCap = kCALineCapRound innerCircle.fillColor = UIColor.clearColor().CGColor innerCircle.strokeColor = UIColor.grayColor().CGColor innerCircleView.layer.addSublayer(innerCircle) innerCircle.strokeStart = 0.0 innerCircle.strokeEnd = 1.0 vibrancyView.contentView.addSubview(innerCircleView) } // MARK: - Public interface public lazy var titleLabel = UILabel() public var subtitleLabel: UILabel? // // Show the spinner activity on screen, if visible only update the title // public class func show(title: String, animated: Bool = true) -> SwiftSpinner { let window = UIApplication.sharedApplication().windows.first as! UIWindow let spinner = SwiftSpinner.sharedInstance spinner.showWithDelayBlock = nil spinner.clearTapHandler() spinner.updateFrame() if spinner.superview == nil { //show the spinner spinner.alpha = 0.0 window.addSubview(spinner) UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: { spinner.alpha = 1.0 }, completion: nil) // Orientation change observer NSNotificationCenter.defaultCenter().addObserver( spinner, selector: "updateFrame", name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil) } spinner.title = title spinner.animating = animated return spinner } // // Show the spinner activity on screen, after delay. If new call to show, // showWithDelay or hide is maked before execution this call is discarded // public class func showWithDelay(delay: Double, title: String, animated: Bool = true) -> SwiftSpinner { let spinner = SwiftSpinner.sharedInstance spinner.showWithDelayBlock = { SwiftSpinner.show(title, animated: animated) } spinner.delay(seconds: delay) { [weak spinner] in if let spinner = spinner { spinner.showWithDelayBlock?() } } return spinner } // // Hide the spinner // public class func hide(completion: (() -> Void)? = nil) { let spinner = SwiftSpinner.sharedInstance NSNotificationCenter.defaultCenter().removeObserver(spinner) dispatch_async(dispatch_get_main_queue(), { spinner.showWithDelayBlock = nil spinner.clearTapHandler() if spinner.superview == nil { return } UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: { spinner.alpha = 0.0 }, completion: {_ in spinner.alpha = 1.0 spinner.removeFromSuperview() spinner.titleLabel.font = spinner.defaultTitleFont spinner.titleLabel.text = nil completion?() }) spinner.animating = false }) } // // Set the default title font // public class func setTitleFont(font: UIFont?) { let spinner = SwiftSpinner.sharedInstance if let font = font { spinner.titleLabel.font = font } else { spinner.titleLabel.font = spinner.defaultTitleFont } } // // The spinner title // public var title: String = "" { didSet { let spinner = SwiftSpinner.sharedInstance UIView.animateWithDuration(0.15, delay: 0.0, options: .CurveEaseOut, animations: { spinner.titleLabel.transform = CGAffineTransformMakeScale(0.75, 0.75) spinner.titleLabel.alpha = 0.2 }, completion: {_ in spinner.titleLabel.text = self.title UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 0.0, options: nil, animations: { spinner.titleLabel.transform = CGAffineTransformIdentity spinner.titleLabel.alpha = 1.0 }, completion: nil) }) } } // // observe the view frame and update the subviews layout // public override var frame: CGRect { didSet { if frame == CGRect.zeroRect { return } blurView.frame = bounds vibrancyView.frame = blurView.bounds titleLabel.center = vibrancyView.center outerCircleView.center = vibrancyView.center innerCircleView.center = vibrancyView.center if let subtitle = subtitleLabel { subtitle.bounds.size = subtitle.sizeThatFits(CGRectInset(bounds, 20.0, 0.0).size) subtitle.center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMaxY(bounds) - CGRectGetMidY(subtitle.bounds) - subtitle.font.pointSize) } } } // // Start the spinning animation // public var animating: Bool = false { willSet (shouldAnimate) { if shouldAnimate && !animating { spinInner() spinOuter() } } didSet { // update UI if animating { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 0.45 self.innerCircle.strokeStart = 0.5 self.innerCircle.strokeEnd = 0.9 } else { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 1.0 self.innerCircle.strokeStart = 0.0 self.innerCircle.strokeEnd = 1.0 } } } // // Tap handler // public func addTapHandler(tap: (()->()), subtitle subtitleText: String? = nil) { clearTapHandler() userInteractionEnabled = true vibrancyView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTapSpinner"))) tapHandler = tap if subtitleText != nil { subtitleLabel = UILabel() if let subtitle = subtitleLabel { subtitle.text = subtitleText subtitle.font = UIFont(name: defaultTitleFont.familyName, size: defaultTitleFont.pointSize * 0.8) subtitle.textColor = UIColor.whiteColor() subtitle.numberOfLines = 0 subtitle.textAlignment = .Center subtitle.lineBreakMode = .ByWordWrapping subtitle.bounds.size = subtitle.sizeThatFits(CGRectInset(bounds, 20.0, 0.0).size) subtitle.center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMaxY(bounds) - CGRectGetMidY(subtitle.bounds) - subtitle.font.pointSize) vibrancyView.contentView.addSubview(subtitle) } } } public func clearTapHandler() { userInteractionEnabled = false subtitleLabel?.removeFromSuperview() tapHandler = nil } // MARK: - Private interface // // layout elements // private var blurEffectStyle: UIBlurEffectStyle = .Dark private var blurEffect: UIBlurEffect! private var blurView: UIVisualEffectView! private var vibrancyView: UIVisualEffectView! var defaultTitleFont = UIFont(name: "HelveticaNeue", size: 22.0)! let frameSize = CGSize(width: 200.0, height: 200.0) private lazy var outerCircleView = UIView() private lazy var innerCircleView = UIView() private let outerCircle = CAShapeLayer() private let innerCircle = CAShapeLayer() private var showWithDelayBlock: (()->())? required public init(coder aDecoder: NSCoder) { fatalError("Not coder compliant") } private var currentOuterRotation: CGFloat = 0.0 private var currentInnerRotation: CGFloat = 0.1 private func spinOuter() { if superview == nil { return } let duration = Double(Float(arc4random()) / Float(UInt32.max)) * 2.0 + 1.5 let randomRotation = Double(Float(arc4random()) / Float(UInt32.max)) * M_PI_4 + M_PI_4 //outer circle UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: nil, animations: { self.currentOuterRotation -= CGFloat(randomRotation) self.outerCircleView.transform = CGAffineTransformMakeRotation(self.currentOuterRotation) }, completion: {_ in let waitDuration = Double(Float(arc4random()) / Float(UInt32.max)) * 1.0 + 1.0 self.delay(seconds: waitDuration, completion: { if self.animating { self.spinOuter() } }) }) } private func spinInner() { if superview == nil { return } //inner circle UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: nil, animations: { self.currentInnerRotation += CGFloat(M_PI_4) self.innerCircleView.transform = CGAffineTransformMakeRotation(self.currentInnerRotation) }, completion: {_ in self.delay(seconds: 0.5, completion: { if self.animating { self.spinInner() } }) }) } public func updateFrame() { let window = UIApplication.sharedApplication().windows.first as! UIWindow SwiftSpinner.sharedInstance.frame = window.frame } // MARK: - Util methods func delay(#seconds: Double, completion:()->()) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds )) dispatch_after(popTime, dispatch_get_main_queue()) { completion() } } override public func layoutSubviews() { super.layoutSubviews() updateFrame() } // MARK: - Tap handler private var tapHandler: (()->())? func didTapSpinner() { tapHandler?() } }
mit
51edcd4fb6d4dbde1c1f384af001eef4
35.553846
463
0.596871
5.379623
false
false
false
false
fortmarek/SwipeViewController
SwipeViewController/SwipeViewController.swift
1
18361
// // SwipeViewController.swift // SwipeBetweenViewControllers // // Created by Marek Fořt on 11.03.16. // Copyright © 2016 Marek Fořt. All rights reserved. // import UIKit public enum Side { case left, right } open class SwipeViewController: UINavigationController, UIPageViewControllerDelegate, UIScrollViewDelegate { public private(set) var pages: [UIViewController] = [] public var startIndex: Int = 0 { didSet { guard pages.count > startIndex else { return } currentPageIndex = startIndex view.backgroundColor = pages[startIndex].view.backgroundColor } } public var selectionBarHeight: CGFloat = 0 { didSet { selectionBar.frame.size.height = selectionBarHeight } } public var selectionBarWidth: CGFloat = 0 { didSet { selectionBar.frame.size.width = selectionBarWidth } } public var selectionBarColor: UIColor = .black { didSet { selectionBar.backgroundColor = selectionBarColor } } public var buttonFont = UIFont.systemFont(ofSize: 18) { didSet { buttons.forEach { $0.titleLabel?.font = buttonFont } } } public var buttonColor: UIColor = .black { didSet { buttons.enumerated().filter { key, _ in currentPageIndex != key }.forEach { _, element in element.titleLabel?.textColor = buttonColor } } } public var selectedButtonColor: UIColor = .green { didSet { guard !buttons.isEmpty else { return } buttons[currentPageIndex].titleLabel?.textColor = selectedButtonColor } } public var navigationBarColor: UIColor = .white { didSet { navigationBar.barTintColor = navigationBarColor } } public var leftBarButtonItem: UIBarButtonItem? { didSet { pageController.navigationItem.leftBarButtonItem = leftBarButtonItem } } public var rightBarButtonItem: UIBarButtonItem? { didSet { pageController.navigationItem.rightBarButtonItem = rightBarButtonItem } } public var bottomOffset: CGFloat = 0 public var equalSpaces: Bool = true public var buttonsWithImages: [SwipeButtonWithImage] = [] public var offset: CGFloat = 40 public let pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) public var currentPageIndex = 0 public private(set) var buttons: [UIButton] = [] private var barButtonItemWidth: CGFloat = 0 private var navigationBarHeight: CGFloat = 0 private weak var selectionBar: UIView! private var totalButtonWidth: CGFloat = 0 private var finalPageIndex = -1 private var indexNotIncremented = true private var pageScrollView = UIScrollView() private var animationFinished = true private var leftSubtract: CGFloat = 0 private var firstWillAppearOccured = false private var spaces: [CGFloat] = [] private var x: CGFloat = 0 private var selectionBarOriginX: CGFloat = 0 private weak var navigationView: UIView! public init(pages: [UIViewController]) { super.init(nibName: nil, bundle: nil) self.pages = pages setViewControllers([pageController], animated: false) pageController.navigationController?.navigationItem.leftBarButtonItem = leftBarButtonItem pageController.delegate = self pageController.dataSource = self if let scrollView = pageController.view.subviews.compactMap({ $0 as? UIScrollView }).first { scrollView.delegate = self } barButtonItemWidth = pageController.navigationController?.navigationBar.topItem?.titleView?.layoutMargins.left ?? 0 navigationBar.isTranslucent = false let navigationView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: navigationBar.frame.height)) navigationView.backgroundColor = navigationBarColor pageController.navigationController?.navigationBar.topItem?.titleView = navigationView self.navigationView = navigationView barButtonItemWidth = navigationBar.topItem?.titleView?.layoutMargins.left ?? 0 addPages() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Method is called when `viewWillAppear(_:)` is called for the first time func viewWillFirstAppear(_: Bool) { updateButtonsAppearance() updateButtonsLayout() updateSelectionBarFrame() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !firstWillAppearOccured { viewWillFirstAppear(animated) firstWillAppearOccured = true } } private func setTitleLabel(_ page: UIViewController, font: UIFont, color: UIColor, button: UIButton) { // Title font and color guard let pageTitle = page.title else { return } let attributes: [NSAttributedString.Key: Any] = [.font: font] let attributedTitle = NSAttributedString(string: pageTitle, attributes: attributes) button.setAttributedTitle(attributedTitle, for: UIControl.State()) guard let titleLabel = button.titleLabel else { return } titleLabel.textColor = color titleLabel.sizeToFit() button.frame = titleLabel.frame } private func createSelectionBar() { let selectionBar = UIView() self.selectionBar = selectionBar // SelectionBar updateSelectionBarFrame() selectionBar.backgroundColor = selectionBarColor navigationView.addSubview(selectionBar) } private func updateSelectionBarFrame() { let originY = navigationView.frame.height - selectionBarHeight - bottomOffset selectionBar.frame = CGRect(x: selectionBarOriginX, y: originY, width: selectionBarWidth, height: selectionBarHeight) selectionBar.frame.origin.x -= leftSubtract } private func addPages() { view.backgroundColor = pages[currentPageIndex].view.backgroundColor createButtons() createSelectionBar() // Init of initial view controller guard currentPageIndex >= 0 else { return } let initialViewController = pages[currentPageIndex] pageController.setViewControllers([initialViewController], direction: .forward, animated: true, completion: nil) // Select button of initial view controller - change to selected image buttons[currentPageIndex].isSelected = true } private func createButtons() { buttons = (1 ... pages.count).map { let button = UIButton() button.tag = $0 navigationView.addSubview(button) return button } } private func updateButtonsAppearance() { totalButtonWidth = 0 buttons.enumerated().forEach { tag, button in if buttonsWithImages.isEmpty { setTitleLabel(pages[tag], font: buttonFont, color: buttonColor, button: button) } else { // Getting buttnWithImage struct from array let buttonWithImage = buttonsWithImages[tag] // Normal image button.setImage(buttonWithImage.image, for: UIControl.State()) // Selected image button.setImage(buttonWithImage.selectedImage, for: .selected) // Button tint color button.tintColor = buttonColor // Button size if let size = buttonWithImage.size { button.frame.size = size } } totalButtonWidth += button.frame.width } } private func updateButtonsLayout() { let totalButtonWidth = buttons.reduce(0) { $0 + $1.frame.width } var space: CGFloat = 0 var width: CGFloat = 0 if equalSpaces { // Space between buttons x = (view.frame.width - 2 * offset - totalButtonWidth) / CGFloat(buttons.count + 1) } else { // Space reserved for one button (with label and spaces around it) space = (view.frame.width - 2 * offset) / CGFloat(buttons.count) } for button in buttons { let buttonHeight = button.frame.height let buttonWidth = button.frame.width let originY = navigationView.frame.height - selectionBarHeight - bottomOffset - buttonHeight - 3 var originX: CGFloat = 0 if equalSpaces { originX = x * CGFloat(button.tag) + width + offset - barButtonItemWidth width += buttonWidth } else { let buttonSpace = space - buttonWidth originX = buttonSpace / 2 + width + offset - barButtonItemWidth width += buttonWidth + space - buttonWidth spaces.append(buttonSpace) } if button.tag == currentPageIndex + 1 { guard let titleLabel = button.titleLabel else { continue } selectionBarOriginX = originX - (selectionBarWidth - buttonWidth) / 2 titleLabel.textColor = selectedButtonColor } button.frame = CGRect(x: originX, y: originY, width: buttonWidth, height: buttonHeight) addFunction(button) } updateLeftSubtract() buttons.forEach { $0.frame.origin.x -= leftSubtract } } private func updateLeftSubtract() { guard let firstButton = buttons.first else { return } let convertedXOrigin = firstButton.convert(firstButton.frame.origin, to: view).x let barButtonWidth: CGFloat = equalSpaces ? 0 : barButtonItemWidth let leftSubtract: CGFloat = (convertedXOrigin - offset + barButtonWidth) / 2 - x / 2 self.leftSubtract = leftSubtract } open func scrollViewDidScroll(_ scrollView: UIScrollView) { let xFromCenter = view.frame.width - scrollView.contentOffset.x var width: CGFloat = 0 let border = view.frame.width - 1 guard currentPageIndex >= 0, currentPageIndex < buttons.endIndex else { return } // Ensuring currentPageIndex is not changed twice if -border ... border ~= xFromCenter { indexNotIncremented = true } // Resetting finalPageIndex for switching tabs if xFromCenter == 0 { finalPageIndex = -1 animationFinished = true } // Going right if xFromCenter <= -view.frame.width, indexNotIncremented, currentPageIndex < buttons.endIndex - 1 { view.backgroundColor = pages[currentPageIndex + 1].view.backgroundColor currentPageIndex += 1 indexNotIncremented = false } // Going left else if xFromCenter >= view.frame.width, indexNotIncremented, currentPageIndex >= 1 { view.backgroundColor = pages[currentPageIndex - 1].view.backgroundColor currentPageIndex -= 1 indexNotIncremented = false } if buttonColor != selectedButtonColor { changeButtonColor(xFromCenter) } for button in buttons { var originX: CGFloat = 0 var space: CGFloat = 0 if equalSpaces { originX = x * CGFloat(button.tag) + width width += button.frame.width } else { space = spaces[button.tag - 1] originX = space / 2 + width width += button.frame.width + space } let selectionBarOriginX = originX - (selectionBarWidth - button.frame.width) / 2 + offset - barButtonItemWidth - leftSubtract // Get button with current index guard button.tag == currentPageIndex + 1 else { continue } var nextButton = UIButton() var nextSpace: CGFloat = 0 if xFromCenter < 0, button.tag < buttons.count { nextButton = buttons[button.tag] if equalSpaces == false { nextSpace = spaces[button.tag] } } else if xFromCenter > 0, button.tag != 1 { nextButton = buttons[button.tag - 2] if equalSpaces == false { nextSpace = spaces[button.tag - 2] } } var newRatio: CGFloat = 0 if equalSpaces { let expression = 2 * x + button.frame.width - (selectionBarWidth - nextButton.frame.width) / 2 newRatio = view.frame.width / (expression - (x - (selectionBarWidth - button.frame.width) / 2)) } else { let expression = button.frame.width + space / 2 + (selectionBarWidth - button.frame.width) / 2 newRatio = view.frame.width / (expression + nextSpace / 2 - (selectionBarWidth - nextButton.frame.width) / 2) } selectionBar.frame = CGRect(x: selectionBarOriginX - (xFromCenter / newRatio), y: selectionBar.frame.origin.y, width: selectionBarWidth, height: selectionBarHeight) return } } // Triggered when selected button in navigation view is changed func scrollToNextViewController(_ index: Int) { let currentViewControllerIndex = currentPageIndex // Comparing index (i.e. tab where user is going to) and when compared, we can now know what direction we should go // Index is on the right if index > currentViewControllerIndex { // loop - if user goes from tab 1 to tab 3 we want to have tab 2 in animation for viewControllerIndex in currentViewControllerIndex ... index { let destinationViewController = pages[viewControllerIndex] pageController.setViewControllers([destinationViewController], direction: .forward, animated: true, completion: nil) } } // Index is on the left else { for viewControllerIndex in (index ... currentViewControllerIndex).reversed() { let destinationViewController = pages[viewControllerIndex] pageController.setViewControllers([destinationViewController], direction: .reverse, animated: true, completion: nil) } } } @objc func switchTabs(_ sender: UIButton) { let index = sender.tag - 1 // Can't animate twice to the same controller (otherwise weird stuff happens) guard index != finalPageIndex, index != currentPageIndex, animationFinished else { return } animationFinished = false finalPageIndex = index scrollToNextViewController(index) } func addFunction(_ button: UIButton) { button.addTarget(self, action: #selector(switchTabs(_:)), for: .touchUpInside) } func changeButtonColor(_ xFromCenter: CGFloat) { // Change color of button before animation finished (i.e. colour changes even when the user is between buttons let viewWidthHalf = view.frame.width / 2 let border = view.frame.width - 1 let halfBorder = view.frame.width / 2 - 1 // Going left, next button selected if viewWidthHalf ... border ~= xFromCenter, currentPageIndex > 0 { let button = buttons[currentPageIndex - 1] let previousButton = buttons[currentPageIndex] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } // Going right, current button selected else if 0 ... halfBorder ~= xFromCenter, currentPageIndex > 1 { let button = buttons[currentPageIndex] let previousButton = buttons[currentPageIndex - 1] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } // Going left, current button selected else if -halfBorder ... 0 ~= xFromCenter, currentPageIndex < buttons.endIndex - 1 { let previousButton = buttons[currentPageIndex + 1] let button = buttons[currentPageIndex] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } // Going right, next button selected else if -border ... -viewWidthHalf ~= xFromCenter, currentPageIndex < buttons.endIndex - 1 { let button = buttons[currentPageIndex + 1] let previousButton = buttons[currentPageIndex] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } } } extension SwipeViewController: UIPageViewControllerDataSource { // Swiping left public func pageViewController(_: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { // Get current view controller index guard let viewControllerIndex = pages.firstIndex(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 // Making sure the index doesn't get bigger than the array of view controllers guard previousIndex >= 0, pages.count > previousIndex else { return nil } return pages[previousIndex] } // Swiping right public func pageViewController(_: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { // Get current view controller index guard let viewControllerIndex = pages.firstIndex(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 // Making sure the index doesn't get bigger than the array of view controllers guard pages.count > nextIndex else { return nil } return pages[nextIndex] } }
mit
ff7d09a27ca3089ff0fc79a272be7444
36.696099
176
0.63057
5.434577
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Models/Alert.swift
1
1826
// // Alert.swift // MEGameTracker // // Created by Emily Ivie on 4/14/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit /// Helper for showing alerts. public struct Alert { // MARK: Types public typealias ActionButtonType = (title: String, style: UIAlertAction.Style, handler: ((UIAlertAction) -> Void)) // MARK: Properties public var title: String public var description: String public var actions: [ActionButtonType] = [] // MARK: Change Listeners And Change Status Flags public static var onSignal = Signal<(Alert)>() // MARK: Initialization public init(title: String?, description: String) { self.title = title ?? "" self.description = description } } // MARK: Basic Actions extension Alert { /// Pops up an alert in the specified controller. public func show(fromController controller: UIViewController, sender: UIView? = nil) { let alert = UIAlertController(title: title, message: description, preferredStyle: .alert) if actions.isEmpty { alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { _ in })) } else { for action in actions { alert.addAction(UIAlertAction(title: action.title, style: action.style, handler: action.handler)) } } alert.popoverPresentationController?.sourceView = sender ?? controller.view alert.modalPresentationStyle = .popover // Alert default button defaults to window tintColor (red), // Which is too similar to destructive button (red), // And I can't change it in Styles using appearance(), // So I have to do it here, which pisses me off. alert.view.tintColor = UIColor.systemBlue // Styles.colors.altTint if let bounds = sender?.bounds { alert.popoverPresentationController?.sourceRect = bounds } controller.present(alert, animated: true, completion: nil) } }
mit
86d28705497d73ce6e80672899d8f164
27.968254
116
0.716164
3.93319
false
false
false
false
petester42/RxSwift
RxSwift/Observables/Implementations/Window.swift
4
4218
// // Buffer.swift // Rx // // Created by Junior B. on 29/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class WindowTimeCountSink<S: SchedulerType, Element, O: ObserverType where O.E == Observable<Element>> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType { typealias Parent = WindowTimeCount<Element, S> typealias E = Element private let _parent: Parent let _lock = NSRecursiveLock() private var _subject = PublishSubject<Element>() private var _count = 0 private var _windowId = 0 private let _timerD = SerialDisposable() private let _refCountDisposable: RefCountDisposable private let _groupDisposable = CompositeDisposable() init(parent: Parent, observer: O) { _parent = parent _groupDisposable.addDisposable(_timerD) _refCountDisposable = RefCountDisposable(disposable: _groupDisposable) super.init(observer: observer) } func run() -> Disposable { forwardOn(.Next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) createTimer(_windowId) _groupDisposable.addDisposable(_parent._source.subscribeSafe(self)) return _refCountDisposable } func startNewWindowAndCompleteCurrentOne() { _subject.on(.Completed) _subject = PublishSubject<Element>() forwardOn(.Next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) } func on(event: Event<E>) { synchronizedOn(event) } func _synchronized_on(event: Event<E>) { var newWindow = false var newId = 0 switch event { case .Next(let element): _subject.on(.Next(element)) do { try incrementChecked(&_count) } catch (let e) { _subject.on(.Error(e as ErrorType)) dispose() } if (_count == _parent._count) { newWindow = true _count = 0 newId = ++_windowId self.startNewWindowAndCompleteCurrentOne() } case .Error(let error): _subject.on(.Error(error)) forwardOn(.Error(error)) dispose() case .Completed: _subject.on(.Completed) forwardOn(.Completed) dispose() } if newWindow { createTimer(newId) } } func createTimer(windowId: Int) { if _timerD.disposed { return } if _windowId != windowId { return } let nextTimer = SingleAssignmentDisposable() _timerD.disposable = nextTimer nextTimer.disposable = _parent._scheduler.scheduleRelative(windowId, dueTime: _parent._timeSpan) { previousWindowId in var newId = 0 self._lock.performLocked { if previousWindowId != self._windowId { return } self._count = 0 self._windowId = self._windowId &+ 1 newId = self._windowId self.startNewWindowAndCompleteCurrentOne() } self.createTimer(newId) return NopDisposable.instance } } } class WindowTimeCount<Element, S: SchedulerType> : Producer<Observable<Element>> { private let _timeSpan: S.TimeInterval private let _count: Int private let _scheduler: S private let _source: Observable<Element> init(source: Observable<Element>, timeSpan: S.TimeInterval, count: Int, scheduler: S) { _source = source _timeSpan = timeSpan _count = count _scheduler = scheduler } override func run<O : ObserverType where O.E == Observable<Element>>(observer: O) -> Disposable { let sink = WindowTimeCountSink(parent: self, observer: observer) sink.disposable = sink.run() return sink } }
mit
5a61b585fbd6732d2aa0de3eb6c49553
26.927152
126
0.555371
5.148962
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Models/CoreData/CoreDataMigrations/CoreDataEliminateDuplicates.swift
1
1070
// // CoreDataEliminateDuplicates.swift // MEGameTracker // // Created by Emily Ivie on 12/31/17. // Copyright © 2017 Emily Ivie. All rights reserved. // import Foundation public struct CoreDataEliminateDuplicates: CoreDataMigrationType { public func run() { deleteDuplicates(type: DataDecision.self) deleteDuplicates(type: DataEvent.self) deleteDuplicates(type: DataItem.self) deleteDuplicates(type: DataMap.self) deleteDuplicates(type: DataMission.self) deleteDuplicates(type: DataPerson.self) } private func deleteDuplicates<T: DataRowStorable>(type: T.Type) { T.getAllIds() .reduce([String: Int]()) { var l = $0; l[$1, default: 0] += 1; return l } .filter { $0.1 > 1 } .forEach { let rows = T.getAll(ids: [$0.0]) for index in 1..<rows.count { var row = rows[index] print("Deleted duplicate row \($0.0)") _ = row.delete() } } } }
mit
14c66e224ea5006346743f337d766e9e
29.542857
85
0.565949
4.095785
false
false
false
false
BPForEveryone/BloodPressureForEveryone
BPApp/BPEveryone/BPEMainViewController.swift
1
1723
// // BPEMainViewController.swift // BPApp // // Created by Chris Blackstone on 4/24/17. // Copyright © 2017 BlackstoneBuilds. All rights reserved. // import UIKit class BPEMainVewController: UIViewController { @IBOutlet weak var viewPatientsButton: UIButton! @IBOutlet weak var quickResourcesButton: UIButton! @IBOutlet weak var settingsButton: UIButton! let btnRadius: CGFloat = 20; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // This sets the system's default measurement system as the app's default // viewPatientsButton.layer.cornerRadius = btnRadius; // quickResourcesButton.layer.cornerRadius = btnRadius; // settingsButton.layer.cornerRadius = btnRadius; // if UserDefaults.standard.value(forKey: "numSystemChanged") as? Bool != true { UserDefaults.standard.set(false, forKey: "numSystemChanged") let isMetric = (Locale.current as NSLocale).object(forKey: NSLocale.Key.usesMetricSystem) as! Bool if isMetric { UserDefaults.standard.set(1, forKey: "numSystem") } else { UserDefaults.standard.set(0, forKey: "numSystem") } } //print("numSystemChanged: ",UserDefaults.standard.value(forKey: "numSystemChanged") ?? "numSystemChanged not set") //print("start numSystem: ",UserDefaults.standard.value(forKey: "numSystem") ?? "numSystem not set") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
c6d4253a4d4fcb308e571a442ca27fc1
37.266667
123
0.656794
4.507853
false
false
false
false
peihsendoyle/ZCPlayer
ZCPlayer/ZCPlayer/PlayerView.swift
1
8631
// // PlayerView.swift // ZCPlayer // // Created by Doyle Illusion on 7/5/17. // Copyright © 2017 Zyncas Technologies. All rights reserved. // import UIKit import AVFoundation protocol PlayerViewDelegate : class { func didScrubbing() func didBeginScrubbing() func didEndScrubbing() func didTouchToggleButton(isPlay: Bool) } class PlayerView: UIView { weak var delegate : PlayerViewDelegate? fileprivate let indicator = UIActivityIndicatorView() fileprivate let containerView = UIView() fileprivate let currentTimeLabel = UILabel() fileprivate let durationTimeLabel = UILabel() fileprivate var gestureRecognizer : UITapGestureRecognizer! let slider = BufferSlider() fileprivate let button = UIButton() fileprivate var timer = Timer() override class var layerClass: AnyClass { return AVPlayerLayer.self } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear (self.layer as! AVPlayerLayer).frame = self.bounds (self.layer as! AVPlayerLayer).videoGravity = AVLayerVideoGravityResizeAspectFill self.initComponents() self.initConstraints() } fileprivate func initComponents() { self.gestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.touchedPlayerView)) self.addGestureRecognizer(self.gestureRecognizer) self.indicator.hidesWhenStopped = true self.indicator.activityIndicatorViewStyle = .white self.addSubview(self.indicator) self.containerView.backgroundColor = .clear self.containerView.isHidden = true self.addSubview(self.containerView) self.button.setImage(UIImage.init(named: "mini-play"), for: .selected) self.button.setImage(UIImage.init(named: "mini-pause"), for: .normal) self.button.isSelected = false self.button.tintColor = .white self.button.addTarget(self, action: #selector(self.touchedButton), for: .touchUpInside) self.containerView.addSubview(self.button) self.slider.addTarget(self, action: #selector(self.endScrubbing), for: .touchCancel) self.slider.addTarget(self, action: #selector(self.beginScrubbing), for: .touchDown) self.slider.addTarget(self, action: #selector(self.scrub), for: .touchDragInside) self.slider.addTarget(self, action: #selector(self.endScrubbing), for: .touchUpInside) self.slider.addTarget(self, action: #selector(self.endScrubbing), for: .touchUpOutside) self.slider.addTarget(self, action: #selector(self.scrub), for: .valueChanged) self.containerView.addSubview(self.slider) self.currentTimeLabel.text = "00:00" self.currentTimeLabel.textAlignment = .left self.currentTimeLabel.textColor = .white self.currentTimeLabel.font = UIFont.systemFont(ofSize: 12.0) self.containerView.addSubview(self.currentTimeLabel) self.durationTimeLabel.text = "--:--" self.durationTimeLabel.textAlignment = .right self.durationTimeLabel.textColor = .white self.durationTimeLabel.font = UIFont.systemFont(ofSize: 12.0) self.containerView.addSubview(self.durationTimeLabel) } fileprivate func initConstraints() { self.indicator.translatesAutoresizingMaskIntoConstraints = false self.containerView.translatesAutoresizingMaskIntoConstraints = false self.slider.translatesAutoresizingMaskIntoConstraints = false self.currentTimeLabel.translatesAutoresizingMaskIntoConstraints = false self.durationTimeLabel.translatesAutoresizingMaskIntoConstraints = false self.button.translatesAutoresizingMaskIntoConstraints = false let views = ["slider": self.slider, "current": self.currentTimeLabel, "duration": self.durationTimeLabel, "indicator": self.indicator, "containerView": self.containerView, "button": self.button] self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[indicator(30)]", options: [], metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[indicator(30)]", options: [], metrics: nil, views: views)) self.addConstraint(NSLayoutConstraint.init(item: self.indicator, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint.init(item: self.indicator, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[containerView]|", options: [], metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[containerView]|", options: [], metrics: nil, views: views)) self.containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[slider]-20-|", options: [], metrics: nil, views: views)) self.containerView.addConstraint(NSLayoutConstraint.init(item: self.currentTimeLabel, attribute: .centerY, relatedBy: .equal, toItem: self.slider, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.containerView.addConstraint(NSLayoutConstraint.init(item: self.durationTimeLabel, attribute: .centerY, relatedBy: .equal, toItem: self.slider, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.containerView.addConstraint(NSLayoutConstraint.init(item: self.button, attribute: .centerY, relatedBy: .equal, toItem: self.slider, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[button(15)]", options: [], metrics: nil, views: views)) self.containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[button(15)]-8-[current(35)]-8-[slider]-8-[duration(35)]-16-|", options: [], metrics: nil, views: views)) } fileprivate dynamic func touchedPlayerView() { if self.containerView.isHidden == true { self.showContainerView() } else { self.hideContainerView() } } dynamic func hideContainerView() { guard self.containerView.isHidden == false else { return } UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: { self.containerView.alpha = 0 }, completion: { _ in self.containerView.isHidden = true self.timer.invalidate() }) } func showContainerView() { guard self.containerView.isHidden == true else { return } self.containerView.isHidden = false UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: { self.containerView.alpha = 1 }, completion: { _ in self.timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.hideContainerView), userInfo: nil, repeats: false) }) } fileprivate dynamic func touchedButton() { self.button.isSelected = !self.button.isSelected self.delegate?.didTouchToggleButton(isPlay: self.button.isSelected) } func showLoading() { self.indicator.startAnimating() } func hideLoading() { self.indicator.stopAnimating() } func enableSlider() { self.slider.isEnabled = true } func disableSlider() { self.slider.isEnabled = false } func syncSlider(value: Double) { self.slider.value = Float(value) } func syncTime(value: Double) { self.currentTimeLabel.text = String(value).timeIntervalToMMSSFormat(value) } func syncDuration(value: Double) { self.durationTimeLabel.text = String(value).timeIntervalToMMSSFormat(value) } dynamic fileprivate func scrub() { self.delegate?.didScrubbing() } dynamic fileprivate func beginScrubbing() { self.timer.invalidate() self.delegate?.didBeginScrubbing() } dynamic fileprivate func endScrubbing() { self.timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.hideContainerView), userInfo: nil, repeats: false) self.delegate?.didEndScrubbing() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
553c72d14224cf2624edf1a2a354aac1
43.947917
209
0.682503
4.765323
false
false
false
false
huankong/Weibo
Weibo/Weibo/Main/Base/Oauth/Oauth2ViewController.swift
1
4105
// // Oauth2ViewController.swift // Weibo // // Created by ldy on 16/7/4. // Copyright © 2016年 ldy. All rights reserved. // //App Key:3078732713 //App Secret:58204b0c2c143b55a219866eff83d8a8 //https://www.baidu.com import UIKit import SVProgressHUD class Oauth2ViewController: UIViewController { override func loadView() { view = webView } let appKey = "3078732713" let appSecret = "58204b0c2c143b55a219866eff83d8a8" let appURLDirect = "https://www.baidu.com" override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(appURLDirect)") // print(url) webView.loadRequest(NSURLRequest(URL: url!)) //导航栏 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(Oauth2ViewController.naviBtnAction)) } // deinit { // print("Oauth2ViewController销毁") // } //MARK: - 点击事件 func naviBtnAction() { if webView.canGoBack { webView.goBack() }else { dismissViewControllerAnimated(true, completion: nil) } } //MARK: - 懒加载 private lazy var webView: UIWebView = { let webView = UIWebView(frame: UIScreen.mainScreen().bounds) webView.delegate = self return webView }() } extension Oauth2ViewController: UIWebViewDelegate { func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { //取消 https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330 //授权之后 https://www.baidu.com/?code=9fe89e4e9539794f43e5179d7c4f5d64 //获取完成字符串 let urlStr = request.URL?.absoluteString //判断如果不是回调继续加载 if !(urlStr!.hasPrefix(appURLDirect)) { return true } //获取回调地址code let queryStr = request.URL?.query // print(queryStr) let code = "code=" if queryStr!.hasPrefix(code) { let codeStr = queryStr?.substringFromIndex(code.endIndex) //根据获取的codeToken换取Access Token getAccessToken(codeStr!) } else { dismissViewControllerAnimated(true, completion: nil) } return false } func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.showWithStatus("正在加载,请稍后。。。") SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.Dark) SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Gradient) } func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.dismiss() } /** 根据获取的codeStr换取Access Token - parameter codeStr: codeToken */ func getAccessToken(codeStr: String) { let paramer = ["client_id":appKey,"client_secret":appSecret,"grant_type":"authorization_code","code":codeStr,"redirect_uri":appURLDirect] DataServer.shareInstance().requsetData(NetMethod.POST, urlStr: "oauth2/access_token", paramer: paramer, success: { (response) in let acount = UserAcount(dict: response as! [String: AnyObject]) acount.loadUserInfo({ (account, error) in if account != nil { account?.saveAccount() SVProgressHUD.dismiss() self.dismissViewControllerAnimated(true, completion: nil) // 去欢迎界面 NSNotificationCenter.defaultCenter().postNotificationName(KSwiftRootViewControllerKey, object: false) return } }) }) { (error) in print(error) SVProgressHUD.dismiss() } } }
apache-2.0
44f23ce3a248d5387a8b3ed09cb201e8
33.631579
175
0.616008
4.435955
false
false
false
false
philipgreat/b2b-swift-app
B2BSimpleApp/B2BSimpleApp/ProductRemoteManagerImpl.swift
1
2250
//Domain B2B/Product/ import SwiftyJSON import Alamofire import ObjectMapper class ProductRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{ override init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } override var remoteURLPrefix:String{ //Every manager need to config their own URL return "https://philipgreat.github.io/naf/productManager/" } func loadProductDetail(productId:String, productSuccessAction: (Product)->String, productErrorAction: (String)->String){ let methodName = "loadProductDetail" let parameters = [productId] let url = compositeCallURL(methodName, parameters: parameters) Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let product = self.extractProductFromJSON(json){ productSuccessAction(product) } } case .Failure(let error): print(error) productErrorAction("\(error)") } } } func extractProductFromJSON(json:JSON) -> Product?{ let jsonTool = SwiftyJSONTool() let product = jsonTool.extractProduct(json) return product } //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). let result = "ProductRemoteManagerImpl, V1" return result } static var CLASS_VERSION = 1 //This value is for serializer like message pack to identify the versions match between //local and remote object. } //Reference http://grokswift.com/simple-rest-with-swift/ //Reference https://github.com/SwiftyJSON/SwiftyJSON //Reference https://github.com/Alamofire/Alamofire //Reference https://github.com/Hearst-DD/ObjectMapper //let remote = RemoteManagerImpl() //let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"]) //print(result)
mit
4f7242a06761b9e57f34a97b27912bd3
25.439024
100
0.688889
3.88601
false
false
false
false
chenchangqing/learnioscollectionview
example01/example01/ViewController.swift
1
18460
// // ViewController.swift // example01 // // Created by green on 15/8/20. // Copyright (c) 2015年 com.chenchangqing. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, CollectionViewHeaderDelegate { private var dataSource : [String:[[String:String]]]! private var collectionView : UICollectionView! private var expandSectionArray = [String:Bool]() // 每一节是否已经被展开 private var constructionDic : [String:[Int]]! // collectionView数据的排列结构 { get{ // 计算 return caculateLayoutForDataSource() } } private var showRowsCount = 1 // 默认显示行数 private var numberOfItemsInSectionDic : [String:Int]! // 每一节对应显示的items的数量 { get { // 计算 return caculateNumberOfItemsInSectionDic() } } private var isShowMoreBtnDic:[String:Bool]! // 每一节对应的更多按钮是否显示 { get { // 计算 return caculateIsShowMoreBtnDic() } } let kCellIdentifier = "CellIdentifier" // 重用单元格ID let kHeaderViewCellIdentifier = "HeaderViewCellIdentifier" // 重用标题ID let kDataSourceCellTextKey = "Food_Name"; // json key1 let kDataSourceCellPictureKey = "Picture"; // json key2 // collectionView的 左、上、右、下 边距 let kCollectionViewToLeftMargin : CGFloat = 16 let kCollectionViewToTopMargin : CGFloat = 12 let kCollectionViewToRightMargin : CGFloat = 16 let kCollectionViewToBottomtMargin : CGFloat = 10 let kCollectionViewCellsHorizonPadding : CGFloat = 12 // items 之间的水平间距padding let kCollectionViewCellHeight : CGFloat = 30 // item height let kCellBtnHorizonPadding : CGFloat = 16 // item 中按钮padding let kCollectionViewItemButtonImageToTextMargin : CGFloat = 5 // item 文字和图片的距离 // MARK: - override func viewDidLoad() { super.viewDidLoad() setup() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - setup private func setup() { // 设置数据源 setupDataSource() // 增加collectionView setupCollectionView() } /** * 加载数据源 */ private func setupDataSource() { // 单例 struct DataSourceSingleton{ static var predicate:dispatch_once_t = 0 static var instance:[String:[[String:String]]]! } dispatch_once(&DataSourceSingleton.predicate, { () -> Void in DataSourceSingleton.instance = [String:[[String:String]]]() let filePath = NSBundle.mainBundle().pathForResource("data", ofType: "json")! let data = NSFileManager.defaultManager().contentsAtPath(filePath) var error:NSError? if let data = data { DataSourceSingleton.instance = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [String:[[String:String]]] } }) // 设置数据源 dataSource = DataSourceSingleton.instance } /** * 增加集合控件 */ private func setupCollectionView() { // 创建collectionView let layout = UICollectionViewLeftAlignedLayout() collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) // 默认为黑色,这里设置为白色以便显示 collectionView.backgroundColor = UIColor.whiteColor() // 内容下移20,为了不遮挡状态栏 collectionView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) // add collectionView view.addSubview(collectionView) // 重用Cell、Header collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: kCellIdentifier) collectionView.registerClass(CollectionViewHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewCellIdentifier) // 设置collection代理为self collectionView.dataSource = self collectionView.delegate = self } // MARK: - UICollectionViewDataSource /** * items count */ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let key = dataSource.keys.array[section] if let flag = expandSectionArray[key] { if flag { return dataSource[key]!.count } } return numberOfItemsInSectionDic[dataSource.keys.array[section]]! } /** * cell */ func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let collectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(kCellIdentifier, forIndexPath: indexPath) as! CollectionViewCell // 处理数据 let item = dicForItem(indexPath: indexPath) let text = item[kDataSourceCellTextKey] let img = item[kDataSourceCellPictureKey] // 重新计算button frame collectionViewCell.button.frame = CGRectMake(0, 0, CGRectGetWidth(collectionViewCell.frame), CGRectGetHeight(collectionViewCell.frame)) // 文字 collectionViewCell.button.setTitle(text, forState: UIControlState.Normal) collectionViewCell.button.setTitle(text, forState: UIControlState.Selected) // 设置图片 if img != nil { collectionViewCell.button.setImage(UIImage(named: "home_btn_shrink"), forState: UIControlState.Normal) let spacing = kCollectionViewItemButtonImageToTextMargin collectionViewCell.button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing) collectionViewCell.button.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0) } else { collectionViewCell.button.setImage(nil, forState: UIControlState.Normal) collectionViewCell.button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0) collectionViewCell.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0) } return collectionViewCell } /** * sections count */ func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return dataSource.count } /** * header */ func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var collectionViewHeader:CollectionViewHeader! if kind == UICollectionElementKindSectionHeader { collectionViewHeader = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewCellIdentifier, forIndexPath: indexPath) as! CollectionViewHeader collectionViewHeader.titleButton.setTitle(dataSource.keys.array[indexPath.section], forState: UIControlState.Normal) collectionViewHeader.titleButton.setTitle(dataSource.keys.array[indexPath.section], forState: UIControlState.Selected) // 是否显示更多 let key = dataSource.keys.array[indexPath.section] collectionViewHeader.rightButton.hidden = !isShowMoreBtnDic[key]! collectionViewHeader.rightButton.tag = indexPath.section // 设置代理 collectionViewHeader.delegate = self // 设置rightButton状态 if let flag = expandSectionArray[key] { if flag { collectionViewHeader.rightButton.selected = true } else { collectionViewHeader.rightButton.selected = false } } } return collectionViewHeader } // MARK: - UICollectionViewDelegateFlowLayout /** * item size */ func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let item = dicForItem(indexPath: indexPath) let cellWidth = caculateItemWidth(item: item) return CGSizeMake(cellWidth, kCollectionViewCellHeight) } /** * header edge */ func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(kCollectionViewToTopMargin, kCollectionViewToLeftMargin, kCollectionViewToBottomtMargin, kCollectionViewToRightMargin) } /** * items 左右之间的最小间距 */ func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return kCollectionViewCellsHorizonPadding } /** * header size */ func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSizeMake(CGRectGetWidth(view.bounds) - 50, 38) } // MARK: - caculate /** * 返回item的width * * @item item单元格数据 * * @return item的宽度 */ private func caculateItemWidth(#item:[String:String]) -> CGFloat { let text = item[kDataSourceCellTextKey]! let img = item[kDataSourceCellPictureKey] let size = (text as NSString).sizeWithAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16)]) let limitWidth = CGRectGetWidth(collectionView.frame) - kCollectionViewToLeftMargin - kCollectionViewToRightMargin var cellWidth:CGFloat = CGFloat(ceilf(Float(size.width))) + kCellBtnHorizonPadding // 如果包含图片,增加item的宽度 if img != nil { cellWidth += kCellBtnHorizonPadding } // 如果通过文字+图片计算出来的宽度大于等于限制宽度,则改变单元格item的实际宽度 cellWidth = cellWidth >= limitWidth ? limitWidth : cellWidth return cellWidth } /** * 返回item包括左右边距做需要占据的长度 * * @indexPath item 单元格数据 * @index item位置 * * @return item的占据的宽度 */ private func caculateItemLimitWidth (#item:[String:String],indexAtItems index:Int) -> CGFloat { let contentViewWidth = CGRectGetWidth(collectionView.frame) - kCollectionViewToLeftMargin - kCollectionViewToRightMargin // 计算单元格item的实际宽度 let itemWidth = caculateItemWidth(item: item) // 单元格item占据的宽度,用于计算该item单元格属于哪一行 var limitWidth : CGFloat! // 如果item的实际宽度等于最大限制宽度,那么item占据宽度等于最大限制宽度 if itemWidth == contentViewWidth { limitWidth = itemWidth } else { // 如果单元格item是数组中第一个,那么不需要+水平间距 if index == 0 { limitWidth = itemWidth } else { let contentViewWidth2 = contentViewWidth - kCollectionViewCellsHorizonPadding if itemWidth >= contentViewWidth2 { // 如果单元格item不是第一个,而且itemWidth大于最大限制宽度-水平间距,那么item占据宽度为最大限制 limitWidth = contentViewWidth } else { // 正常占据 limitWidth = itemWidth + kCollectionViewCellsHorizonPadding } } } return limitWidth } /** * 计算指定数组第一行的Item数量 * * @param items * * @return 指定数组第一行的Item数量 */ private func caculateItemsCountForFirstRow (#items:[[String:String]]) -> Int { var itemsCount: Int = 0 let contentViewWidth = CGRectGetWidth(collectionView.frame) - kCollectionViewToLeftMargin - kCollectionViewToRightMargin let widthArray = NSMutableArray() for (var i=0; i<items.count; i++) { let limitWidth = caculateItemLimitWidth(item: items[i], indexAtItems: i) widthArray.addObject(limitWidth) let sumArray = NSArray(array: widthArray) let sum:CGFloat = sumArray.valueForKeyPath("@sum.self") as! CGFloat if sum <= contentViewWidth { itemsCount++ } else { break } } return itemsCount } /** * 返回指定节item的分布结构,例如:[4,3] 表示 指定节第一行有4个元素,第二行有3个元素 * @param items * * @return 行数组 */ private func caculateItemsCountForEveryRow(var #items:[[String:String]]) -> [Int] { var resultArray = [Int]() let tempArray = NSMutableArray(array: items) let itemCount = caculateItemsCountForFirstRow(items: items) resultArray.append(itemCount) for item in tempArray { let itemCount = caculateItemsCountForFirstRow(items: items) if items.count != itemCount { items.removeRange(Range(start: 0, end: itemCount)) let itemCount = caculateItemsCountForFirstRow(items: items) resultArray.append(itemCount) } } return resultArray } /** * 返回整个collection的布局,例如:["菜系":[4,3],"厨房工具":[2,2]] 表示 菜系 匹配的节 有两行,分别对应的元素个数为4、3 * * @return 整个collection的布局 */ private func caculateLayoutForDataSource() -> [String:[Int]] { var resultDic = [String:[Int]]() for key in dataSource.keys.array { let tempArray = caculateItemsCountForEveryRow(items: dataSource[key]!) resultDic[key] = tempArray } return resultDic } /** * 返回每节包含多少行 */ private func caculateRowsCountForSection() -> [Int] { var resultArray = [Int]() for(var i=0; i<dataSource.count; i++) { let items = arrayForSection(section: i) let rowsCount = caculateItemsCountForEveryRow(items: items).count resultArray.append(rowsCount) } return resultArray } /** * 返回每节对应显示items的个数 */ private func caculateNumberOfItemsInSectionDic() -> [String:Int] { var resultDic = [String:Int]() for key in constructionDic.keys.array { var sum: Int = 0 let rowsArray = constructionDic[key]! for (var i=0; i<rowsArray.count; i++) { if i < showRowsCount { sum += rowsArray[i] } else { break } } resultDic[key] = sum } return resultDic } /** * 返回每个节是否应该显示更多按钮 */ private func caculateIsShowMoreBtnDic() -> [String: Bool] { var resultDic = [String: Bool]() for key in constructionDic.keys.array { let rowsArray = constructionDic[key]! if rowsArray.count > showRowsCount { resultDic[key] = true } else { resultDic[key] = false } } return resultDic } // MARK: - 处理数据 /** * 返回节对应的数组 */ private func arrayForSection(#section:Int) -> [[String:String]] { // 处理数据 let key = dataSource.keys.array[section] let items = dataSource[key]! return items } /** * 返回item数据 */ private func dicForItem(#indexPath:NSIndexPath) -> [String:String] { let items = arrayForSection(section: indexPath.section) let item = items[indexPath.row] return item } // MARK: - CollectionViewHeaderDelegate func collectionViewHeaderMoreBtnClicked(sender: UIButton) { sender.selected = !sender.selected let key = dataSource.keys.array[sender.tag] expandSectionArray[key] = sender.selected // 更新collectionView collectionView.performBatchUpdates({ () -> Void in let section = NSIndexSet(index: sender.tag) self.collectionView.reloadSections(section) }, completion: { (finished) -> Void in }) } }
apache-2.0
31efc61763640e60b262538a5b26df34
31.148423
224
0.575889
5.471424
false
false
false
false
toggl/superday
teferi/UI/Modules/Main/CMAccessForExistingUsersPresenter.swift
1
967
import Foundation class CMAccessForExistingUsersPresenter { private weak var viewController : CMAccessForExistingUsersViewController! private let viewModelLocator : ViewModelLocator private init(viewModelLocator: ViewModelLocator) { self.viewModelLocator = viewModelLocator } static func create(with viewModelLocator: ViewModelLocator) -> CMAccessForExistingUsersViewController { let presenter = CMAccessForExistingUsersPresenter(viewModelLocator: viewModelLocator) let viewController = StoryboardScene.Main.cmAccessForExistingUsers.instantiate() let viewModel = viewModelLocator.getCMAccessForExistingUsersViewModel() viewController.inject(presenter: presenter, viewModel: viewModel) presenter.viewController = viewController return viewController } func dismiss() { viewController.dismiss(animated: true) } }
bsd-3-clause
095216e67a13af53994c75bad50569ba
30.193548
105
0.723888
6.361842
false
false
false
false
leonereveel/Moya
Source/RxSwift/Moya+RxSwift.swift
1
3082
import Foundation import RxSwift /// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures. public class RxMoyaProvider<Target where Target: TargetType>: MoyaProvider<Target> { /// Initializes a reactive provider. override public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = RxMoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = [], trackInflights: Bool = false) { super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights) } /// Designated request-making method. public func request(token: Target) -> Observable<Response> { // Creates an observable that starts a request each time it's subscribed to. return Observable.create { [weak self] observer in let cancellableToken = self?.request(token) { result in switch result { case let .Success(response): observer.onNext(response) observer.onCompleted() case let .Failure(error): observer.onError(error) } } return AnonymousDisposable { cancellableToken?.cancel() } } } } public extension RxMoyaProvider { public func requestWithProgress(token: Target) -> Observable<ProgressResponse> { let progressBlock = { (observer: AnyObserver) -> (ProgressResponse) -> Void in return { (progress: ProgressResponse) in observer.onNext(progress) } } let response: Observable<ProgressResponse> = Observable.create { [weak self] observer in let cancellableToken = self?.request(token, queue: nil, progress: progressBlock(observer)) { result in switch result { case let .Success(response): observer.onNext(ProgressResponse(response: response)) observer.onCompleted() case let .Failure(error): observer.onError(error) } } return AnonymousDisposable { cancellableToken?.cancel() } } // Accumulate all progress and combine them when the result comes return response.scan(ProgressResponse()) { (last, progress) in let totalBytes = progress.totalBytes > 0 ? progress.totalBytes : last.totalBytes let bytesExpected = progress.bytesExpected > 0 ? progress.bytesExpected : last.bytesExpected let response = progress.response ?? last.response return ProgressResponse(totalBytes: totalBytes, bytesExpected: bytesExpected, response: response) } } }
mit
3c0c555eea9b28e3397a726958475e10
43.028571
182
0.632057
5.892925
false
false
false
false
lancy/CaesarParser
CaesarParser/JSONSerialization.swift
1
3265
// // JSONSerialization.swift // Caesar // // Created by lancy on 5/17/15. // Copyright (c) 2015 Chenyu Lan. All rights reserved. // import Foundation // MARK: - Protocol /// convert to JSON object public protocol JSONSerializable { func toJSONObject() -> JSONObject } // MARK: - Serialization struct Serialization { // MARK: - General Type Serialization static func convertAndAssign<T: JSONSerializable>(property: T?, inout toJSONObject jsonObject: JSONObject?) -> JSONObject? { if let property = property { jsonObject = property.toJSONObject() } return jsonObject } // MARK: - Array Serialization static func convertAndAssign<T: JSONSerializable>(properties: [T]?, inout toJSONObject jsonObject: JSONObject?) -> JSONObject? { if let properties = properties { jsonObject = properties.map { p in p.toJSONObject() } } return jsonObject } // MARK: - Map Serialization static func convertAndAssign<T, U where T: JSONSerializable, U: CustomStringConvertible, U: Hashable>(map: [U: T]?, inout toJSONObject jsonObject: JSONObject?) -> JSONObject? { if let jsonMap = map { var json = JSONDictionary() for (key, value) in jsonMap { json[key.description] = value.toJSONObject() } jsonObject = json } return jsonObject } // MARK: - Raw Representable (Enum) Serialization static func convertAndAssign<T: RawRepresentable where T.RawValue: JSONSerializable>(property: T?, inout toJSONObject value: JSONObject?) -> JSONObject? { if let jsonValue: JSONObject = property?.rawValue.toJSONObject() { value = jsonValue } return value } static func convertAndAssign<T: RawRepresentable where T.RawValue: JSONSerializable>(properties: [T]?, inout toJSONObject jsonObject: JSONObject?) -> JSONObject? { if let properties = properties { jsonObject = properties.map { p in p.rawValue.toJSONObject() } } return jsonObject } } // MARK: - Operator for use in serialization operations. infix operator --> { associativity right precedence 150 } public func --> <T: JSONSerializable>(property: T?, inout jsonObject: JSONObject?) -> JSONObject? { return Serialization.convertAndAssign(property, toJSONObject: &jsonObject) } public func --> <T: JSONSerializable>(properties: [T]?, inout jsonObject: JSONObject?) -> JSONObject? { return Serialization.convertAndAssign(properties, toJSONObject: &jsonObject) } public func --> <T, U where T: JSONSerializable, U: CustomStringConvertible, U: Hashable>(map: [U: T]?, inout jsonObject: JSONObject?) -> JSONObject? { return Serialization.convertAndAssign(map, toJSONObject: &jsonObject) } public func --> <T: RawRepresentable where T.RawValue: JSONSerializable>(property: T?, inout jsonObject: JSONObject?) -> JSONObject? { return Serialization.convertAndAssign(property, toJSONObject: &jsonObject) } public func --> <T: RawRepresentable where T.RawValue: JSONSerializable>(property: [T]?, inout jsonObject: JSONObject?) -> JSONObject? { return Serialization.convertAndAssign(property, toJSONObject: &jsonObject) }
mit
c938f49955a2aa6d21685933ad683c41
34.107527
180
0.679939
4.773392
false
false
false
false
taku33/FolioReaderPlus
Source/EPUBCore/FRMediaType.swift
1
4457
// // FRMediaType.swift // FolioReaderKit // // Created by Heberti Almeida on 29/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit /** MediaType is used to tell the type of content a resource is. Examples of mediatypes are image/gif, text/css and application/xhtml+xml */ struct MediaType { var name: String var defaultExtension: String! var extensions: [String]! init(name: String, defaultExtension: String) { self.name = name self.defaultExtension = defaultExtension self.extensions = [defaultExtension] } init(name: String, defaultExtension: String, extensions: [String]) { self.name = name self.defaultExtension = defaultExtension self.extensions = extensions } } // MARK: Equatable extension MediaType: Equatable {} /** Compare if two mediatypes are equal or different. */ func ==(lhs: MediaType, rhs: MediaType) -> Bool { return lhs.name == rhs.name && lhs.defaultExtension == rhs.defaultExtension } /** Manages mediatypes that are used by epubs. */ class FRMediaType: NSObject { static var XHTML = MediaType(name: "application/xhtml+xml", defaultExtension: ".xhtml", extensions: [".htm", ".html", ".xhtml", ".xml"]) static var EPUB = MediaType(name: "application/epub+zip", defaultExtension: ".epub") static var NCX = MediaType(name: "application/x-dtbncx+xml", defaultExtension: ".ncx") static var OPF = MediaType(name: "application/oebps-package+xml", defaultExtension: ".opf") static var JAVASCRIPT = MediaType(name: "text/javascript", defaultExtension: ".js") static var CSS = MediaType(name: "text/css", defaultExtension: ".css") // images static var JPG = MediaType(name: "image/jpeg", defaultExtension: ".jpg", extensions: [".jpg", ".jpeg"]) static var PNG = MediaType(name: "image/png", defaultExtension: ".png") static var GIF = MediaType(name: "image/gif", defaultExtension: ".gif") static var SVG = MediaType(name: "image/svg+xml", defaultExtension: ".svg") // fonts static var TTF = MediaType(name: "application/x-font-ttf", defaultExtension: ".ttf") static var TTF1 = MediaType(name: "application/x-font-truetype", defaultExtension: ".ttf") static var TTF2 = MediaType(name: "application/x-truetype-font", defaultExtension: ".ttf") static var OPENTYPE = MediaType(name: "application/vnd.ms-opentype", defaultExtension: ".otf") static var WOFF = MediaType(name: "application/font-woff", defaultExtension: ".woff") // audio static var MP3 = MediaType(name: "audio/mpeg", defaultExtension: ".mp3") static var MP4 = MediaType(name: "audio/mp4", defaultExtension: ".mp4") static var OGG = MediaType(name: "audio/ogg", defaultExtension: ".ogg") static var SMIL = MediaType(name: "application/smil+xml", defaultExtension: ".smil") static var XPGT = MediaType(name: "application/adobe-page-template+xml", defaultExtension: ".xpgt") static var PLS = MediaType(name: "application/pls+xml", defaultExtension: ".pls") static var mediatypes = [XHTML, EPUB, NCX, OPF, JPG, PNG, GIF, CSS, SVG, TTF, TTF1, TTF2, OPENTYPE, WOFF, SMIL, XPGT, PLS, JAVASCRIPT, MP3, MP4, OGG] /** Gets the MediaType based on the file mimetype. - Parameters: - name: The mediaType name - filename: The file name to extract the extension - Returns: A know mediatype or create a new one. */ static func mediaTypeByName(name: String, fileName: String) -> MediaType { for mediatype in mediatypes { if mediatype.name == name { return mediatype } } let ext = "."+NSURL(string: fileName ?? "")!.pathExtension! return MediaType(name: name, defaultExtension: ext) } /** Compare if the resource is a image. - Returns: `true` if is a image and `false` if not */ static func isBitmapImage(mediaType: MediaType) -> Bool { return mediaType == JPG || mediaType == PNG || mediaType == GIF } /** Gets the MediaType based on the file extension. */ static func determineMediaType(fileName: String) -> MediaType? { for mediatype in mediatypes { let ext = "."+(fileName as NSString).pathExtension if mediatype.extensions.contains(ext) { return mediatype } } return nil } }
bsd-3-clause
dc003d865efada374f99ec906e523769
35.235772
153
0.652681
3.937279
false
false
false
false
Instagram/IGListKit
Examples/Examples-iOS/IGListKitExamples/Views/FullWidthSelfSizingCell.swift
1
2753
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import UIKit final class FullWidthSelfSizingCell: UICollectionViewCell { private let label: UILabel = { let label = UILabel() label.backgroundColor = UIColor.red.withAlphaComponent(0.1) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() var text: String? { get { return label.text } set { label.text = newValue } } override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = UIColor.background contentView.addSubview(label) NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 15).isActive = true NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 15).isActive = true NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1, constant: 15).isActive = true NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: 15).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { setNeedsLayout() layoutIfNeeded() let size = contentView.systemLayoutSizeFitting(layoutAttributes.size) var newFrame = layoutAttributes.frame // note: don't change the width newFrame.size.height = ceil(size.height) layoutAttributes.frame = newFrame return layoutAttributes } }
mit
a451302a127fa864778440ca9070a3ed
33.848101
142
0.522703
6.214447
false
false
false
false
fulldecent/formant-analyzer
Formant Analyzer/Formant Analyzer/ViewController.swift
1
17457
// // ViewController.swift // FormantPlotter // // Created by William Entriken on 1/21/16. // Copyright © 2016 William Entriken. All rights reserved. // import UIKit import AVKit import AVFoundation import FSLineChart import FDSoundActivatedRecorder import SafariServices enum GraphingMode: Int { case signal case lpc case frequencyResponse case formant } class FirstViewController: UIViewController { // Top row @IBOutlet var indicatorImageView: UIImageView! @IBOutlet var statusLabel: UILabel! @IBOutlet weak var inputSelector: UIButton! // Second row @IBOutlet var graphingMode: UISegmentedControl! // Third row @IBOutlet var formantPlot: FormantPlotView! @IBOutlet var lineChartTopHalf: FSLineChart! @IBOutlet var lineChartBottomHalf: FSLineChart! @IBOutlet var lineChartFull: FSLineChart! // Fourth row @IBOutlet var firstFormantLabel: UILabel! @IBOutlet var secondFormantLabel: UILabel! @IBOutlet var thirdFormantLabel: UILabel! @IBOutlet var fourthFormantLabel: UILabel! var displayIdentifier: GraphingMode = .signal lazy var soundActivatedRecorder: FDSoundActivatedRecorder = { let retval = FDSoundActivatedRecorder() retval.delegate = self return retval }() /// Whether we are processing live speech or stored samples. var speechIsFromMicrophone = true /// Which stored file (1 out of 7) is being processed var soundFileIdentifier = 0 /// Array of names of 7 stored sound files. var soundFileBaseNames = ["arm", "beat", "bid", "calm", "cat", "four", "who"] var speechAnalyzer = SpeechAnalyzer(int16Samples: Data(), withFrequency: 44100) var speechData = Data() func showPlotForDisplayIdentifier(_ displayIdentifier: GraphingMode, withAnalyzer analyzer: SpeechAnalyzer) { self.formantPlot.isHidden = true self.lineChartTopHalf.isHidden = true self.lineChartBottomHalf.isHidden = true self.lineChartFull.isHidden = true switch displayIdentifier { case .signal: self.drawSignalPlot() self.lineChartTopHalf.isHidden = false self.lineChartBottomHalf.isHidden = false case .lpc: self.drawLPCPlot() self.lineChartFull.isHidden = false case .frequencyResponse: self.drawHwPlot() self.lineChartFull.isHidden = false case .formant: self.formantPlot.formants = self.speechAnalyzer.formants self.formantPlot.setNeedsDisplay() self.formantPlot.isHidden = false } } //TODO: Should be a separate view class func drawSignalPlot() { guard speechAnalyzer.samples.count > 0 else { return } let plottableValuesHigh: [Double] = self.speechAnalyzer.downsampleToSamples(400).map{max(0,Double($0))} let plottableValuesLow: [Double] = plottableValuesHigh.map({-$0}) self.lineChartTopHalf.drawInnerGrid = false self.lineChartTopHalf.axisLineWidth = 0 self.lineChartTopHalf.margin = 0 self.lineChartTopHalf.axisWidth = self.lineChartTopHalf.frame.size.width self.lineChartTopHalf.axisHeight = self.lineChartTopHalf.frame.size.height self.lineChartTopHalf.backgroundColor = UIColor.clear self.lineChartTopHalf.fillColor = UIColor.blue self.lineChartTopHalf.clearData() self.lineChartTopHalf.setChartData(plottableValuesHigh) self.lineChartBottomHalf.drawInnerGrid = false self.lineChartBottomHalf.axisLineWidth = 0 self.lineChartBottomHalf.margin = 0 self.lineChartBottomHalf.axisWidth = self.lineChartTopHalf.frame.size.width self.lineChartBottomHalf.axisHeight = self.lineChartTopHalf.frame.size.height self.lineChartBottomHalf.backgroundColor = UIColor.clear self.lineChartBottomHalf.fillColor = UIColor.blue self.lineChartBottomHalf.clearData() self.lineChartBottomHalf.setChartData(plottableValuesLow) self.lineChartTopHalf.subviews.forEach({$0.removeFromSuperview()}) self.lineChartBottomHalf.subviews.forEach({$0.removeFromSuperview()}) let strongRect = CGRect( x: CGFloat(self.lineChartTopHalf.frame.size.width) * CGFloat(self.speechAnalyzer.strongPart.first!) / CGFloat(self.speechAnalyzer.samples.count), y: 0, width: CGFloat(self.lineChartTopHalf.frame.size.width) * CGFloat(self.speechAnalyzer.strongPart.count) / CGFloat(self.speechAnalyzer.samples.count), height: self.lineChartTopHalf.frame.size.height * 2) let strongBox = UIView(frame: strongRect) strongBox.backgroundColor = UIColor(hue: 60.0/255.0, saturation: 180.0/255.0, brightness: 92.0/255.0, alpha: 0.2) self.lineChartTopHalf.insertSubview(strongBox, at: 0) let vowelRect = CGRect( x: CGFloat(self.lineChartTopHalf.frame.size.width) * CGFloat(self.speechAnalyzer.vowelPart.first!) / CGFloat(self.speechAnalyzer.samples.count), y: self.lineChartTopHalf.frame.size.height * 0.05, width: CGFloat(self.lineChartTopHalf.frame.size.width) * CGFloat(self.speechAnalyzer.vowelPart.count) / CGFloat(self.speechAnalyzer.samples.count), height: self.lineChartTopHalf.frame.size.height * 1.9) let vowelBox = UIView(frame: vowelRect) vowelBox.backgroundColor = UIColor(hue: 130.0/255.0, saturation: 180.0/255.0, brightness: 92.0/255.0, alpha: 0.2) self.lineChartTopHalf.insertSubview(vowelBox, at: 0) } //TODO: Should be a separate view class func drawLPCPlot() { // Index label properties self.lineChartFull.labelForIndex = { (item: UInt) -> String in return "\(Int(item))" } // Value label properties self.lineChartFull.labelForValue = { (value: CGFloat) -> String in return String(format: "%.02f", value) } self.lineChartFull.valueLabelPosition = .left // Number of visible step in the chart self.lineChartFull.verticalGridStep = 3 self.lineChartFull.horizontalGridStep = 20 // Margin of the chart self.lineChartFull.margin = 40 self.lineChartFull.axisWidth = self.lineChartFull.frame.size.width - 2 * self.lineChartFull.margin self.lineChartFull.axisHeight = self.lineChartFull.frame.size.height - 2 * self.lineChartFull.margin // Decoration parameters, let you pick the color of the line as well as the color of the axis self.lineChartFull.axisLineWidth = 1 // Chart parameters self.lineChartFull.color = UIColor.black self.lineChartFull.fillColor = UIColor.blue self.lineChartFull.backgroundColor = UIColor.clear // Grid parameters self.lineChartFull.drawInnerGrid = true let lpcCoefficients: [Double] = self.speechAnalyzer.estimatedLpcCoefficients self.lineChartFull.clearData() self.lineChartFull.setChartData(lpcCoefficients) } //TODO: Should be a separate view class func drawHwPlot() { // Index label properties self.lineChartFull.labelForIndex = { (item: UInt) -> String in return String(format: "%.0f kHz", Double(item) / 60) } // Value label properties self.lineChartFull.labelForValue = { (value: CGFloat) -> String in return String(format: "%.02f", value) } self.lineChartFull.valueLabelPosition = .left // Number of visible steps in the chart self.lineChartFull.verticalGridStep = 3 self.lineChartFull.horizontalGridStep = 5 // Margin of the chart self.lineChartFull.margin = 40 self.lineChartFull.axisWidth = self.lineChartFull.frame.size.width - 2 * self.lineChartFull.margin self.lineChartFull.axisHeight = self.lineChartFull.frame.size.height - 2 * self.lineChartFull.margin // Decoration parameters, let you pick the color of the line as well as the color of the axis self.lineChartFull.axisLineWidth = 1 // Chart parameters self.lineChartFull.color = UIColor.black self.lineChartFull.fillColor = UIColor.blue self.lineChartFull.backgroundColor = UIColor.clear // Grid parameters self.lineChartFull.drawInnerGrid = true let synthesizedFrequencyResponse: [Double] = self.speechAnalyzer.synthesizedFrequencyResponse self.lineChartFull.clearData() self.lineChartFull.setChartData(synthesizedFrequencyResponse) } @IBAction func graphingModeChanged(_ sender: UISegmentedControl) { self.displayIdentifier = GraphingMode(rawValue: sender.selectedSegmentIndex)! self.showPlotForDisplayIdentifier(self.displayIdentifier, withAnalyzer: self.speechAnalyzer) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext) -> Void in self.showPlotForDisplayIdentifier(self.displayIdentifier, withAnalyzer: self.speechAnalyzer) }, completion: {(context: UIViewControllerTransitionCoordinatorContext) -> Void in }) super.viewWillTransition(to: size, with: coordinator) } func displayFormantFrequencies() { let formants: [Double] = self.speechAnalyzer.formants let firstFLabel = String(format: "Formant 1:%5.0f", formants[0]) self.firstFormantLabel.text = firstFLabel let secondFLabel = String(format: "Formant 2:%5.0f", formants[1]) self.secondFormantLabel.text = secondFLabel let thirdFLabel = String(format: "Formant 3:%5.0f", formants[2]) self.thirdFormantLabel.text = thirdFLabel let fourthFLabel = String(format: "Formant 4:%5.0f", formants[3]) self.fourthFormantLabel.text = fourthFLabel } func processRawBuffer() { let fileURL = Bundle.main.url(forResource: self.soundFileBaseNames[self.soundFileIdentifier], withExtension: "raw")! NSLog("Processing saved file %@", self.soundFileBaseNames[self.soundFileIdentifier]) speechData = try! Data(contentsOf: fileURL) self.speechAnalyzer = SpeechAnalyzer(int16Samples: speechData, withFrequency: 44100) displayFormantFrequencies() self.showPlotForDisplayIdentifier(self.displayIdentifier, withAnalyzer: self.speechAnalyzer) } /// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. override func viewDidLoad() { super.viewDidLoad() self.indicatorImageView.image = UIImage(named: "green_light.png") self.inputSelector.setTitle("Microphone", for: UIControl.State()) self.speechIsFromMicrophone = true self.indicatorImageView.isHidden = false self.statusLabel.text = "Listening ..." _ = try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: AVAudioSession.Mode.default) self.soundActivatedRecorder.startListening() } @IBAction func showHelp() { let url = URL(string: "https://fulldecent.github.io/formant-analyzer/")! if #available(iOS 9.0, *) { let svc = SFSafariViewController(url: url, entersReaderIfAvailable: true) svc.delegate = self self.present(svc, animated: true, completion: nil) } else { UIApplication.shared.openURL(url) } } @IBAction func showInputSelectSheet(_ sender: UIButton) { let alert: UIAlertController = UIAlertController(title: "Audio source", message: "Select the audio soucre to analyze", preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Microphone", style: .default, handler: { (action: UIAlertAction) -> Void in self.inputSelector.setTitle("Microphone", for: UIControl.State()) self.speechIsFromMicrophone = true self.indicatorImageView.isHidden = false self.statusLabel.text = "Waiting ..." self.soundActivatedRecorder.startListening() })) for basename: String in self.soundFileBaseNames { alert.addAction(UIAlertAction(title: basename, style: .default, handler: { (action: UIAlertAction) -> Void in self.soundActivatedRecorder.abort() self.inputSelector.setTitle("File", for: UIControl.State()) self.speechIsFromMicrophone = false self.indicatorImageView.isHidden = true self.soundFileIdentifier = self.soundFileBaseNames.firstIndex(of: basename)! self.statusLabel.text = self.soundFileBaseNames[self.soundFileIdentifier] self.processRawBuffer() })) } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } /// Get raw PCM data from the track func readSoundFileSamples(_ assetURL: URL) -> Data { let retval = NSMutableData() let asset = AVURLAsset(url: assetURL) let track = asset.tracks[0] let reader = try! AVAssetReader(asset: asset) let settings: [String: NSNumber] = [ AVFormatIDKey: NSNumber(integerLiteral: Int(kAudioFormatLinearPCM)), AVSampleRateKey: 16000.0, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsNonInterleaved: 0, AVLinearPCMIsFloatKey: 0, AVLinearPCMIsBigEndianKey: 0 ] let output = AVAssetReaderTrackOutput(track: track, outputSettings: settings) reader.add(output) reader.startReading() // read the samples from the asset and append them subsequently while reader.status != .completed { guard let buffer = output.copyNextSampleBuffer() else { continue } let blockBuffer = CMSampleBufferGetDataBuffer(buffer)! let size = CMBlockBufferGetDataLength(blockBuffer) let outBytes = NSMutableData(length: size)! CMBlockBufferCopyDataBytes(blockBuffer, atOffset: 0, dataLength: size, destination: outBytes.mutableBytes) CMSampleBufferInvalidate(buffer) retval.append(outBytes as Data) } return retval as Data } } extension FirstViewController: FDSoundActivatedRecorderDelegate { /// A recording was successfully captured public func soundActivatedRecorderDidFinishRecording(recorder: FDSoundActivatedRecorder, andSaved file: NSURL) { } func soundActivatedRecorderDidStartRecording(_ recorder: FDSoundActivatedRecorder) { DispatchQueue.main.async(execute: { NSLog("STARTED RECORDING") self.indicatorImageView.image = UIImage(named: "blue_light.png") self.statusLabel.text = "Capturing sound" }) } func soundActivatedRecorderDidFinishRecording(_ recorder: FDSoundActivatedRecorder, andSaved file: URL) { DispatchQueue.main.async(execute: { NSLog("STOPPED RECORDING") self.indicatorImageView.image = UIImage(named: "red_light.png") self.statusLabel.text = "Processing sound" self.speechData = self.readSoundFileSamples(file) self.speechAnalyzer = SpeechAnalyzer(int16Samples: self.speechData, withFrequency: 44100) self.displayFormantFrequencies() self.showPlotForDisplayIdentifier(self.displayIdentifier, withAnalyzer: self.speechAnalyzer) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(NSEC_PER_SEC) / 2) / Double(NSEC_PER_SEC), execute: { self.indicatorImageView.image = UIImage(named: "green_light.png") self.statusLabel.text = "Listening ..." self.soundActivatedRecorder.startListening() }) }) } func soundActivatedRecorderDidAbort(_ recorder: FDSoundActivatedRecorder) { DispatchQueue.main.async(execute: { NSLog("STOPPED RECORDING") self.indicatorImageView.image = UIImage(named: "red_light.png") self.statusLabel.text = "Retrying ..." if self.speechIsFromMicrophone { self.soundActivatedRecorder.startListening() } }) } func soundActivatedRecorderDidTimeOut(_ recorder: FDSoundActivatedRecorder) { DispatchQueue.main.async(execute: { NSLog("STOPPED RECORDING") self.indicatorImageView.image = UIImage(named: "red_light.png") self.statusLabel.text = "Retrying ..." if self.speechIsFromMicrophone { self.soundActivatedRecorder.startListening() } }) } } @available(iOS 9.0, *) extension FirstViewController: SFSafariViewControllerDelegate { func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true, completion: nil) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String { return input.rawValue }
mit
de77209c85ab15b13e803e4dbecbdbfd
44.696335
160
0.673751
4.560084
false
false
false
false
fakerabbit/memoria
Memoria/NotificationDelegate.swift
1
2410
// // NotificationDelegate.swift // Memoria // // Created by Mirko Justiniano on 3/9/17. // Copyright © 2017 MM. All rights reserved. // import Foundation import UIKit import UserNotifications class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate { // MARK:- Foreground App func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // Play sound and show alert to the user completionHandler([.alert,.sound]) } // MARK:- Action in delivered notification func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { UIApplication.shared.applicationIconBadgeNumber = 0 let userInfo = response.notification.request.content.userInfo // Determine the user action switch response.actionIdentifier { case UNNotificationDismissActionIdentifier: print("Dismiss Action") case UNNotificationDefaultActionIdentifier: practice(with: userInfo["cardId"] as! String) case "Snooze": let newDate = Date(timeInterval: 60, since: Date()) scheduleNotification(at: newDate, for: userInfo["cardId"] as! String) case "Practice": practice(with: userInfo["cardId"] as! String) default: practice(with: userInfo["cardId"] as! String) } completionHandler() } func scheduleNotification(at date: Date,for cardId: String) { DataMgr.sharedInstance.fetchCard(for: cardId) { card in if card != nil { DataMgr.sharedInstance.programCard(card: card!, difficulty: Difficulty.easy.rawValue) } } } func practice(with cardId: String) { DataMgr.sharedInstance.fetchCard(for: cardId) { card in let application = UIApplication.shared.delegate as! AppDelegate if card != nil { application.nav.startTest(for: card!) } } } }
mit
27c659df4462385b5727ae3d2de13b7b
34.426471
129
0.609797
5.790865
false
false
false
false
Matzo/Kamishibai
Kamishibai/Classes/KamishibaiFocusViewController.swift
1
7397
// // KamishibaiFocusViewController.swift // Hello // // Created by Keisuke Matsuo on 2017/08/12. // // import UIKit public enum FocusAccesoryViewPosition { case topRight(CGPoint) case bottomRight(CGPoint) case center(CGPoint) case point(CGPoint) } public class KamishibaiFocusViewController: UIViewController { // MARK: Properties let focusView = KamishibaiFocusView(frame: CGRect.zero) var customViews = [UIView]() let transitioning = KamishibaiFocusTransitioning(state: .presenting) weak var kamishibai: Kamishibai? public var isFocusing: Bool { return self.view.superview != nil } // MARK: UIViewController Lifecycle override public func viewDidLoad() { super.viewDidLoad() setupViews() } var first = true override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() focusView.frame = view.bounds } // MARK: Initializing func setupViews() { view.addSubview(focusView) view.backgroundColor = UIColor.clear // view.isUserInteractionEnabled = false } // MARK: Public Methods public func on(view: UIView? = nil, focus: FocusType, completion: (() -> Void)? = nil) { guard let targetView = view ?? kamishibai?.currentViewController?.view else { return } let focusBlock = { if let _ = self.focusView.focus { self.focusView.move(to: focus, completion: completion) } else { self.focusView.appear(focus: focus, completion: completion) } } if self.view.superview == nil { present(onView: targetView, completion: { focusBlock() }) } else { focusBlock() } } override public func dismiss(animated flag: Bool, completion: (() -> Swift.Void)? = nil) { hideAllCustomViews() let duration = isFocusing ? focusView.animationDuration : 0 UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveLinear, animations: { self.view.alpha = 0 }) { (_) in self.view.alpha = 1 self.view.removeFromSuperview() self.clean() completion?() } } public func addCustomView(view: UIView, position: FocusAccesoryViewPosition, completion: @escaping () -> Void = {}) { self.customViews.append(view) self.view.addSubview(view) view.sizeToFit() switch position { case .topRight(let adjust): view.frame.origin.x = self.view.bounds.size.width - view.frame.size.width + adjust.x if let focus = focusView.focus { view.frame.origin.y = focus.frame.minY - view.frame.size.height + adjust.y } case .bottomRight(let adjust): view.frame.origin.x = self.view.bounds.size.width - view.frame.size.width + adjust.x if let focus = focusView.focus { view.frame.origin.y = focus.frame.maxY + adjust.y } case .center(let adjust): if let focus = focusView.focus { view.center = CGPoint(x: focus.frame.midX + adjust.x, y: focus.frame.midY + adjust.y) } else { view.center = CGPoint(x: self.view.frame.midX + adjust.x, y: self.view.frame.midY + adjust.y) } case .point(let point): view.frame.origin = point } if let animate = view as? KamishibaiCustomViewAnimation { animate.show(animated: true, fulfill: completion) } } public func hideAllCustomViews() { customViews.forEach { (view) in if let animate = view as? KamishibaiCustomViewAnimation { animate.hide(animated: true, fulfill: {}) } } } public func clean() { customViews.forEach { (view) in view.removeFromSuperview() } customViews.removeAll() focusView.disappear() focusView.maskLayer.path = nil } // MARK: Private Methods func present(onView view: UIView, completion: (() -> Void)? = nil) { focusView.focus = nil view.addSubview(self.view) completion?() } // MARK: Class Methods static func create() -> KamishibaiFocusViewController { let vc = KamishibaiFocusViewController() vc.transitioningDelegate = vc vc.modalPresentationStyle = .overCurrentContext return vc } } // MARK: - Transitioning extension KamishibaiFocusViewController: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transitioning.state = .presenting return transitioning } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transitioning.state = .dismissing return transitioning } } enum KamishibaiFocusTransitioningState { case presenting case dismissing } class KamishibaiFocusTransitioning: NSObject, UIViewControllerAnimatedTransitioning { var state: KamishibaiFocusTransitioningState init(state: KamishibaiFocusTransitioningState) { self.state = state } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { switch self.state { case .presenting: return 0.5 case .dismissing: return 0.5 } } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return } guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return } let duration = self.transitionDuration(using: transitionContext) let containerView = transitionContext.containerView switch self.state { case .presenting: containerView.addSubview(toVC.view) toVC.view.alpha = 0 UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [.beginFromCurrentState], animations: { () -> Void in toVC.view.alpha = 1 }, completion: { (done) -> Void in transitionContext.completeTransition(true) }) case .dismissing: containerView.addSubview(fromVC.view) if fromVC.modalPresentationStyle != .overCurrentContext { containerView.insertSubview(toVC.view, at: 0) } fromVC.view.alpha = 1 UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [.beginFromCurrentState], animations: { () -> Void in fromVC.view.alpha = 0 }, completion: { (done) -> Void in transitionContext.completeTransition(true) }) } } }
mit
5fe2604ec77736f8e4fcd8cdc48fc13d
33.565421
126
0.6189
5.097864
false
false
false
false
withcopper/CopperKit
CopperKit/CopperPictureRecord.swift
1
4483
// // CopperPictureRecord.swift // CopperRecordObject Representation of a avatar // // Created by Doug Williams on 6/2/14. // Copyright (c) 2014 Doug Williams. All rights reserved. // import UIKit public class CopperPictureRecord: CopperRecordObject, CopperPicture { // We do this level of indirection because the JSON parser doesn't know how to deal with UIImage objects // So we manage to make it work with this little rodeo. You should call and set avatar, and we'll manage the data dictionary stuff // for writing out to the API. public var image: UIImage? { didSet { if self.image == nil { self.picture = nil } else { self.picture = UIImagePNGRepresentation(self.image!) } } } // This is broken -- we have to methods to access avatar // but there is a bug where accessing picture when casting from a CopperRecordObject returns a bad_access error // eg (record as? CopperAvatarRecord).picture so we need this method instead public func getPicture() -> UIImage? { if let picture = self.picture { return UIImage(data: picture)! } return UIImage?() } public var url: String? { get { if let url = data[ScopeDataKeys.PictureURL.rawValue] as? String { return url } return nil } set { if let new = newValue { self.data[ScopeDataKeys.PictureURL.rawValue] = new } else { self.data.removeValueForKey(ScopeDataKeys.PictureURL.rawValue) } self.uploaded = false } } // You shouldn't be calling this directly. This handles serializing the photo data into and out of a JSON acceptable format private var picture: NSData? { get { if let base64Encoded = self.data[ScopeDataKeys.PictureImage.rawValue] as? String { if let decoded = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions(rawValue: 0)) { return decoded } } return NSData?() } set { if let new = newValue?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) { self.data[ScopeDataKeys.PictureImage.rawValue] = new } else { self.data.removeValueForKey(ScopeDataKeys.PictureURL.rawValue) } self.uploaded = false } } // Note: avatar didSet must fire to set picture, // which doesnt appear to happen when you set avatar in the init() function // so i removed it from the paramter set to ensure no hard to track down bugs occur // SO: set avatar after init public convenience init(image: UIImage! = nil, id: String = "current", verified: Bool = false) { self.init(scope: C29Scope.Picture, data: nil, id: id, verified: verified) self.image = image } public override var valid: Bool { return picture != nil } override func rehydrateDataIfNeeded(session: C29SessionDataSource?, completion: ((record: CopperRecordObject?) -> ())!) { // create a temporary image cache in case we need one var imageCache = C29ImageCache() var cacheOnDownload = false // if we did get a session object, then let's atempt to use it's cache for optimization if let sessionImageCache = session?.imageCache { imageCache = sessionImageCache cacheOnDownload = true } if let url = url { imageCache.getImage(url, cacheOnDownload: cacheOnDownload, callback: { (image: UIImage?) in self.image = image completion(record: self) }) } else { completion(record: self) } } public class func getAvatarRecordForInitials(initials: String, session: C29SessionDataSource! = nil) -> CopperPicture { let record = CopperPictureRecord() record.url = "https://bytes.withcopper.com/default/\(initials.uppercaseString).png" record.rehydrateDataIfNeeded(session, completion: { record in // no op }) return record } } func ==(lhs: CopperPictureRecord, rhs: CopperPictureRecord) -> Bool { if lhs.id == rhs.id { return true } return lhs.picture == rhs.picture }
mit
cae19bfea8d58b85c7994c6067126029
36.366667
134
0.60919
4.655244
false
false
false
false
Incipia/IncSpinner
IncSpinner/Classes/IncSpinner+Extensions.swift
1
2503
// // IncSpinner+Extensions.swift // Pods // // Created by Gregory Klein on 11/7/16. // // import Foundation extension UILabel { convenience init(incSpinnerText text: String, font: UIFont? = nil) { self.init() self.text = text self.font = font ?? UIFont.boldSystemFont(ofSize: 26) textAlignment = .center numberOfLines = 0 } convenience init(tapToDismissText text: String, fontName: String? = nil) { self.init() self.text = text var font: UIFont? = UIFont.systemFont(ofSize: 20) if let fontName = fontName { font = UIFont(name: fontName, size: 16) } self.font = font textAlignment = .center numberOfLines = 0 } } extension DispatchQueue { func incSpinner_delay(_ seconds: Double, completion: @escaping () -> Void) { let popTime = DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * seconds)) / Double(NSEC_PER_SEC) asyncAfter(deadline: popTime) { completion() } } } extension UIView { func incSpinner_addAndFill(subview: UIView) { addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = false subview.topAnchor.constraint(equalTo: topAnchor).isActive = true subview.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true subview.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true subview.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true } } extension CABasicAnimation { static var incSpinner_scale: CABasicAnimation { let scaleAnim = CABasicAnimation(keyPath: "transform.scale") scaleAnim.fromValue = 0 scaleAnim.toValue = 1 scaleAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return scaleAnim } static var incSpinner_fadeIn: CABasicAnimation { let alphaAnim = CABasicAnimation(keyPath: "opacity") alphaAnim.toValue = NSNumber(value: 1.0) alphaAnim.fromValue = NSNumber(value: 0.0) alphaAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return alphaAnim } static var incSpinner_fadeOut: CABasicAnimation { let alphaAnim = CABasicAnimation(keyPath: "opacity") alphaAnim.toValue = NSNumber(value: 0.0) alphaAnim.fromValue = NSNumber(value: 1.0) alphaAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return alphaAnim } }
mit
de430dfbd50da956c169d65a9745b028
31.089744
109
0.691171
4.69606
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
WikipediaSearch/WikipediaSearch/Common/UIDevice+Extension.swift
1
1178
// // UIDevice+Extension.swift // WikipediaSearch // // Created by Anirudh Das on 8/12/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation import UIKit public extension UIDevice { public var iPhoneX: Bool { return UIScreen.main.nativeBounds.height == 2436 } public enum ScreenType: String { case iPhone4_4S = "iPhone 4 or iPhone 4S" case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE" case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6S, iPhone 7 or iPhone 8" case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus or iPhone 8 Plus" case iPhoneX = "iPhone X" case unknown } public var screenType: ScreenType { switch UIScreen.main.nativeBounds.height { case 960: return .iPhone4_4S case 1136: return .iPhones_5_5s_5c_SE case 1334: return .iPhones_6_6s_7_8 case 1920, 2208: return .iPhones_6Plus_6sPlus_7Plus_8Plus case 2436: return .iPhoneX default: return .unknown } } }
apache-2.0
fd95b6134ef75eea9302e8a8da202d7e
27.02381
111
0.59898
3.621538
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Chapters/Document10.playgroundchapter/Pages/Challenge3.playgroundpage/Sources/SetUp.swift
1
3699
// // SetUp.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import Foundation // MARK: Globals //public let world = GridWorld(columns: 5, rows: 7) public let world = loadGridWorld(named: "10.5") let actor = Actor() var gemRandomizer: RandomizedQueueObserver? public let randomNumberOfGems = Int(arc4random_uniform(8)) + 1 public var pinkPortal = Portal(color: .pink) public var bluePortal = Portal(color: .blue) public var gemsPlaced = 0 let gemCoords = [ Coordinate(column: 0, row: 1), Coordinate(column: 0, row: 2), Coordinate(column: 0, row: 4), Coordinate(column: 0, row: 5), Coordinate(column: 4, row: 1), Coordinate(column: 4, row: 2), Coordinate(column: 4, row: 4), Coordinate(column: 4, row: 5), Coordinate(column: 2, row: 1), Coordinate(column: 2, row: 3), Coordinate(column: 2, row: 5), ] public func playgroundPrologue() { placeRandomPlaceholders() placeActor() placePortals() // placeBlocks() // Must be called in `playgroundPrologue()` to update with the current page contents. registerAssessment(world, assessment: assessmentPoint) //// ---- // Any items added or removed after this call will be animated. finalizeWorldBuilding(for: world) { realizeRandomGems() } //// ---- placeGemsOverTime() } // Called from LiveView.swift to initially set the LiveView. public func presentWorld() { setUpLiveViewWith(world) } // MARK: Epilogue public func playgroundEpilogue() { sendCommands(for: world) } func placeActor() { world.place(actor, facing: south, at: Coordinate(column: 2, row: 3)) } func placePortals() { world.place(pinkPortal, between: Coordinate(column: 0, row: 3), and: Coordinate(column: 2, row: 2)) world.place(bluePortal, between: Coordinate(column: 4, row: 3), and: Coordinate(column: 2, row: 4)) } func placeBlocks() { let topBottomRows = world.coordinates(inRows:[6,0]) world.removeNodes(at: topBottomRows) world.placeWater(at: topBottomRows) world.placeBlocks(at: world.coordinates(inColumns: [0,4], intersectingRows: 1...5)) let obstacles = [ Coordinate(column: 1, row: 3), Coordinate(column: 1, row: 4), Coordinate(column: 1, row: 2), Coordinate(column: 3, row: 3), Coordinate(column: 3, row: 4), Coordinate(column: 3, row: 2), ] world.removeNodes(at: obstacles) world.placeWater(at: obstacles) } func placeRandomPlaceholders() { let gem = Gem() for coordinate in gemCoords { world.place(RandomNode(resembling: gem), at: coordinate) } } func realizeRandomGems() { for coordinate in gemCoords where gemsPlaced < randomNumberOfGems { let random = Int(arc4random_uniform(5)) if random % 2 == 0 { world.place(Gem(), at: coordinate) gemsPlaced += 1 } } } func placeGemsOverTime() { gemRandomizer = RandomizedQueueObserver(randomRange: 0...5, world: world) { world in let existingGemCount = world.existingGems(at: gemCoords).count guard existingGemCount < 5 && gemsPlaced < randomNumberOfGems else { return } for coordinate in Set(gemCoords) { if world.existingGems(at: [coordinate]).isEmpty { world.place(Gem(), at: coordinate) gemsPlaced += 1 return } } } }
mit
78a5b9d708fa34f8a04db4d37aa65272
26.4
103
0.594485
3.985991
false
false
false
false
nahive/spotify-notify
SpotifyNotify/Helpers/Extensions.swift
1
3280
// // Extensions.swift // SpotifyNotify // // Created by 先生 on 22/02/2018. // Copyright © 2018 Szymon Maślanka. All rights reserved. // import Cocoa extension NSButton { var isSelected: Bool { get { return state.rawValue == 1 } set { state = NSControl.StateValue(rawValue: newValue ? 1 : 0) } } } extension String { var url: URL? { return URL(string: self) } var cfString: CFString { return self as CFString } var withLeadingZeroes: String { guard let int = Int(self) else { return self } return String(format: "%02d", int) } } extension URL { var image: NSImage? { guard let data = try? Data(contentsOf: self) else { return nil } return NSImage(data: data) } func asyncImage(result: @escaping (NSImage?) -> Void) { URLSession.shared.dataTask(with: self) { (data, res, err) in guard let data = data, let image = NSImage(data: data) else { result(nil) return } result(image) }.resume() } } extension Data { var image: NSImage? { return NSImage(data: self) } } // private apple apis extension NSUserNotification { enum IdentityImageStyle: Int { case normal = 0 case rounded = 2 } var identityImage: NSImage? { get { return value(forKey: "_identityImage") as? NSImage } set { setValue(newValue, forKey: "_identityImage") } } var identityImageStyle: IdentityImageStyle { get { guard let value = value(forKey: "_identityImageStyle") as? Int, let style = IdentityImageStyle(rawValue: value) else { return .normal } return style } set { setValue(newValue.rawValue, forKey: "_identityImageStyle") } } } extension NSImage { /// Save an NSImage to a temporary directory /// /// - Parameter name: The file name, to use /// - Returns: A URL if saving is successful, or nil if there was an error func saveToTemporaryDirectory(withName name: String) -> URL? { guard let data = tiffRepresentation else { return nil } let fileManager = FileManager.default let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()) let bundleURL = tempURL.appendingPathComponent(AppConstants.bundleIdentifier, isDirectory: true) do { try fileManager.createDirectory(at: bundleURL, withIntermediateDirectories: true) let fileURL = bundleURL.appendingPathComponent(name + ".png") try NSBitmapImageRep(data: data)? .representation(using: .png, properties: [:])? .write(to: fileURL) return fileURL } catch { print("Error: " + error.localizedDescription) } return nil } } extension NSImage { /// Apply a circular mask to the image func applyCircularMask() -> NSImage { let image = NSImage(size: size) image.lockFocus() NSGraphicsContext.current?.imageInterpolation = .high let frame = NSRect(origin: .zero, size: size) NSBezierPath(ovalIn: frame).addClip() draw(at: .zero, from: frame, operation: .sourceOver, fraction: 1) image.unlockFocus() return image } }
unlicense
c68fa8eb0471d72e5233ee30ad5e2e8d
25.617886
104
0.612706
4.229974
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Managers/AnalyticsManager.swift
1
5424
// // AnalyticsManager.swift // Rocket.Chat // // Created by Filipe Alvarenga on 27/06/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation import Firebase import Crashlytics enum AnalyticsProvider { case fabric case firebase } enum Event { case showNewWorkspace case signup case login case updateStatus case replyNotification case openAdmin case directory(searchType: String, workspace: String) case screenView(screenName: String) case messageSent(subscriptionType: String, server: String) case mediaUpload(mediaType: String, subscriptionType: String) case reaction(subscriptionType: String) case serverSwitch(server: String, serverCount: Int) case updatedSubscriptionSorting(sorting: String, grouping: String) case updatedWebBrowser(browser: String) case updatedTheme(theme: String) case jitsiVideoCall(subscriptionType: String, server: String) case audioMessage(subscriptionType: String) } enum UserProperty { case server(server: String) var propertyName: String { switch self { case .server: return "Server" } } } struct AnalyticsManager { static func set(userProperty: UserProperty) { // Make sure the user has opted in for sending his usage data guard !AnalyticsCoordinator.isUsageDataLoggingDisabled else { return } switch userProperty { case let .server(server): Analytics.setUserProperty(server, forName: userProperty.propertyName) } } static func log(event: Event) { // Make sure the user has opted in for sending his usage data guard !AnalyticsCoordinator.isUsageDataLoggingDisabled else { return } // Don't log screen views when using firebase since it already logs them automatically if event.name() != Event.screenView(screenName: "").name() { Analytics.logEvent( event.name(for: .firebase), parameters: event.parameters(for: .firebase) ) } // Fabric has a specific method for logging login and sign up events if event.name() == Event.login.name() { Answers.logLogin( withMethod: nil, success: 1, customAttributes: event.parameters(for: .fabric) ) return } if event.name() == Event.signup.name() { Answers.logSignUp( withMethod: nil, success: 1, customAttributes: event.parameters(for: .fabric) ) return } Answers.logCustomEvent( withName: event.name(for: .fabric), customAttributes: event.parameters(for: .fabric) ) } } extension Event { // swiftlint:disable cyclomatic_complexity func name(for provider: AnalyticsProvider? = nil) -> String { switch self { case .signup: return provider == .firebase ? AnalyticsEventSignUp : "sign_up" case .login: return provider == .firebase ? AnalyticsEventLogin : "login" case .showNewWorkspace: return "show_new_workspace" case .updateStatus: return "status_update" case .replyNotification: return "reply_notification" case .openAdmin: return "open_admin" case .screenView: return "screen_view" case .messageSent: return "message_sent" case .mediaUpload: return "media_upload" case .reaction: return "reaction" case .directory: return "directory" case .serverSwitch: return "server_switch" case .updatedSubscriptionSorting: return "updated_subscriptions_sorting" case .updatedWebBrowser: return "updated_web_browser" case .updatedTheme: return "updated_theme" case .jitsiVideoCall: return "jitsi_video_call" case .audioMessage: return "audio_message" } } func parameters(for provider: AnalyticsProvider) -> [String: Any]? { switch self { case let .screenView(screenName): return ["screen": screenName] case let .reaction(subscriptionType): return ["subscription_type": subscriptionType] case let .directory(searchType, workspace): return ["search_type": searchType, "workspace": workspace] case let .messageSent(subscriptionType, server): return ["subscription_type": subscriptionType, "server": server] case let .mediaUpload(mediaType, subscriptionType): return ["media_type": mediaType, "subscription_type": subscriptionType] case let .serverSwitch(server, serverCount): return ["server_url": server, "server_count": serverCount] case let .updatedSubscriptionSorting(sorting, grouping): return ["sorting": sorting, "grouping": grouping] case let .updatedWebBrowser(browser): return ["web_browser": browser] case let .updatedTheme(theme): return ["theme": theme] case let .jitsiVideoCall(subscriptionType, server): return ["subscription_type": subscriptionType, "server": server] case let .audioMessage(subscriptionType): return ["subscription_type": subscriptionType] default: return nil } } }
mit
d80738ce719465c21e3052e2a42a2c40
33.322785
94
0.631385
4.799115
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/DAO/BatchFetch/Users/GroupUsersQueueBatchFetcher.swift
1
4865
// // GroupUsersQueueBatchFetcher.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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. // class GroupUsersQueueBatchFetcher: Cancelable { private let pageSize = 20 private let requestSender: RequestSender private let groupId: String private let completion: UsersBatchClosure? private var operationQueue: OperationQueue? private var firstRequestHandler: RequestHandler? private var objectsByPage: Dictionary<PagingData, Array<User>> private var errorsByPage: Dictionary<PagingData, APIClientError> init(requestSender: RequestSender, groupId: String, completion: UsersBatchClosure?) { self.requestSender = requestSender self.groupId = groupId self.completion = completion self.objectsByPage = Dictionary<PagingData, Array<User>>() self.errorsByPage = Dictionary<PagingData, APIClientError>() } func cancel() { operationQueue?.cancelAllOperations() firstRequestHandler?.cancel() } func fetch() -> RequestHandler { guard operationQueue == nil else { assert(false) //Fetch should be called only once return RequestHandler(object: self) } let request = GroupCreatorsRequest(groupId: groupId, page: 1, perPage: pageSize) let handler = GroupCreatorsResponseHandler { [weak self](users, pagingInfo, error) -> (Void) in guard let strongSelf = self else { return } if let users = users, let pagingInfo = pagingInfo { strongSelf.objectsByPage[PagingData(page: 1, pageSize: strongSelf.pageSize)] = users strongSelf.prepareBlockOperations(pagingInfo: pagingInfo) } else { strongSelf.completion?(nil, error) } } firstRequestHandler = requestSender.send(request, withResponseHandler: handler) return RequestHandler(object: self) } private func prepareBlockOperations(pagingInfo: PagingInfo) { operationQueue = OperationQueue() operationQueue!.maxConcurrentOperationCount = 4 let finishOperation = BlockOperation() finishOperation.addExecutionBlock { [unowned finishOperation, weak self] in guard let strongSelf = self, !finishOperation.isCancelled else { return } let objects = strongSelf.objectsByPage.sorted(by: { $0.key.page > $1.key.page }).flatMap({ $0.value }) let error = strongSelf.errorsByPage.values.first DispatchQueue.main.async { [weak self] in self?.completion?(objects, error) } } if pagingInfo.totalPages > 1 { for page in 2...pagingInfo.totalPages { let pagingData = PagingData(page: page, pageSize: pageSize) let operation = GroupUsersBatchFetchOperation(requestSender: requestSender, groupId: groupId, pagingData: pagingData) { [weak self](operation, error) in guard let strongSelf = self, let operation = operation as? GroupUsersBatchFetchOperation else { return } if let users = operation.users { strongSelf.objectsByPage[operation.pagingData] = users } if let error = error as? APIClientError { strongSelf.errorsByPage[operation.pagingData] = error } } finishOperation.addDependency(operation) operationQueue!.addOperation(operation) } } operationQueue!.addOperation(finishOperation) } }
mit
b54a331a305f9d4fb71f112107488b49
39.882353
135
0.648099
5.164544
false
false
false
false
google/JacquardSDKiOS
JacquardSDK/Classes/Internal/TagAndComponent/GearInternal.swift
1
2028
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Metadata describing the capabilities of a piece of Gear. class GearCapabilities { /// Helper function to get vendor and product data for specified vendor and product id static func gearData(vendorID: String, productID: String) -> ( vendor: GearMetadata.GearData.Vendor, product: GearMetadata.GearData.Product ) { let gearMetadata = fetchGearMetadata() guard let vendorData = gearMetadata.vendors.first(where: { $0.id == vendorID }), let productData = vendorData.products.first(where: { $0.id == productID }) else { jqLogger.preconditionAssertFailure( "Unable to find gear data for given \(vendorID) and \(productID)" ) return (GearMetadata.GearData.Vendor(), GearMetadata.GearData.Product()) } return (vendorData, productData) } /// Retrieve vendors and associated products information from local .Json file private static func fetchGearMetadata() -> GearMetadata.GearData { guard let jsonURL = jsonURL else { preconditionFailure("GearMetadata json not available.") } do { let jsonData = try Data(contentsOf: jsonURL) return try GearMetadata.GearData(jsonUTF8Data: jsonData) } catch { preconditionFailure("Unable to fetch GearMetadata from Local JSON file error: \((error))") } } static var jsonURL: URL? { Bundle.sdk.url( forResource: "GearMetadata", withExtension: "json" ) } }
apache-2.0
819f237e402240831b1d4cddb45753e4
35.872727
96
0.711538
4.305732
false
false
false
false
AiguangLi/CustomNavigationBarBackground
CustomNavigationBarDemo/UINavigationBarExtention/UINavigationBarExtention.swift
1
1564
// // UINavigationBarExtention.swift // UINavigationBarExtention // // Created by [email protected] on 16/4/22. // Inspired by https://github.com/ltebean/LTNavigationBar/ // Copyright © 2016年 mooeen. All rights reserved. // import Foundation import UIKit extension UINavigationBar { private struct AssociatedKeys { static var DescriptiveName = "CustomNavigationBar" } var overlayer:UIView? { get { let anyObj = objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) return anyObj as? UIView } set { objc_setAssociatedObject(self, &AssociatedKeys.DescriptiveName, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func setCustomBackgroundColor(color:UIColor) { if(self.overlayer == nil) { self.setBackgroundImage(UIImage.init(), forBarMetrics: UIBarMetrics.Default) self.shadowImage = UIImage.init() self.overlayer = UIView.init(frame: CGRect(x: 0, y: -DeviceCommonParameter.StatusBarHeight, width: DeviceCommonParameter.ScreenWidth, height: DeviceCommonParameter.StatusBarHeight + DeviceCommonParameter.NavigationBarHeight)) self.overlayer?.userInteractionEnabled = false self.overlayer?.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] self.insertSubview(self.overlayer!, atIndex: 0) } self.overlayer?.backgroundColor = color } }
gpl-3.0
e68cc099a3f127651c9fcb539c4f5714
34.477273
143
0.677771
4.832817
false
false
false
false
JadenGeller/Gluey
Sources/GlueyTests/GlueyTests.swift
1
5897
// // GlueyTests.swift // GlueyTests // // Created by Jaden Geller on 1/18/16. // Copyright © 2016 Jaden Geller. All rights reserved. // import XCTest import Gluey class GlueyTests: XCTestCase { func testUnificationWithDelayedValueSet() { let a = Binding<Int>() let b = Binding<Int>() try! Binding.unify(a, b) a.value = 10 XCTAssertEqual(10, b.value) } func testUnificationWithEagerValueSet() { let a = Binding<Int>() a.value = 10 let b = Binding<Int>() try! Binding.unify(a, b) XCTAssertEqual(10, b.value) } func testChainedUnification() { let a = Binding<Int>() let b = Binding<Int>() let c = Binding<Int>() try! Binding.unify(a, b) try! Binding.unify(b, c) c.value = 10 XCTAssertEqual(a.value, 10) XCTAssertEqual(b.value, 10) } func testSuccessfulUnification() { let a = Binding<Int>() let b = Binding<Int>() a.value = 10 b.value = 10 try! Binding.unify(a, b) } func testSuccessfulChainedUnification() { let a = Binding<Int>() let b = Binding<Int>() let c = Binding<Int>() a.value = 10 c.value = 10 try! Binding.unify(a, b) try! Binding.unify(b, c) } func testFailedUnification() { let a = Binding<Int>() let b = Binding<Int>() a.value = 10 b.value = 20 do { try Binding.unify(a, b) XCTFail() } catch { } } func testFailedChainedUnification() { let a = Binding<Int>() let b = Binding<Int>() let c = Binding<Int>() a.value = 10 c.value = 20 try! Binding.unify(a, b) do { try Binding.unify(b, c) XCTFail() } catch { } } func testValueMutation() { let a = Binding<Int>() let b = Binding<Int>() a.value = 10 b.value = 10 try! Binding.unify(a, b) b.value = 12 XCTAssertEqual(a.value, 12) } func testBacktracking() { let a = Binding<Int>() let b = Binding<Int>() let c = Binding<Int>() let d = Binding<Int>() let e = Binding<Int>() try! Binding.unify(a, b) try! Binding.unify(c, d) do { try Binding.attempt(a) { try! Binding.unify(a, e) try! Binding.unify(a, c) throw UnificationError("Test") } XCTFail() } catch { a.value = 10 e.value = 20 XCTAssertEqual(10, a.value) XCTAssertEqual(10, b.value) XCTAssertEqual(20, c.value) XCTAssertEqual(20, d.value) XCTAssertEqual(20, e.value) } } func testValue() { let a = Unifiable.literal(10) let b = Unifiable.variable(Binding<Int>()) let c = Unifiable.literal(12) try! Unifiable.unify(a, b) XCTAssertEqual(10, b.value) try! Unifiable.unify(a, a) do { try Unifiable.unify(a, c) XCTFail() } catch { } } func testRecursiveUnification() throws { let a = Unifiable.literal(Unifiable.variable(Binding<Int>())) let b = Unifiable.literal(Unifiable.literal(10)) try Unifiable.unify(a, b) XCTAssertEqual(10, b.value?.value) } func testRecursiveBacktracking() throws { let a = Unifiable.literal(Unifiable.variable(Binding<Int>())) let b = Unifiable.literal(Unifiable.literal(10)) let c = Unifiable.literal(Unifiable.literal(20)) let d = Unifiable.literal(Unifiable.variable(Binding<Int>())) try Unifiable.unify(a, b) do { try Unifiable.attempt(a) { try Unifiable.unify(b, c) } } catch { try Unifiable.unify(a, d) } XCTAssertEqual(10, d.value?.value) } func testCopy() { let a = Unifiable.variable(Binding<Int>()) let b = Unifiable.variable(Binding<Int>()) try! Unifiable.unify(a, b) let context = CopyContext() let aa = Unifiable.copy(a, withContext: context) let bb = Unifiable.copy(b, withContext: context) try! Unifiable.unify(a, Unifiable.literal(1)) XCTAssertEqual(1, b.value) XCTAssertEqual(1, a.value) XCTAssertEqual(nil, aa.value) XCTAssertEqual(nil, bb.value) try! Unifiable.unify(aa, Unifiable.literal(2)) XCTAssertEqual(1, b.value) XCTAssertEqual(1, a.value) XCTAssertEqual(2, aa.value) XCTAssertEqual(2, bb.value) } func testRecursiveCopy() throws { let a = Unifiable.literal(Unifiable.variable(Binding<Int>())) let b = Unifiable.literal(Unifiable.variable(Binding<Int>())) try Unifiable.unify(a, b) let context = CopyContext() let aa = Unifiable.copy(a, withContext: context) let bb = Unifiable.copy(b, withContext: context) try! Unifiable.unify(a, Unifiable.literal(Unifiable.literal(1))) XCTAssertEqual(1, b.value!.value) XCTAssertEqual(1, a.value!.value) XCTAssertEqual(nil, aa.value!.value) XCTAssertEqual(nil, bb.value!.value) try! Unifiable.unify(aa, Unifiable.literal(Unifiable.literal(2))) XCTAssertEqual(1, b.value!.value) XCTAssertEqual(1, a.value!.value) XCTAssertEqual(2, aa.value!.value) XCTAssertEqual(2, bb.value!.value) } }
mit
57ce4fdee82cb085e171e9ff085f9cbf
26.045872
73
0.522218
3.949096
false
true
false
false
ZeeQL/ZeeQL3Apache
Sources/ApacheZeeQLAdaptor/ApacheRequestAdaptor.swift
1
6751
// // ApacheRequestAdaptor.swift // ZeeQL // // Created by Helge Hess on 03.04.17. // Copyright © 2017 ZeeZide GmbH. All rights reserved. // import APRAdaptor import CApache import CAPRUtil import ZeeQL // our funcs need to declare the type, there is no automagic macro way ... fileprivate func APR_RETRIEVE_OPTIONAL_FN<T>(_ name: String) -> T? { guard let fn = apr_dynamic_fn_retrieve(name) else { return nil } return unsafeBitCast(fn, to: T.self) // TBD: is there a better way? } /** * A ZeeQL adaptor which hooks up ZeeQL to Apache `mod_dbd`. * * Using `mod_dbd` has several advantages over using `APRAdaptor` directly: * * - endpoint can be configured in the regular Apache configuration * - does configurable pooling and connection-reuse * - can share connections between different Apache modules (not just Swift * ones!). * E.g. if you implement a part of your app in PHP, it can still use the same * pool. * * Example code (using ApacheExpress): * * app.use(mod_dbd()) * * try req.dbAdaptor?.select("SELECT COUNT(*) FROM person") { (count:Int) in * console.log("Number of persons:", count) * } * * THREADING: This adaptor is scoped to a single Apache request and hence is * single threaded. */ open class ApacheRequestAdaptor : ZeeQL.Adaptor { public enum Error : Swift.Error { case MissingAcquireModDBDNotAvailable case CouldNotAquire // those should never happen: case RequestHasNoPool case ConnectionHasNoHandle case ConnectionHasNoDriver } typealias aprz_OFN_ap_dbd_acquire_t = @convention(c) ( UnsafeMutableRawPointer? ) -> UnsafeMutablePointer<ap_dbd_t>? static let ap_dbd_acquire : aprz_OFN_ap_dbd_acquire_t? = { return APR_RETRIEVE_OPTIONAL_FN("ap_dbd_acquire") }() public let handle : OpaquePointer // UnsafeMutablePointer<request_rec> var _expressionFactory : SQLExpressionFactory? public var expressionFactory : SQLExpressionFactory { return _expressionFactory ?? APRSQLExpressionFactory.shared } public var model : Model? public init(handle: UnsafeMutablePointer<request_rec>, model: Model? = nil) throws { guard ApacheRequestAdaptor.ap_dbd_acquire != nil else { throw Error.MissingAcquireModDBDNotAvailable } self.handle = OpaquePointer(handle) self.model = model } public var typedHandle : UnsafeMutablePointer<request_rec>? { // yes, this is awkward, but we cannot store request_rec or ZzApache in an // instance variable, crashes swiftc return UnsafeMutablePointer<request_rec>(handle) } open func openChannel() throws -> AdaptorChannel { return try primaryOpenChannel() } open func primaryOpenChannel() throws -> AdaptorChannel { guard let acquire = ApacheRequestAdaptor.ap_dbd_acquire else { throw AdaptorError.CouldNotOpenChannel( Error.MissingAcquireModDBDNotAvailable) } guard let apCon = acquire(typedHandle) else { throw AdaptorError.CouldNotOpenChannel(Error.CouldNotAquire) } guard let pool = typedHandle!.pointee.pool else { throw AdaptorError.CouldNotOpenChannel(Error.RequestHasNoPool) } guard let con = apCon.pointee.handle else { throw AdaptorError.CouldNotOpenChannel(Error.ConnectionHasNoHandle) } guard let driver = apCon.pointee.driver else { throw AdaptorError.CouldNotOpenChannel(Error.ConnectionHasNoDriver) } if let driverName = apr_dbd_name(driver) { if strcmp(driverName, APRDriverNames.SQLite3) == 0 { if _expressionFactory == nil { _expressionFactory = APRSQLExpressionFactory.shared } return try APRSQLite3AdaptorChannel(adaptor: self, pool: pool, driver: driver, connection: con, ownsPool: false, ownsConnection: false) } if strcmp(driverName, APRDriverNames.PostgreSQL) == 0 { if _expressionFactory == nil { _expressionFactory = APRPostgreSQLExpressionFactory.shared } return try APRPostgreSQLAdaptorChannel(adaptor: self, pool: pool, driver: driver, connection: con, ownsPool: false, ownsConnection: false) } } if _expressionFactory == nil { _expressionFactory = APRSQLExpressionFactory.shared } return try APRAdaptorChannel(adaptor: self, pool: pool, driver: driver, connection: con, ownsPool: false, ownsConnection: false) } // MARK: - Model public func fetchModel() throws -> Model { let channel = try openChannelFromPool() defer { releaseChannel(channel) } // TODO: maybe make the model-fetch public API to avoid all those dupes if let c = channel as? APRSQLite3AdaptorChannel { return try SQLite3ModelFetch(channel: c).fetchModel() } else if let c = channel as? APRPostgreSQLAdaptorChannel { return try PostgreSQLModelFetch(channel: c).fetchModel() } else { throw AdaptorError.NotImplemented(#function) } } public func fetchModelTag() throws -> ModelTag { let channel = try openChannelFromPool() defer { releaseChannel(channel) } // TODO: maybe make the model-fetch public API to avoid all those dupes if let c = channel as? APRSQLite3AdaptorChannel { return try SQLite3ModelFetch(channel: c).fetchModelTag() } else if let c = channel as? APRPostgreSQLAdaptorChannel { return try PostgreSQLModelFetch(channel: c).fetchModelTag() } else { throw AdaptorError.NotImplemented(#function) } } // MARK: - Request local connection pool for mod_dbd let maxPoolSize = 4 var pooledConnections = [ AdaptorChannel ]() // This is easy in this case, because we are single threaded and the pool // won't live for long. // We don't want to acquire connections from mod_dbd unnecessarily. public func openChannelFromPool() throws -> AdaptorChannel { guard !pooledConnections.isEmpty else { return try primaryOpenChannel() } return pooledConnections.removeFirst() // expensive but better } open func releaseChannel(_ channel: AdaptorChannel) { guard pooledConnections.count < maxPoolSize else { return } // do not pool // This is fine from a retain-cycle perspective, the APRAdaptorChannel // doesn't actually retain the adaptor (just refers to the handles). pooledConnections.append(channel) } }
apache-2.0
f52961f4506b07a2aaae1d3b68d340ea
33.974093
80
0.659704
4.388817
false
false
false
false
perlmunger/NewFreeApps
NewFreeApps/DataManager.swift
1
4410
// // DataManager.swift // NewFreeApps // // Created by Matt Long on 10/9/14. // Copyright (c) 2014 Matt Long. All rights reserved. // import UIKit import CoreData class DataManager: NSObject { var managedObjectContext:NSManagedObjectContext? class var sharedInstance : DataManager { struct DataManagerStruct { static let sharedInstance = DataManager() } return DataManagerStruct.sharedInstance } override init() { super.init() } func downloadFeed() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in var task = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: NSURL(string: "https://itunes.apple.com/us/rss/newfreeapplications/limit=10/json")), completionHandler: { (data, response, error) -> Void in if data.length > 0 { var object = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSDictionary var importContext = NSManagedObjectContext() importContext.persistentStoreCoordinator = self.managedObjectContext!.persistentStoreCoordinator var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" var request = NSFetchRequest(entityName: EntryMO.entityName()) var entryObjects = importContext.executeFetchRequest(request, error: nil) as? [EntryMO] var lookup:[String:EntryMO] = [:] for entryObject in entryObjects! { lookup[entryObject.id!] = entryObject } if object != nil { let entries = object!.valueForKeyPath("feed.entry") as? NSArray for entry in entries! { if let entryDict = entry as? NSDictionary { let id = entryDict.valueForKeyPath("id.attributes.im:id") as String var entryObject = lookup[id] if entryObject == nil { entryObject = EntryMO(managedObjectContext: importContext) } let images = entryDict.valueForKeyPath("im:image") as NSArray let filteredImages = images.filteredArrayUsingPredicate(NSPredicate(format: "attributes.height == %@", "75")) as NSArray let imageLink = (filteredImages.lastObject as NSDictionary).valueForKeyPath("label") as? String let releaseDate = entryDict.valueForKeyPath("im:releaseDate.label") as? String let link = entryDict.valueForKeyPath("link.attributes.href") as? String let rights = entryDict.valueForKeyPath("rights.label") as? String let title = entryDict.valueForKeyPath("title.label") as? String entryObject!.id = id entryObject!.imageLink = imageLink if releaseDate != nil { entryObject!.releaseDate = dateFormatter.dateFromString(releaseDate!) } entryObject!.link = link entryObject!.rights = rights entryObject!.title = title } } importContext.save(nil) } dispatch_async(dispatch_get_main_queue(), { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName("dataDidUpdateNotification", object: nil) }) } }) task.resume() }) } }
mit
e4fc8f340c87279391b09b42887f6da6
44
230
0.480272
6.5625
false
false
false
false
QHexacoda/Research-iOS
Searcher/Searcher/ViewControllers/BookmarkViewController.swift
1
3719
// // BookmarkViewController.swift // Searcher // // Created by Weerayoot Ngandee on 7/24/2559 BE. // Copyright © 2559 Weerayoot Ngandee. All rights reserved. // import UIKit class BookmarkViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Properties @IBOutlet weak var bookmarkTableView: UITableView! var filteredData = [SearchObj]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. bookmarkTableView.delegate = self bookmarkTableView.dataSource = self NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BookmarkViewController.methodOfReceivedNotificationReload(_:)), name:"NotificationIdentifierReload", object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Fetch data self.fetchBookmarks() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { } // MARK: - Table View func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SearchCell let search = filteredData[indexPath.row] as SearchObj! cell.titleLb?.text = String(format:"%@", search.title) cell.authorLb?.text = String(format:"ผู้แต่ง : %@", search.author) cell.sourceLb?.text = String(format:"แหล่งที่มา : %@", search.site_name.uppercaseString) cell.publishDateLb.text = String(format:"ปีที่เผยแพร่ : %@", search.pubyear) cell.searchObj = search return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 190.0 } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // if segue.identifier == "showDetail" { // if let indexPath = tableView.indexPathForSelectedRow { // let candy = candies[indexPath.row] // let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController // controller.detailCandy = candy // controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem() // controller.navigationItem.leftItemsSupplementBackButton = true // } // } } // MARK: - Helper Methods func fetchBookmarks() { filteredData.removeAll() // Query using an NSPredicate let searchText = "1" let predicate = NSPredicate(format: "bookmarked BEGINSWITH %@", searchText) let searchResults = Utillities.sharedInstance.realm.objects(SearchObj).filter(predicate) for searchObj in searchResults { filteredData.append(searchObj) } bookmarkTableView.reloadData() } func methodOfReceivedNotificationReload(notification: NSNotification){ //Take Action on Notification print("Reload") self.fetchBookmarks() } }
unlicense
ee0435c4ff68c928e67dc7015d16b338
35.237624
196
0.659563
5.140449
false
false
false
false
Allow2CEO/browser-ios
Client/Frontend/Browser/SearchSuggestClient.swift
2
2936
/* 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 Alamofire import Foundation import Shared let SearchSuggestClientErrorDomain = "org.mozilla.firefox.SearchSuggestClient" let SearchSuggestClientErrorInvalidEngine = 0 let SearchSuggestClientErrorInvalidResponse = 1 /* * Clients of SearchSuggestionClient should retain the object during the * lifetime of the search suggestion query, as requests are canceled during destruction. * * Query callbacks that must run even if they are cancelled should wrap their contents in `withExtendendLifetime`. */ class SearchSuggestClient { fileprivate let searchEngine: OpenSearchEngine fileprivate weak var request: Request? fileprivate let userAgent: String lazy fileprivate var alamofire: Alamofire.SessionManager = { let configuration = URLSessionConfiguration.ephemeral return Alamofire.SessionManager.managerWithUserAgent(self.userAgent, configuration: configuration) }() init(searchEngine: OpenSearchEngine, userAgent: String) { self.searchEngine = searchEngine self.userAgent = userAgent } func query(_ query: String, callback: @escaping ([String]?, Error?) -> ()) { let url = searchEngine.suggestURLForQuery(query) if url == nil { let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidEngine, userInfo: nil) callback(nil, error) return } request = alamofire.request(url!) .validate(statusCode: 200..<300) .responseJSON { response in if let error = response.result.error { callback(nil, error) return } // The response will be of the following format: // ["foobar",["foobar","foobar2000 mac","foobar skins",...]] // That is, an array of at least two elements: the search term and an array of suggestions. let array = response.result.value as? NSArray if array?.count ?? 0 < 2 { let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil) callback(nil, error) return } let suggestions = array?[1] as? [String] if suggestions == nil { let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil) callback(nil, error) return } callback(suggestions, nil) } } func cancelPendingRequest() { request?.cancel() } }
mpl-2.0
d909cb928fb39171f2ea5a9cc8395c63
38.146667
141
0.636921
5.233512
false
true
false
false
dnseitz/YAPI
YAPI/YAPI/V2/V2_YelpPhoneSearchRequest.swift
1
1046
// // YelpPhoneSearchRequest.swift // YAPI // // Created by Daniel Seitz on 9/12/16. // Copyright © 2016 Daniel Seitz. All rights reserved. // import Foundation import OAuthSwift public final class YelpV2PhoneSearchRequest : YelpRequest { public typealias Response = YelpV2PhoneSearchResponse public let oauthVersion: OAuthSwiftCredential.Version = .oauth1 public let path: String = YelpEndpoints.V2.phone public let parameters: [String: String] public let session: YelpHTTPClient public var requestMethod: OAuthSwiftHTTPRequest.Method { return .GET } init(phoneSearch: YelpV2PhoneSearchParameters, session: YelpHTTPClient = YelpHTTPClient.sharedSession) { var parameters = [String: String]() parameters.insertParameter(phoneSearch.phone) if let countryCode = phoneSearch.countryCode { parameters.insertParameter(countryCode) } if let category = phoneSearch.category { parameters.insertParameter(category) } self.parameters = parameters self.session = session } }
mit
1578b165d238e689422b60e208ec06d6
28.027778
106
0.745455
4.390756
false
false
false
false
crewst/sycamore
Radar/Radar/Networking.swift
1
9864
// // Networking.swift // Radar // // Created by Thomas Crews on 3/8/17. // Copyright © 2017 Thomas Crews. All rights reserved. // import Foundation import SystemConfiguration.CaptiveNetwork import SystemConfiguration.SCNetwork import UIKit import PlainPing public class Networking: NSObject, URLSessionDelegate, URLSessionDownloadDelegate { let url = URL(string: "https://dl.dropboxusercontent.com/s/tbjg34fo6u633vo/LargeTestFile") class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .reachable let needsConnection = flags == .connectionRequired return isReachable && !needsConnection } class func fetchSSIDInfo() -> String { var currentSSID = "" if let interfaces = CNCopySupportedInterfaces() { for i in 0..<CFArrayGetCount(interfaces) { let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, i) let rec = unsafeBitCast(interfaceName, to: AnyObject.self) let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString) if unsafeInterfaceData != nil { let interfaceData = unsafeInterfaceData! as NSDictionary currentSSID = interfaceData["SSID"] as! String } } } return currentSSID } class func getWiFiAddress() -> String? { var address : String? // Get list of all interfaces on the local machine var ifaddr : UnsafeMutablePointer<ifaddrs>? guard getifaddrs(&ifaddr) == 0 else { return nil } guard let firstAddr = ifaddr else { return nil } // For each interface for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { let interface = ifptr.pointee // Check for IPv4 interface let addrFamily = interface.ifa_addr.pointee.sa_family if addrFamily == UInt8(AF_INET) { // Check interface name: let name = String(cString: interface.ifa_name) if name == "en0" { // Convert interface address to a human readable string var addr = interface.ifa_addr.pointee var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String(cString: hostname) } } } freeifaddrs(ifaddr) return address } class func getWiFiAddressV6() -> String? { var address : String? // Get list of all interfaces on the local machine var ifaddr : UnsafeMutablePointer<ifaddrs>? guard getifaddrs(&ifaddr) == 0 else { return nil } guard let firstAddr = ifaddr else { return nil } // For each interface for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { let interface = ifptr.pointee // Check for IPv6 interface let addrFamily = interface.ifa_addr.pointee.sa_family if addrFamily == UInt8(AF_INET6) { // Check interface name: // let name = String(cString: interface.ifa_name) // if name == "en0" { // Convert interface address to a human readable string var addr = interface.ifa_addr.pointee var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String(cString: hostname) //} } } freeifaddrs(ifaddr) return address } class func getExternalAddress() -> String? { let url = URL(string: "https://api.ipify.org/") let ipAddress = try? String(contentsOf: url!, encoding: String.Encoding.utf8) if ipAddress != nil { return ipAddress } else { return "Unavailable" } } func testSpeed() { Globals.shared.dlStartTime = Date() Globals.shared.DownComplete = false let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) let task = session.downloadTask(with: url!) if Globals.shared.currentSSID == "" { Globals.shared.bandwidth = 0 Globals.shared.DownComplete = true session.invalidateAndCancel() NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil) } else { task.resume() } } public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8) / 1000 let progress = (Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) * 100.0 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessUpdating"), object: nil, userInfo: ["progress" : progress]) } public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("INFO: Process completed.") if Globals.shared.DownComplete == false { let elapsed = Double( Date().timeIntervalSince(Globals.shared.dlStartTime)) Globals.shared.bandwidth = Int(Globals.shared.dlFileSize / elapsed) Globals.shared.DownComplete = true Globals.shared.dataUse! += (Globals.shared.dlFileSize! / 8000) } NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil) } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error != nil { print("ERROR: Process interrupted.") Globals.shared.bandwidth = 0 Globals.shared.DownComplete = true NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil) } } class func getBSSID() -> String{ var currentBSSID = "" if let interfaces = CNCopySupportedInterfaces() { for i in 0..<CFArrayGetCount(interfaces) { let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, i) let rec = unsafeBitCast(interfaceName, to: AnyObject.self) let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString) if unsafeInterfaceData != nil { let interfaceData = unsafeInterfaceData! as NSDictionary currentBSSID = interfaceData["BSSID"] as! String } } } return currentBSSID } class func getDNS() -> String { var numAddress = "" let host = CFHostCreateWithName(nil,"www.google.com" as CFString).takeRetainedValue() CFHostStartInfoResolution(host, .addresses, nil) var success: DarwinBoolean = false if let addresses = CFHostGetAddressing(host, &success)?.takeUnretainedValue() as NSArray?, let theAddress = addresses.firstObject as? NSData { var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if getnameinfo(theAddress.bytes.assumingMemoryBound(to: sockaddr.self), socklen_t(theAddress.length), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 { numAddress = String(cString: hostname) } } return numAddress } class func pingHost() { Globals.shared.latency = "..." PlainPing.ping("www.google.com", withTimeout: 1.0, completionBlock: { (timeElapsed:Double?, error:Error?) in if let latency = timeElapsed { print("INFO: Ping time is \(latency) ms.") Globals.shared.latency = String(Int(latency)) + " ms" } if error != nil { print("WARNING: Ping time is unknown.") Globals.shared.latency = "Unknown" } }) } } // S.D.G.
gpl-3.0
78af7ab9a1679c2c216e96d99ef358cf
37.98419
183
0.577005
5.009142
false
false
false
false
IvanVorobei/RateApp
SPRateApp - project/SPRateApp/sparrow/ui/controllers/SPPageItemsScallingViewController.swift
1
2892
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @available(iOS, unavailable) public class SPPageItemsScallingViewController: SPGradientViewControllerDEPRICATED, UICollectionViewDataSource, UICollectionViewDelegate { //var collectionView = SPPageItemsScalingCollectionView() var collectionView = SPCollectionView.init() override public func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.collectionView.delegate = self self.view.addSubview(self.collectionView) } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.collectionView.frame = CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height * 0.5) self.collectionView.center = self.view.center } //MARK: - UICollectionViewDataSource //must ovveride in subclass public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { fatalError("need emplementation in subclass") } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { fatalError("need emplementation in subclass") } //MARK: - UICollectionViewDelegate //Centering first and last item func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { let width = self.collectionView.frame.width let itemWidth = self.collectionView.layout.itemSize.width let edgeInsets = (width - itemWidth) / 2 return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets) } }
mit
bd683ccf8d1beb90dd6fbf58f41bdbf7
46.393443
167
0.740574
5.07193
false
false
false
false
TYG1/SwiftLearning
SwiftLearning.playground/Pages/Functions.xcplaygroundpage/Contents.swift
1
13476
/*: [Table of Contents](@first) | [Previous](@previous) | [Next](@next) - - - # Functions * callout(Session Overview): Functions are statements of code grouped together to provide readability, reusability, and modularity within your program. The Swift Standard Library provides functions that we have already used within previous Playgrounds. Please visit The Swift Standard Library [Functions](https://developer.apple.com/library/prerelease/mac/documentation/Swift/Reference/Swift_StandardLibrary_Functions/index.html#//apple_ref/doc/uid/TP40016052) online resource to see the full list of global functions available to your programs. */ import Foundation /*: ## Calling Functions All functions have a name, that describes what the function will do when you *call* the function. The `print` function has a name *print* that informs the caller the function will print the parameters *passed* to the function. Functions are constructed using the following parts: - Name of the function - Parameters data type(s) that will be passed as arguments - Return type of the output */ let i = 4 let j = 5 let biggest = max(i, j) //: The above statements creates 2 Int constants, *calls* the function `max`, *passing* parameters i and j and *returns* an Int of which parameter is larger. //: > **Experiment**: Call the `min` function to determine which value is smaller. /*: ## Creating your own functions Calling functions created outside of your program is a very common task. There will be many instances that you will have to create your own function to accomplish a specific task. The process of creating a function is also known as defining a function. You start defining a function with the `func` keyword. */ func sayHiTeacher() { print("Hi Teach!"); } //: The above statement creates a function using the `func` keyword, with a name of *sayHiTeacher*, that doesn't accept parameters and doesn't return a value. //: > **Experiment**: Call the `sayHiTeacher` function. /*: ## Passing parameters Functions can be defined with no parameters or with many parameters. The above function `max` is defined with 2 parameters and the `print` function is defined without parameters. Parameters are data types such as `Int`s, `Bool`eans, `String`s and complex types such as [Enumerations](Enumerations), [Classes & Structures](Classes%20and%20Structures) explained in future sessions. */ /*: ### Functions Without Parameters The above function `sayHiTeacher` is and example of a function defined without parameters. */ //: > **Experiment**: Create and call a function to print your name. Define the function with a name of your choice, without parameters and no return value. /*: ### Functions With Multiple Parameters The above function `max` is and example of a function defined with multiple parameters. The `min` function is also a function defined with multiple parameters. */ func sayHiTeacher2(name: String, className: String) { print("Hi \(name), from my \(className) class"); } sayHiTeacher2("Mr. Sheets", className: "Swift") //: The above statement creates a function `sayHiTeacher2` defined with accepting 1 parameter of type String. //: > **Experiment**: Create and call a function to print your name and age. Define the function with a name of your choice, with a parameter of a `String` and `Int` data types and no return value. /*: ### Function Parameter Names There are two possible names you can give parameters when defining a function. The *local* parameter name is only available for use within the function body. The *external* parameter name is used by the caller to label arguments passed with calling a function. All functions have *local* parameter names name must be unique when defining the function. */ /*: ### Specifying External Parameter Names *External* parameter names are exposed to the caller of the function. *External* and *local* parameter names don't have to be the same and by default the first parameter doesn't have an external name and all subsequent *local* names are also the *external* names. The `sayHiTeacher2` function is an example of a function omitting the *external* name for the first parameter and using the default external name for the second parameter. */ func sayHiTeacher3(teacherName name: String, tmpName className: String) { print("Hi \(name), from my \(className) class"); } sayHiTeacher3(teacherName: "Mr. Sheets", tmpName: "Swift") /*: ### Omitting External Parameter Names You can omit *external* names by using the underscore `_` in front of second or subsequent parameters. */ func sayHiTeacher4(name: String, _ className: String) { print("Hi \(name), from my \(className) class"); } sayHiTeacher4("Mr. Sheets", "Swift") /*: ### Default Parameter Values Function parameters can be set to a default value and omitted from a function call. It's recommended that you place all defaulted parameters at the end of the parameter list. */ func sayHiTeacher5(name: String = "Mr. Sheets", _ className: String = "Swift") { print("Hi \(name), from my \(className) class"); } sayHiTeacher5() /*: ### Variadic Parameters Functions can be defined with accepting a varying number of arguments (zero or more) when called. You used the three dot notation `...` after the parameter type name. A function can only have at most 1 variadic parameter. */ func sayHiTeacher6(name: String, classNames: String ...) { var classes = "" for className in classNames { classes += className + " " } print("Hi \(name), from my \(classes)classes"); } sayHiTeacher6("Mr. Sheets", classNames: "Swift 1", "Swift 2", "Swift 3") /*: ### Constant and Variable Parameters By default function parameters are defined as constants, meaning that you are not allowed to change the value. You can also define parameters as variable, providing you the ability to change the value and not define another variable with in your function. */ func sayHiTeacher7(var teacherName name: String, className: String) { if !name.hasPrefix("Mr.") { name = "Mr. " + name; } print("Hi \(name), from my \(className) class"); } sayHiTeacher7(teacherName: "Sheets", className: "Swift 1") //: The above variable parameter `name`'s value was changed within the function body but changing the value of variable parameters has no impact outside of the function. /*: ### In-Out Parameters As mentioned above, changing the value of a variable parameter doesn't change the value of the argument variable. If you want the changes to a variable parameter to be reflected outside of your function body, you can define the variable parameter with the `inout` keyword. You place an `&` in front of the varable argument to indicate that the function can modify the value. */ func sayHiTeacher8(inout name: String, _ className: String) { if !name.hasPrefix("Mr.") { name = "Mr. " + name; } print("Hi \(name), from my \(className) class"); } var teacherName = "Sheets"; sayHiTeacher8(&teacherName, "Swift 1") print(teacherName) //: The above variable `teacherName`'s value was changed within the function body and now has a new value. /*: ## Return values When defining a function, the part that describes the output of calling the function is called the `return` value. You indicate what you are *returning* from a function using the right arrow `->`. The return value from a function can be ignored when it is called. */ func getHello() -> String { return "Hello"; } let hello = getHello() getHello() /*: ### Functions Without Return Values As we have seen above, functions don't always have to return a value. A function without a return value (or omitting the function definition return syntax) is the same as including the return syntax of ` -> Void`. */ func sayHi() -> Void { print("Hi"); } sayHi() /*: ### Functions with Multiple Return Values There are instances where returning multiple values from a function is needed. Swift provides tuples as a return type enabling you to return multiple values grouped together in one return type. */ func ends(names: String ...) -> (first: String, last: String)? { if names.isEmpty { return nil } var first = "z" var last = "." for name in names[0..<names.count] { if name < first { first = name } else if name > last { last = name } } return (first, last) } let firstLastName = ends("Mathew", "Sam", "Jack", "Annie", "Oliver", "Hudson") if firstLastName != nil { print("first = \(firstLastName!.first), last = \(firstLastName!.last)") } let none = ends() if none != nil { print("first = \(none!.first), last = \(none!.last)") } //: The above function `ends` defines variadic parameter of `String`s and returns an optional tuple. /*: ## Function as Types We have already learned about data types such as `Int` and `String` in which you declare that a constant or variable stores a certain *type* of data. Functions are *types* as well. Function types are comprised of parameter types and the return type of the function. */ func twice(num: Int) -> Int { return 2 * num } //: The type of the `twice` function is `(Int) -> Int`. In the case of the `sayHiTeacher`, the function type is `() -> Void`. /*: Since functions are types, you can refer to the function in a constant or variable like: */ let doubleIt: (Int) -> Int = twice // or simply using type inference let doubleItAgain = twice print(doubleItAgain(4)) /*: ### Function Types as parameter types Function types can also be used as parameters, meaning that you can pass functions as arguments to another function. */ func printTwice(twiceFunction: (Int) -> Int, _ num: Int) { print(twiceFunction(num)) } printTwice(doubleItAgain, 8) /*: The `printTwice` function has two parameters. The first parameter `twiceFunction` is of type `(Int) -> Int` and the second parameter is an `Int`. You can pass any function type that conforms to `(Int) -> Int` to the `printTwice` function. The second parameter is used as an argument for the first parameter function type. */ /*: ### Function Types as a return type Function types can also be used as return types, meaning that you can return a functions within a function. Defining a function that returns a function is done by placing the function type after the defined function's return arrow `-> `. */ func sayHello(name: String) -> String { return "Hello " + name + "!" } func sayGoodBye(name: String) -> String { return "GoodBye " + name + "!" } func saySomething(justMet justMet: Bool) -> (String) -> String { return justMet ? sayHello : sayGoodBye; } print(saySomething(justMet: true)("Chris")) print(saySomething(justMet: false)("Jason")) /*: Here we have defined two functions, one that returns a `String` saying 'hello' to someone and another function that returns a `String` saying 'good bye' to someone. The third function defined `saySomething` accepts as an argument a `Boolean` if whether you just met someone and returns the appropriate function type to be called at a later time. The `firstTime` and `longTimeFriends` constants refer to different function on which you can call passing a `String` of a persons name as an argument. */ /*: ## Nesting Functions The function examples above are called *global functions*. A *global* function means that the function is visible from anywhere and anytime. Nested functions, functions within functions, are visible only to the function containing the nested function. */ func saySomethingNested(justMet justMet: Bool) -> (String) -> String { func hello(name: String) -> String { return "Hello " + name + "!" } func goodBye(name: String) -> String { return "GoodBye " + name + "!" } return justMet ? hello : goodBye; } print(saySomethingNested(justMet: true)("Chris")) print(saySomethingNested(justMet: false)("Jason")) /*: Above we rewrote the `saySomething` *global* function as `saySomethingNested`, *nesting* functions `hello` and `goodBye` and return the correct nested function. */ /*: - - - * callout(Exercise): Create a playground with pages with each playground page consisting of the previous four exercises. Refactor each exercise leveraging collection types and functions. **Constraints:** Create a swift file containing your functions for each exercise in the **Sources** directory. Make sure each function has the keyword `public` in front of the keyword `func`. * callout(Checkpoint): At this point, you should have a good understanding of calling and creating functions. Functions can be declared with or without parameters and with or without return values. Functions can also be used just like any other data type. You can assign functions to a constant or variable, pass functions as arguments to other functions and return functions from functions. **Keywords to remember:** - `func` = to create a function - `inout` = changing a value of a parameter will change the value of the argument - `return` = exiting a function passing to the caller a potential value * callout(Supporting Materials): Chapters and sections from the Guide and Vidoes from WWDC - [Guide: Functions](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html) - - - [Table of Contents](@first) | [Previous](@previous) | [Next](@next) */
mit
03030793f2686c44df3d52302110d8e5
46.957295
546
0.726254
4.251104
false
false
false
false
saagarjha/iina
iina/HistoryWindowController.swift
1
9807
// // HistoryWindowController.swift // iina // // Created by lhc on 28/4/2017. // Copyright © 2017 lhc. All rights reserved. // import Cocoa fileprivate let MenuItemTagShowInFinder = 100 fileprivate let MenuItemTagDelete = 101 fileprivate let MenuItemTagSearchFilename = 200 fileprivate let MenuItemTagSearchFullPath = 201 fileprivate let MenuItemTagPlay = 300 fileprivate let MenuItemTagPlayInNewWindow = 301 fileprivate extension NSUserInterfaceItemIdentifier { static let time = NSUserInterfaceItemIdentifier("Time") static let filename = NSUserInterfaceItemIdentifier("Filename") static let progress = NSUserInterfaceItemIdentifier("Progress") static let group = NSUserInterfaceItemIdentifier("Group") static let contextMenu = NSUserInterfaceItemIdentifier("ContextMenu") } class HistoryWindowController: NSWindowController, NSOutlineViewDelegate, NSOutlineViewDataSource, NSMenuDelegate, NSMenuItemValidation { enum SortOption: Int { case lastPlayed = 0 case fileLocation } enum SearchOption { case filename, fullPath } private let getKey: [SortOption: (PlaybackHistory) -> String] = [ .lastPlayed: { DateFormatter.localizedString(from: $0.addedDate, dateStyle: .medium, timeStyle: .none) }, .fileLocation: { $0.url.deletingLastPathComponent().path } ] override var windowNibName: NSNib.Name { return NSNib.Name("HistoryWindowController") } @IBOutlet weak var outlineView: NSOutlineView! @IBOutlet weak var historySearchField: NSSearchField! var groupBy: SortOption = .lastPlayed var searchOption: SearchOption = .fullPath private var historyData: [String: [PlaybackHistory]] = [:] private var historyDataKeys: [String] = [] override func windowDidLoad() { super.windowDidLoad() NotificationCenter.default.addObserver(forName: .iinaHistoryUpdated, object: nil, queue: .main) { [unowned self] _ in self.reloadData() } prepareData() outlineView.delegate = self outlineView.dataSource = self outlineView.menu?.delegate = self outlineView.target = self outlineView.doubleAction = #selector(doubleAction) outlineView.expandItem(nil, expandChildren: true) } func reloadData() { prepareData() outlineView.reloadData() outlineView.expandItem(nil, expandChildren: true) } private func prepareData(fromHistory historyList: [PlaybackHistory]? = nil) { // reconstruct data historyData.removeAll() historyDataKeys.removeAll() let historyList = historyList ?? HistoryController.shared.history for entry in historyList { addToData(entry, forKey: getKey[groupBy]!(entry)) } } private func addToData(_ entry: PlaybackHistory, forKey key: String) { if historyData[key] == nil { historyData[key] = [] historyDataKeys.append(key) } historyData[key]!.append(entry) } // MARK: Key event override func keyDown(with event: NSEvent) { let commandKey = NSEvent.ModifierFlags.command if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == commandKey { switch event.charactersIgnoringModifiers! { case "f": window!.makeFirstResponder(historySearchField) case "a": outlineView.selectAll(nil) default: break } } else if event.charactersIgnoringModifiers == "\u{7f}" { let entries = outlineView.selectedRowIndexes.compactMap { outlineView.item(atRow: $0) as? PlaybackHistory } HistoryController.shared.remove(entries) } } // MARK: NSOutlineViewDelegate @objc func doubleAction() { if let selected = outlineView.item(atRow: outlineView.clickedRow) as? PlaybackHistory { PlayerCore.activeOrNew.openURL(selected.url) } } func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { return item is String } func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool { return item is String } func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { if let item = item { return historyData[item as! String]!.count } else { return historyData.count } } func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { if let item = item { return historyData[item as! String]![index] } else { return historyDataKeys[index] } } func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? { if let entry = item as? PlaybackHistory { if tableColumn?.identifier == .time { return groupBy == .lastPlayed ? DateFormatter.localizedString(from: entry.addedDate, dateStyle: .none, timeStyle: .short) : DateFormatter.localizedString(from: entry.addedDate, dateStyle: .short, timeStyle: .short) } else if tableColumn?.identifier == .progress { return entry.duration.stringRepresentation } } return item } func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { if let identifier = tableColumn?.identifier { let view = outlineView.makeView(withIdentifier: identifier, owner: nil) if identifier == .filename { // Filename cell let entry = item as! PlaybackHistory let filenameView = (view as! HistoryFilenameCellView) let fileExists = !entry.url.isFileURL || FileManager.default.fileExists(atPath: entry.url.path) filenameView.textField?.stringValue = entry.url.isFileURL ? entry.name : entry.url.absoluteString filenameView.textField?.textColor = fileExists ? .controlTextColor : .disabledControlTextColor filenameView.docImage.image = NSWorkspace.shared.icon(forFileType: entry.url.pathExtension) } else if identifier == .progress { // Progress cell let entry = item as! PlaybackHistory let filenameView = (view as! HistoryProgressCellView) if let progress = entry.mpvProgress { filenameView.textField?.stringValue = progress.stringRepresentation filenameView.indicator.isHidden = false filenameView.indicator.doubleValue = (progress / entry.duration) ?? 0 } else { filenameView.textField?.stringValue = "" filenameView.indicator.isHidden = true } } return view } else { // group columns return outlineView.makeView(withIdentifier: .group, owner: nil) } } // MARK: - Searching @IBAction func searchFieldAction(_ sender: NSSearchField) { let searchString = sender.stringValue guard !searchString.isEmpty else { reloadData() return } let newObjects = HistoryController.shared.history.filter { entry in let string = searchOption == .filename ? entry.name : entry.url.path // Do a locale-aware, case and diacritic insensitive search: return string.localizedStandardContains(searchString) } prepareData(fromHistory: newObjects) outlineView.reloadData() outlineView.expandItem(nil, expandChildren: true) } // MARK: - Menu private var selectedEntries: [PlaybackHistory] = [] func menuNeedsUpdate(_ menu: NSMenu) { let selectedRow = outlineView.selectedRowIndexes let clickedRow = outlineView.clickedRow var indexSet = IndexSet() if menu.identifier == .contextMenu { if clickedRow != -1 { if selectedRow.contains(clickedRow) { indexSet = selectedRow } else { indexSet.insert(clickedRow) } } selectedEntries = indexSet.compactMap { outlineView.item(atRow: $0) as? PlaybackHistory } } } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { switch menuItem.tag { case MenuItemTagShowInFinder: if selectedEntries.isEmpty { return false } return selectedEntries.contains { FileManager.default.fileExists(atPath: $0.url.path) } case MenuItemTagDelete, MenuItemTagPlay, MenuItemTagPlayInNewWindow: return !selectedEntries.isEmpty case MenuItemTagSearchFilename: menuItem.state = searchOption == .filename ? .on : .off case MenuItemTagSearchFullPath: menuItem.state = searchOption == .fullPath ? .on : .off default: break } return menuItem.isEnabled } // MARK: - IBActions @IBAction func playAction(_ sender: AnyObject) { guard let firstEntry = selectedEntries.first else { return } PlayerCore.active.openURL(firstEntry.url) } @IBAction func playInNewWindowAction(_ sender: AnyObject) { guard let firstEntry = selectedEntries.first else { return } PlayerCore.newPlayerCore.openURL(firstEntry.url) } @IBAction func groupByChangedAction(_ sender: NSPopUpButton) { groupBy = SortOption(rawValue: sender.selectedTag()) ?? .lastPlayed reloadData() } @IBAction func showInFinderAction(_ sender: AnyObject) { let urls = selectedEntries.compactMap { FileManager.default.fileExists(atPath: $0.url.path) ? $0.url: nil } NSWorkspace.shared.activateFileViewerSelecting(urls) } @IBAction func deleteAction(_ sender: AnyObject) { Utility.quickAskPanel("delete_history", sheetWindow: window) { respond in guard respond == .alertFirstButtonReturn else { return } HistoryController.shared.remove(self.selectedEntries) } } @IBAction func searchOptionFilenameAction(_ sender: AnyObject) { searchOption = .filename } @IBAction func searchOptionFullPathAction(_ sender: AnyObject) { searchOption = .fullPath } } // MARK: - Other classes class HistoryFilenameCellView: NSTableCellView { @IBOutlet var docImage: NSImageView! } class HistoryProgressCellView: NSTableCellView { @IBOutlet var indicator: NSProgressIndicator! }
gpl-3.0
fd1f1700d2c277f18b370d4739e6cc78
31.686667
137
0.705181
4.69636
false
false
false
false
Webtrekk/webtrekk-ios-sdk
Source/Internal/CryptoSwift/UInt64+Extension.swift
1
2124
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, // and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /** array of bytes */ extension UInt64 { @_specialize(where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T) where T.Element == UInt8, T.Index == Int { self = UInt64(bytes: bytes, fromIndex: bytes.startIndex) } @_specialize(where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { if bytes.isEmpty { self = 0 return } let count = bytes.count let val0 = !bytes.isEmpty ? UInt64(bytes[index.advanced(by: 0)]) << 56 : 0 let val1 = count > 1 ? UInt64(bytes[index.advanced(by: 1)]) << 48 : 0 let val2 = count > 2 ? UInt64(bytes[index.advanced(by: 2)]) << 40 : 0 let val3 = count > 3 ? UInt64(bytes[index.advanced(by: 3)]) << 32 : 0 let val4 = count > 4 ? UInt64(bytes[index.advanced(by: 4)]) << 24 : 0 let val5 = count > 5 ? UInt64(bytes[index.advanced(by: 5)]) << 16 : 0 let val6 = count > 6 ? UInt64(bytes[index.advanced(by: 6)]) << 8 : 0 let val7 = count > 7 ? UInt64(bytes[index.advanced(by: 7)]) : 0 self = val0 | val1 | val2 | val3 | val4 | val5 | val6 | val7 } }
mit
ea4be829730c7b4cd58a577edddee8a6
46.177778
124
0.64861
3.698606
false
false
false
false
pkx0128/UIKit
MUITextField/MUITextField/ViewController.swift
1
1583
// // ViewController.swift // MUITextField // // Created by pankx on 2017/9/12. // Copyright © 2017年 pankx. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { override func viewDidLoad() { super.viewDidLoad() //创建UITextField let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 20)) //设置位置 myTextField.center = view.center //设置初始文字 myTextField.placeholder = "请输入用户名" //设置圆角输入框 myTextField.borderStyle = .roundedRect //设置编辑时显示清除按钮 myTextField.clearButtonMode = .whileEditing //设置键盘模式 myTextField.keyboardType = .emailAddress //设置键盘的return模式 myTextField.returnKeyType = .done //设置文字颜色 myTextField.textColor = UIColor.blue //设置背景颜色 myTextField.backgroundColor = UIColor.darkGray //设置代理 myTextField.delegate = self //增加到视图 view.addSubview(myTextField) } /// 设置返回按钮 func textFieldShouldReturn(_ textField: UITextField) -> Bool { view.endEditing(true) return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
05afaf4fe0e84a9222e60eb3fbdafa29
21.3125
88
0.577731
5.155235
false
false
false
false
kharrison/CodeExamples
Stacks/Stacks/AppDelegate.swift
1
3790
// // AppDelegate.swift // Stacks // // Created by Keith Harrison http://useyourloaf.com // Copyright (c) 2015 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { enum ShortcutIdentifier: String { case OpenFavorites case OpenFeatured case OpenTopRated init?(fullIdentifier: String) { guard let shortIdentifier = fullIdentifier.components(separatedBy: ".").last else { return nil } self.init(rawValue: shortIdentifier) } } var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if let shortcutItem = launchOptions?[UIApplication.LaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem { handleShortcut(shortcutItem) return false } return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { completionHandler(handleShortcut(shortcutItem)) } @discardableResult private func handleShortcut(_ shortcutItem: UIApplicationShortcutItem) -> Bool { let shortcutType = shortcutItem.type guard let shortcutIdentifier = ShortcutIdentifier(fullIdentifier: shortcutType) else { return false } return selectTabBarItemForIdentifier(shortcutIdentifier) } private func selectTabBarItemForIdentifier(_ identifier: ShortcutIdentifier) -> Bool { guard let tabBarController = self.window?.rootViewController as? UITabBarController else { return false } switch (identifier) { case .OpenFavorites: tabBarController.selectedIndex = 0 return true case .OpenFeatured: tabBarController.selectedIndex = 1 return true case .OpenTopRated: tabBarController.selectedIndex = 2 return true } } }
bsd-3-clause
65f91a4ccac2f85c5be53b04153d4aba
36.9
145
0.686544
5.453237
false
false
false
false
GenerallyHelpfulSoftware/Scalar2D
Example/Scalar2D Test App/AnimatingFrogViewController.swift
1
2912
// // AnimatingFrogViewController.swift // Scalar2D iOS Test App // // Created by Glenn Howes on 1/3/19. // Copyright © 2019 Generally Helpful Software. All rights reserved. // // // // The MIT License (MIT) // Copyright (c) 2016-2019 Generally Helpful Software // 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 Scalar2D_UIKitViews class AnimatingFrogViewController: UIViewController { @IBOutlet var frogView: PathView! @IBOutlet var strokeView: PathView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let duration: CFTimeInterval = 3.0 self.strokeView.shapeLayer.strokeEnd = 0.0 // so it doesn't disappear after the animation let strokeAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeAnimation.fromValue = 1.0 strokeAnimation.toValue = 0.0 strokeAnimation.beginTime = 0 strokeAnimation.duration = duration strokeAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) strokeAnimation.fillMode = CAMediaTimingFillMode.forwards let group = CAAnimationGroup() group.animations = [strokeAnimation] group.duration = duration // 6) self.strokeView.shapeLayer.add(group, forKey: "move") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
mit
2496b16dff1a2d2581cf915a1c363841
35.3875
109
0.702851
4.680064
false
false
false
false
Romdeau4/16POOPS
iOS_app/Help's Kitchen/HomeViewController.swift
1
3601
// // HomeViewController.swift // Help's Kitchen // // Created by Stephen Ulmer on 2/13/17. // Copyright © 2017 Stephen Ulmer. All rights reserved. // import UIKit import Firebase class HomeViewController: UIViewController { let ref = FIRDatabase.database().reference(fromURL: "https://helps-kitchen.firebaseio.com/") override func viewDidLoad() { super.viewDidLoad() checkStatus() } override func viewDidAppear(_ animated: Bool){ checkStatus() } func checkStatus() { let uid = FIRAuth.auth()?.currentUser?.uid if uid == nil { handleLogout() }else{ ref.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in let values = snapshot.value as? [String : AnyObject] let userType = values?["userType"] as! String if userType == "customer" { let customerHasReservation = values?["customerHasReservation"] as! Bool let customerIsSeated = values?["customerIsSeated"] as! Bool if customerHasReservation { if customerIsSeated { let tableStatusController = SeatedViewController() let navController = CustomNavigationController(rootViewController: tableStatusController) self.present(navController, animated: true, completion: nil) }else{ let waitingController = WaitingViewController() let navController = CustomNavigationController(rootViewController: waitingController) self.present(navController, animated: true, completion: nil) } }else{ let reservationController = ReservationViewController() let navController = CustomNavigationController(rootViewController: reservationController) self.present(navController, animated: true, completion: nil) } }else if userType == "host" { let hostController = HostSeatingController() let navController = CustomNavigationController(rootViewController: hostController) self.present(navController, animated: true, completion: nil) }else if userType == "server" { let serverController = ServerTableController() let navController = CustomNavigationController(rootViewController: serverController) self.present(navController, animated: true, completion: nil) } }) } } func handleLogout() { do{ try FIRAuth.auth()?.signOut() }catch let logoutError { print(logoutError) } let loginViewController = LoginViewController() present(loginViewController, animated: true, completion: nil) } }
mit
b867a72acb60d28a93f5cfa6a89f5c38
34.643564
117
0.49
6.949807
false
false
false
false
tutsplus/iOS-3DTouch-Introduction-Starter
Introducing 3D Touch/MasterViewController.swift
1
3758
// // MasterViewController.swift // Introducing 3D Touch // // Created by Davis Allie on 24/10/2015. // Copyright © 2015 tutsplus. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() @IBOutlet weak var peek: UIButton! var forceButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() self.forceButton = self.peek self.forceButton.setTitle("Force", forState: .Normal) let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
bsd-2-clause
44aaf223def9186f292137e28694171c
36.949495
157
0.691509
5.632684
false
false
false
false
alvinvarghese/DeLorean
DeLorean/iOS/CoreLocation.swift
1
10295
// // CoreLocation.swift // DeLorean // // Created by Junior B. on 27/03/15. // Copyright (c) 2015 Bonto.ch. All rights reserved. // import CoreLocation public struct CLLocationManagerEvent : RawOptionSetType, BooleanType { private var value: UInt init(_ rawValue: UInt) { self.value = rawValue } // MARK: _RawOptionSetType public init(rawValue: UInt) { self.value = rawValue } // MARK: NilLiteralConvertible public init(nilLiteral: ()) { self.value = 0} // MARK: RawRepresentable public var rawValue: UInt { return self.value } // MARK: BooleanType public var boolValue: Bool { return self.value != 0 } // MARK: BitwiseOperationsType public static var allZeros: CLLocationManagerEvent { return self(0) } // MARK: User defined bit values public static var None: CLLocationManagerEvent { return self(0) } public static var AuthorizationDidChange: CLLocationManagerEvent { return self(1 << 0) } public static var LocationsUpdated: CLLocationManagerEvent { return self(1 << 1) } public static var BeaconsRanged: CLLocationManagerEvent { return self(1 << 2) } public static var RegionEntered: CLLocationManagerEvent { return self(1 << 3) } public static var RegionExited: CLLocationManagerEvent { return self(1 << 4) } public static var MonitoringStarted: CLLocationManagerEvent { return self(1 << 5) } public static var MonitoringStopped: CLLocationManagerEvent { return self(1 << 6) } public static var ManagerPaused: CLLocationManagerEvent { return self(1 << 7) } public static var ManagerResumed: CLLocationManagerEvent { return self(1 << 8) } public static var All: CLLocationManagerEvent { return self(0b11111111) } } /** BeaconEvent is a special case of event having CLLocationManagerEvent as key, an instance of CLLocationManager as source and a Region reference. */ public final class BeaconEvent<R>: SourceEvent<CLLocationManager, CLLocationManagerEvent, [CLBeacon]> { let region: R public init(_ k: CLLocationManagerEvent, _ v: [CLBeacon], _ s:CLLocationManager, _ r:R) { region = r super.init(k, v, s) } } /** LocationEvent is a special case of event having CLLocationManagerEvent as key and, as source, an instance of CLLocationManager. */ public class LocationEvent<V>: SourceEvent<CLLocationManager, CLLocationManagerEvent, V> { public override init(_ k: CLLocationManagerEvent, _ v: V, _ s: CLLocationManager) { super.init(k, v, s) } } extension CLLocationManager { private struct AssociatedKeys { static var AuthorizationEmitterKey = "CLLocationManager_AuthorizationEmitter" static var LocationsEmitterKey = "CLLocationManager_LocationsEmitter" static var BeaconsEmitterKey = "CLLocationManager_BeaconsEmitter" static var RegionEmitterKey = "CLLocationManager_RegionEmitter" static var ProxyKey = "CLLocationManager_Proxy" } /// Returns an emitter for locations public var locationsEmitter: Emitter<LocationEvent<[CLLocation]>> { get { if let e = objc_getAssociatedObject(self, &AssociatedKeys.LocationsEmitterKey) as? Emitter<LocationEvent<[CLLocation]>> { return e } let e = Emitter<LocationEvent<[CLLocation]>>(scheduler: Scheduler.UIScheduler) self.proxy.locationsEmitter = e objc_setAssociatedObject(self, &AssociatedKeys.LocationsEmitterKey, e, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return e } set { objc_setAssociatedObject(self, &AssociatedKeys.LocationsEmitterKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } /// Returns an emitter for authorizations public var authorizationEmitter: Emitter<LocationEvent<CLAuthorizationStatus>> { get { if let e = objc_getAssociatedObject(self, &AssociatedKeys.AuthorizationEmitterKey) as? Emitter<LocationEvent<CLAuthorizationStatus>> { return e } let e = Emitter<LocationEvent<CLAuthorizationStatus>>(scheduler: Scheduler.UIScheduler) self.proxy.authorizationEmitter = e objc_setAssociatedObject(self, &AssociatedKeys.AuthorizationEmitterKey, e, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return e } set { objc_setAssociatedObject(self, &AssociatedKeys.AuthorizationEmitterKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } /// Returns an emitter for beacons public var beaconRegionEmitter: Emitter<BeaconEvent<CLBeaconRegion>> { get { if let be = objc_getAssociatedObject(self, &AssociatedKeys.BeaconsEmitterKey) as? Emitter<BeaconEvent<CLBeaconRegion>> { return be } let be = Emitter<BeaconEvent<CLBeaconRegion>>(scheduler: Scheduler.UIScheduler) self.proxy.beaconEmitter = be objc_setAssociatedObject(self, &AssociatedKeys.BeaconsEmitterKey, be, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return be } set { objc_setAssociatedObject(self, &AssociatedKeys.BeaconsEmitterKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } /// Returns an emiter for regions public var regionEmitter: Emitter<LocationEvent<CLRegion>> { get { if let re = objc_getAssociatedObject(self, &AssociatedKeys.RegionEmitterKey) as? Emitter<LocationEvent<CLRegion>> { return re } let re = Emitter<LocationEvent<CLRegion>>(scheduler: Scheduler.UIScheduler) self.proxy.regionEmitter = re objc_setAssociatedObject(self, &AssociatedKeys.RegionEmitterKey, re, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return re } set { objc_setAssociatedObject(self, &AssociatedKeys.RegionEmitterKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } private var proxy: CLLocationManagerProxy { get { if let p = objc_getAssociatedObject(self, &AssociatedKeys.ProxyKey) as? CLLocationManagerProxy { return p } let p = CLLocationManagerProxy(self) objc_setAssociatedObject(self, &AssociatedKeys.ProxyKey, p, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return p } set { objc_setAssociatedObject(self, &AssociatedKeys.ProxyKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } } internal class CLLocationManagerProxy: NSObject, CLLocationManagerDelegate { internal weak var locationsEmitter: Emitter<LocationEvent<[CLLocation]>>? internal weak var authorizationEmitter: Emitter<LocationEvent<CLAuthorizationStatus>>? internal weak var beaconEmitter: Emitter<BeaconEvent<CLBeaconRegion>>? internal weak var regionEmitter: Emitter<LocationEvent<CLRegion>>? init(_ manager: CLLocationManager) { super.init() manager.delegate = self } // Authorization Status Emitter func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { self.authorizationEmitter?.emit(LocationEvent(.AuthorizationDidChange, status, manager)) } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { self.locationsEmitter?.emit(LocationEvent(.LocationsUpdated, locations as! [CLLocation], manager)) } func locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!) { } func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) { } func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { self.beaconEmitter?.emit(BeaconEvent(.BeaconsRanged, beacons as! [CLBeacon], manager, region)) } func locationManager(manager: CLLocationManager!, rangingBeaconsDidFailForRegion region: CLBeaconRegion!, withError error: NSError!) { // Emit an empty array so we know what region was causing the problem self.beaconEmitter?.emit(BeaconEvent(.None, Array<CLBeacon>(), manager, region)) self.beaconEmitter?.error(error) } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { self.regionEmitter?.emit(LocationEvent(.RegionEntered, region, manager)) } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { self.regionEmitter?.emit(LocationEvent(.RegionExited, region, manager)) } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { self.regionEmitter?.error(error) } func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) { } func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) { self.regionEmitter?.emit(LocationEvent(.MonitoringStarted, region, manager)) } func locationManagerDidPauseLocationUpdates(manager: CLLocationManager!) { self.regionEmitter?.emit(LocationEvent(.ManagerPaused, CLRegion(), manager)) } func locationManagerDidResumeLocationUpdates(manager: CLLocationManager!) { self.regionEmitter?.emit(LocationEvent(.ManagerResumed, CLRegion(), manager)) } func locationManager(manager: CLLocationManager!, didFinishDeferredUpdatesWithError error: NSError!) { self.beaconEmitter?.error(error) self.locationsEmitter?.error(error) self.regionEmitter?.error(error) } func locationManager(manager: CLLocationManager!, didVisit visit: CLVisit!) { } }
mit
e8926c8ca0e77c0667e802e2a20edd16
43.37931
152
0.687712
5.181178
false
false
false
false
yo-op/sketchcachecleaner
Sketch Cache Cleaner/Controllers/MainViewController.swift
1
5797
// // ViewController.swift // Sketch Cache Cleaner // // Created by Sasha Prokhorenko on 2/6/17. // Copyright © 2017 Sasha Prokhorenko. All rights reserved. // import Cocoa final class MainViewController: NSViewController { // MARK: - IBOutlets @IBOutlet private var backgroundView: NSView! @IBOutlet private var button: NSButton! @IBOutlet private var shareToTweeterButton: NSButton! @IBOutlet private var shareToFaceBookButton: NSButton! @IBOutlet private var mainImage: NSImageView! @IBOutlet private var backgroundImage: NSImageView! @IBOutlet private var cacheCleared: NSImageView! @IBOutlet private var notificationLabel: NSTextField! @IBOutlet private var sketchLabel: NSTextField! @IBOutlet private var progress: NSProgressIndicator! // MARK: - Instance Properties private var permissionGranted = false private var stringToTest = "" private let privilegedTask = STPrivilegedTask() private let bashPath = Environment.bashPath private let calculateCacheSizeTask = [Environment.calculateCacheScriptPath] private let clearCacheTask = [Environment.clearCacheScriptPath] // MARK: - ViewController lifecycle override func viewDidLoad() { super.viewDidLoad() configureInitialVCState() } override func viewWillAppear() { super.viewWillAppear() additionalVCConfigure() } // MARK: - Initial state private func configureInitialVCState() { backgroundImage.isHidden = true cacheCleared.isHidden = true notificationLabel.isHidden = true shareToTweeterButton.isHidden = true shareToFaceBookButton.isHidden = true } private func additionalVCConfigure() { view.window?.titlebarAppearsTransparent = true view.window?.backgroundColor = Colors.background view.window?.contentView?.setFrameSize(CGSize(width: (view.window?.contentView?.frame.width)!, height: (view.window?.contentView?.frame.height)! + 20)) NSButton.setButton(button, title: ButtonText.enableAndScan) } private func appState() { switch (permissionGranted, button.title) { case (false, ButtonText.enableAndScan): button.title = ButtonText.enableAndScan askPermission() case (true, ButtonText.scanning): checkSizeOfCache() case (true, stringToTest): clearCache() default: break } } // MARK: - Helpers private func askPermission() { privilegedTask.launchPath = bashPath privilegedTask.arguments = calculateCacheSizeTask privilegedTask.currentDirectoryPath = Bundle.main.resourcePath let err = privilegedTask.launch() if err != errAuthorizationSuccess { if err == errAuthorizationCanceled { permissionGranted = false return } else { print("Something went wrong:", err) // For error codes, see http://www.opensource.apple.com/source/libsecurity_authorization/libsecurity_authorization-36329/lib/Authorization.h } } privilegedTask.waitUntilExit() permissionGranted = true backgroundImage.isHidden = false progress.startAnimation(self) button.isEnabled = false NSButton.setButton(button, title: ButtonText.scanning) mainImage.cell?.image = #imageLiteral(resourceName: "closedBox") DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { self.button.isEnabled = true self.checkSizeOfCache() } } private func checkSizeOfCache() { progress.stopAnimation(self) let readHandle = privilegedTask.outputFileHandle let outputData = readHandle?.readDataToEndOfFile() let outputString = String(data: outputData!, encoding: .utf8) let stringArray = outputString?.components(separatedBy: "/") guard let stringToDispaly = stringArray?[0] else { return } if stringToDispaly.trim() == "0B" || stringToDispaly == "" { finalUIState() } else { stringToTest = "Clear \(stringToDispaly.trim())B" NSButton.setButton(button, title: "Clear \(stringToDispaly.trim())B") mainImage.cell?.image = #imageLiteral(resourceName: "boxWithSketch") notificationLabel.isHidden = false } } private func clearCache() { privilegedTask.launchPath = bashPath privilegedTask.arguments = clearCacheTask privilegedTask.currentDirectoryPath = Bundle.main.resourcePath let err = privilegedTask.launch() if err != errAuthorizationSuccess { if err == errAuthorizationCanceled { print("User cancelled", permissionGranted) return } else { print("Something went wrong:", err) } } privilegedTask.waitUntilExit() finalUIState() } private func finalUIState() { mainImage.cell?.image = #imageLiteral(resourceName: "openBox") button.isHidden = true cacheCleared.isHidden = false notificationLabel.isHidden = true shareToTweeterButton.isHidden = false shareToFaceBookButton.isHidden = false } // MARK: - Actions @IBAction private func buttonPressed(_: NSButton) { appState() } @IBAction private func shareToTweeterDidPress(_: NSButton) { NSWorkspace.shared.open(Share.twitterMessage(stringToTest)) } @IBAction private func shareToFacebookrDidPress(_: NSButton) { NSWorkspace.shared.open(Share.facebookMessage(stringToTest)) } }
mit
e181a8dd44bd2a84c73a36568cba831d
34.558282
156
0.650794
5.026886
false
false
false
false
cylof22/GitRest
GistsRest/GistsRest/MasterViewController.swift
1
10115
// // MasterViewController.swift // GistsRest // // Created by 曹元乐 on 2017/3/11. // Copyright © 2017年 曹元乐. All rights reserved. // import UIKit import SafariServices class MasterViewController: UITableViewController, LoginViewDelegate, SFSafariViewControllerDelegate { var safariViewController : SFSafariViewController? var detailViewController: DetailViewController? = nil var gists = [Gist]() var nextPageURLString : String? var isLoading = false var dateFormatter = DateFormatter() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } let defaults = UserDefaults.standard defaults.set(false, forKey: "loadingOAuthToken") } override func viewWillAppear(_ animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed if( self.refreshControl == nil) { self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: #selector(MasterViewController.refresh(sender:)), for: UIControlEvents.valueChanged) self.dateFormatter.dateStyle = DateFormatter.Style.short self.dateFormatter.timeStyle = DateFormatter.Style.long } let defaults = UserDefaults.standard if(!defaults.bool(forKey: "loadingOAuthToken")) { loadInitialData() } // initial the gist view if(nextPageURLString == nil) { loadGists(urlToLoad: nil) } super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(_ sender: Any) { let alert = UIAlertController(title : "Not implemented", message : "Can't create a new gists yet, will implment later", preferredStyle : UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title : "Ok", style : UIAlertActionStyle.default, handler : nil)) self.present(alert, animated : true, completion : nil) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let gist = gists[indexPath.row] let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = gist controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return gists.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let gist = gists[indexPath.row] cell.textLabel!.text = gist.m_description cell.detailTextLabel!.text = gist.m_ownerLogin if let url = gist.m_ownerAvatorURL { GitHubAPIManager.sharedInstance.imageFromURLString(imageURLString: url, completionHandler: { (image, requestError) in if let error = requestError { print(error) } if let cellUpdate = self.tableView?.cellForRow(at: indexPath) { cellUpdate.imageView?.image = image cellUpdate.setNeedsLayout() } }) } else { cell.imageView?.image = nil } let rowsToLoadFromBotton = 5; let rowsLoaded = gists.count if let nextPage = nextPageURLString { if (!isLoading && (indexPath.row >= (rowsLoaded - rowsToLoadFromBotton))) { self.loadGists(urlToLoad: nextPage) } } return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { gists.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } func loadGists(urlToLoad : String?) { if(!GitHubAPIManager.sharedInstance.hasOAuthToken()) { return } self.isLoading = true; GitHubAPIManager.sharedInstance.getMineGists(pageToLoad: urlToLoad) { (result, nextPage) in self.nextPageURLString = nextPage self.isLoading = false if(self.refreshControl != nil && self.refreshControl!.isRefreshing) { self.refreshControl!.endRefreshing() } guard result.error == nil else { print(result.error!) return } if let fetchedGists = result.value { if self.nextPageURLString == nil { self.gists = fetchedGists } else { self.gists += fetchedGists } } let now = Date() let updateString = "Last Updated at " + self.dateFormatter.string(from: now) self.refreshControl?.attributedTitle = NSAttributedString(string : updateString) self.tableView.reloadData() } } func loadInitialData() { self.isLoading = true GitHubAPIManager.sharedInstance.OAuthTokenCompletionHandler = { (error) -> Void in self.safariViewController?.dismiss(animated: true, completion: nil) if let error = error { print(error) self.isLoading = false self.showOAuthLoginView() } else { self.loadGists(urlToLoad: nil) } } if(!GitHubAPIManager.sharedInstance.hasOAuthToken()) { showOAuthLoginView() } else { self.loadGists(urlToLoad: nil) } } func refresh(sender : AnyObject) { let defaults = UserDefaults.standard defaults.set(false, forKey: "loadingOAuthToken") nextPageURLString = nil loadInitialData() } func showOAuthLoginView() { let storyBoard = UIStoryboard(name : "Main", bundle : Bundle.main) if let loginVC = storyBoard.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController { loginVC.m_delegate = self self.present(loginVC, animated: true, completion: nil) } } func didTapLoginButton() { let defaults = UserDefaults.standard defaults.set(true, forKey: "loadingOAuthToken") self.dismiss(animated: false, completion: nil) if let authURL = GitHubAPIManager.sharedInstance.urlToStartOAuth2Login() { safariViewController = SFSafariViewController(url:authURL as URL) safariViewController?.delegate = self if safariViewController != nil { self.present(safariViewController!, animated: true, completion: nil) } } else { defaults.set(false, forKey: "loadingOAuthToken") if let completionHandler = GitHubAPIManager.sharedInstance.OAuthTokenCompletionHandler { let error = NSError(domain: GitHubAPIManager.ErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "Couldn't create an OAuth authorization URL", NSLocalizedRecoverySuggestionErrorKey: "Please retry your request"]) completionHandler(error) } } } func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true, completion: nil) } // func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) { // // Detect not being able to load the OAuth URL // if (!didLoadSuccessfully) { // let defaults = UserDefaults.standard // defaults.set(false, forKey: "loadingOAuthToken") // if let completionHandler = GitHubAPIManager.sharedInstance.OAuthTokenCompletionHandler { // let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet, // userInfo: [NSLocalizedDescriptionKey: "No Internet Connection", // NSLocalizedRecoverySuggestionErrorKey: "Please retry your request"]) // completionHandler(error) // } // controller.dismiss(animated: true, completion: nil) // } // } }
mit
3749e23a7d5aa04424e7a3b6fd5408b6
38.147287
174
0.617624
5.59247
false
false
false
false
lzbgithubcode/LZBPageView
LZBPageView/LZBPageView/LZBPageView/LZBPageView.swift
1
1913
// // LZBPageView.swift // LZBPageView // // Created by zibin on 2017/5/12. // Copyright © 2017年 项目共享githud地址:https://github.com/lzbgithubcode/LZBPageView 简书详解地址:http://www.jianshu.com/p/3170d0d886a2 作者喜欢分享技术与开发资料,如果你也是喜欢分享的人可以加入我们iOS资料demo共享群:490658347. All rights reserved. // import UIKit class LZBPageView: UIView { //MARK - 属性保存 var titles : [String] var pageStyle : LZBPageStyleModel var childVcs : [UIViewController] var parentVc : UIViewController init(frame: CGRect, titles : [String], pageStyle : LZBPageStyleModel, childVcs : [UIViewController] , parentVc: UIViewController) { self.titles = titles self.pageStyle = pageStyle self.childVcs = childVcs self.parentVc = parentVc super.init(frame:frame) self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: UI初始化 extension LZBPageView { fileprivate func setupUI(){ //1.创建titleView let titleViewFrame = CGRect(x: 0, y: 0, width: bounds.width, height: self.pageStyle.titleViewHeight) let titleView = LZBTitleView(frame: titleViewFrame, titles: self.titles, style: self.pageStyle) titleView.backgroundColor = UIColor.orange self.addSubview(titleView) //2.创建内容View let contentFrame = CGRect(x: 0, y: titleView.frame.maxY, width: bounds.width, height: bounds.height - titleView.frame.maxY) let contentView = LZBContentView(frame: contentFrame, childVcs: childVcs, parentVc: parentVc, style: pageStyle) contentView.backgroundColor = UIColor.blue self.addSubview(contentView) //3.设置代理对象 titleView.delegate = contentView contentView.delegate = titleView } }
apache-2.0
9d89fd84af9aa89de648d6bc71770210
33.038462
201
0.697175
3.75
false
false
false
false
nathawes/swift
stdlib/public/core/ReflectionMirror.swift
5
9719
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // //===----------------------------------------------------------------------===// @_silgen_name("swift_isClassType") internal func _isClassType(_: Any.Type) -> Bool @_silgen_name("swift_getMetadataKind") internal func _metadataKind(_: Any.Type) -> UInt @_silgen_name("swift_reflectionMirror_normalizedType") internal func _getNormalizedType<T>(_: T, type: Any.Type) -> Any.Type @_silgen_name("swift_reflectionMirror_count") internal func _getChildCount<T>(_: T, type: Any.Type) -> Int @_silgen_name("swift_reflectionMirror_recursiveCount") internal func _getRecursiveChildCount(_: Any.Type) -> Int @_silgen_name("swift_reflectionMirror_recursiveChildMetadata") internal func _getChildMetadata( _: Any.Type, index: Int, outName: UnsafeMutablePointer<UnsafePointer<CChar>?>, outFreeFunc: UnsafeMutablePointer<NameFreeFunc?> ) -> Any.Type @_silgen_name("swift_reflectionMirror_recursiveChildOffset") internal func _getChildOffset( _: Any.Type, index: Int ) -> Int internal typealias NameFreeFunc = @convention(c) (UnsafePointer<CChar>?) -> Void @_silgen_name("swift_reflectionMirror_subscript") internal func _getChild<T>( of: T, type: Any.Type, index: Int, outName: UnsafeMutablePointer<UnsafePointer<CChar>?>, outFreeFunc: UnsafeMutablePointer<NameFreeFunc?> ) -> Any // Returns 'c' (class), 'e' (enum), 's' (struct), 't' (tuple), or '\0' (none) @_silgen_name("swift_reflectionMirror_displayStyle") internal func _getDisplayStyle<T>(_: T) -> CChar internal func getChild<T>(of value: T, type: Any.Type, index: Int) -> (label: String?, value: Any) { var nameC: UnsafePointer<CChar>? = nil var freeFunc: NameFreeFunc? = nil let value = _getChild(of: value, type: type, index: index, outName: &nameC, outFreeFunc: &freeFunc) let name = nameC.flatMap({ String(validatingUTF8: $0) }) freeFunc?(nameC) return (name, value) } #if _runtime(_ObjC) @_silgen_name("swift_reflectionMirror_quickLookObject") internal func _getQuickLookObject<T>(_: T) -> AnyObject? @_silgen_name("_swift_stdlib_NSObject_isKindOfClass") internal func _isImpl(_ object: AnyObject, kindOf: UnsafePointer<CChar>) -> Bool internal func _is(_ object: AnyObject, kindOf `class`: String) -> Bool { return `class`.withCString { return _isImpl(object, kindOf: $0) } } internal func _getClassPlaygroundQuickLook( _ object: AnyObject ) -> _PlaygroundQuickLook? { if _is(object, kindOf: "NSNumber") { let number: _NSNumber = unsafeBitCast(object, to: _NSNumber.self) switch UInt8(number.objCType[0]) { case UInt8(ascii: "d"): return .double(number.doubleValue) case UInt8(ascii: "f"): return .float(number.floatValue) case UInt8(ascii: "Q"): return .uInt(number.unsignedLongLongValue) default: return .int(number.longLongValue) } } if _is(object, kindOf: "NSAttributedString") { return .attributedString(object) } if _is(object, kindOf: "NSImage") || _is(object, kindOf: "UIImage") || _is(object, kindOf: "NSImageView") || _is(object, kindOf: "UIImageView") || _is(object, kindOf: "CIImage") || _is(object, kindOf: "NSBitmapImageRep") { return .image(object) } if _is(object, kindOf: "NSColor") || _is(object, kindOf: "UIColor") { return .color(object) } if _is(object, kindOf: "NSBezierPath") || _is(object, kindOf: "UIBezierPath") { return .bezierPath(object) } if _is(object, kindOf: "NSString") { return .text(_forceBridgeFromObjectiveC(object, String.self)) } return .none } #endif extension Mirror { internal struct ReflectedChildren: RandomAccessCollection { let subject: Any let subjectType: Any.Type var startIndex: Int { 0 } var endIndex: Int { _getChildCount(subject, type: subjectType) } subscript(index: Int) -> Child { getChild(of: subject, type: subjectType, index: index) } } internal init( internalReflecting subject: Any, subjectType: Any.Type? = nil, customAncestor: Mirror? = nil ) { let subjectType = subjectType ?? _getNormalizedType(subject, type: type(of: subject)) self._children = _Children( ReflectedChildren(subject: subject, subjectType: subjectType)) self._makeSuperclassMirror = { guard let subjectClass = subjectType as? AnyClass, let superclass = _getSuperclass(subjectClass) else { return nil } // Handle custom ancestors. If we've hit the custom ancestor's subject type, // or descendants are suppressed, return it. Otherwise continue reflecting. if let customAncestor = customAncestor { if superclass == customAncestor.subjectType { return customAncestor } if customAncestor._defaultDescendantRepresentation == .suppressed { return customAncestor } } return Mirror(internalReflecting: subject, subjectType: superclass, customAncestor: customAncestor) } let rawDisplayStyle = _getDisplayStyle(subject) switch UnicodeScalar(Int(rawDisplayStyle)) { case "c": self.displayStyle = .class case "e": self.displayStyle = .enum case "s": self.displayStyle = .struct case "t": self.displayStyle = .tuple case "\0": self.displayStyle = nil default: preconditionFailure("Unknown raw display style '\(rawDisplayStyle)'") } self.subjectType = subjectType self._defaultDescendantRepresentation = .generated } internal static func quickLookObject(_ subject: Any) -> _PlaygroundQuickLook? { #if _runtime(_ObjC) let object = _getQuickLookObject(subject) return object.flatMap(_getClassPlaygroundQuickLook) #else return nil #endif } } /// Options for calling `_forEachField(of:options:body:)`. @available(macOS 10.15.4, iOS 13.4, tvOS 13.4, watchOS 6.2, *) @_spi(Reflection) public struct _EachFieldOptions: OptionSet { public var rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } /// Require the top-level type to be a class. /// /// If this is not set, the top-level type is required to be a struct or /// tuple. public static var classType = _EachFieldOptions(rawValue: 1 << 0) /// Ignore fields that can't be introspected. /// /// If not set, the presence of things that can't be introspected causes /// the function to immediately return `false`. public static var ignoreUnknown = _EachFieldOptions(rawValue: 1 << 1) } /// The metadata "kind" for a type. @available(macOS 10.15.4, iOS 13.4, tvOS 13.4, watchOS 6.2, *) @_spi(Reflection) public enum _MetadataKind: UInt { // With "flags": // runtimePrivate = 0x100 // nonHeap = 0x200 // nonType = 0x400 case `class` = 0 case `struct` = 0x200 // 0 | nonHeap case `enum` = 0x201 // 1 | nonHeap case optional = 0x202 // 2 | nonHeap case foreignClass = 0x203 // 3 | nonHeap case opaque = 0x300 // 0 | runtimePrivate | nonHeap case tuple = 0x301 // 1 | runtimePrivate | nonHeap case function = 0x302 // 2 | runtimePrivate | nonHeap case existential = 0x303 // 3 | runtimePrivate | nonHeap case metatype = 0x304 // 4 | runtimePrivate | nonHeap case objcClassWrapper = 0x305 // 5 | runtimePrivate | nonHeap case existentialMetatype = 0x306 // 6 | runtimePrivate | nonHeap case heapLocalVariable = 0x400 // 0 | nonType case heapGenericLocalVariable = 0x500 // 0 | nonType | runtimePrivate case errorObject = 0x501 // 1 | nonType | runtimePrivate case unknown = 0xffff init(_ type: Any.Type) { let v = _metadataKind(type) if let result = _MetadataKind(rawValue: v) { self = result } else { self = .unknown } } } /// Calls the given closure on every field of the specified type. /// /// If `body` returns `false` for any field, no additional fields are visited. /// /// - Parameters: /// - type: The type to inspect. /// - options: Options to use when reflecting over `type`. /// - body: A closure to call with information about each field in `type`. /// The parameters to `body` are a pointer to a C string holding the name /// of the field, the offset of the field in bytes, the type of the field, /// and the `_MetadataKind` of the field's type. /// - Returns: `true` if every invocation of `body` returns `true`; otherwise, /// `false`. @available(macOS 10.15.4, iOS 13.4, tvOS 13.4, watchOS 6.2, *) @discardableResult @_spi(Reflection) public func _forEachField( of type: Any.Type, options: _EachFieldOptions = [], body: (UnsafePointer<CChar>, Int, Any.Type, _MetadataKind) -> Bool ) -> Bool { // Require class type iff `.classType` is included as an option if _isClassType(type) != options.contains(.classType) { return false } let childCount = _getRecursiveChildCount(type) for i in 0..<childCount { let offset = _getChildOffset(type, index: i) var nameC: UnsafePointer<CChar>? = nil var freeFunc: NameFreeFunc? = nil let childType = _getChildMetadata( type, index: i, outName: &nameC, outFreeFunc: &freeFunc) defer { freeFunc?(nameC) } let kind = _MetadataKind(childType) if !body(nameC!, offset, childType, kind) { return false } } return true }
apache-2.0
7ca22b29935c99fd8d0278086d49f18f
31.723906
101
0.661899
3.925283
false
false
false
false
nathawes/swift
test/Parse/omit_return.swift
10
31565
// RUN: %target-swift-frontend %s -typecheck -verify // MARK: - Helpers @discardableResult func logAndReturn<T : CustomStringConvertible>(_ t: T) -> String { let log = "\(t)" print(log) return log } @discardableResult func failableLogAndReturn<T : CustomStringConvertible>(_ t: T) throws -> String { let log = "\(t)" print(log) return log } typealias MyOwnVoid = () func failableIdentity<T>(_ t: T) throws -> T { t } enum MyOwnNever {} func myOwnFatalError() -> MyOwnNever { fatalError() } struct MyOwnInt : ExpressibleByIntegerLiteral { init(integerLiteral: Int) {} } struct MyOwnFloat : ExpressibleByFloatLiteral { init(floatLiteral: Double) {} } struct MyOwnBoolean : ExpressibleByBooleanLiteral { init(booleanLiteral: Bool) {} } struct MyOwnString : ExpressibleByStringLiteral { init(stringLiteral: String) {} } struct MyOwnInterpolation : ExpressibleByStringInterpolation { init(stringLiteral: String) {} } enum Unit { case only } struct Initable {} struct StructWithProperty { var foo: Int } @dynamicMemberLookup struct DynamicStruct { subscript(dynamicMember input: String) -> String { return input } } struct MyOwnArray<Element> : ExpressibleByArrayLiteral { init(arrayLiteral elements: Element...) {} } struct MyOwnDictionary<Key, Value> : ExpressibleByDictionaryLiteral { init(dictionaryLiteral elements: (Key, Value)...) {} } struct SubscriptableStruct { subscript(int: Int) -> Int { int } } extension Int { var zero: Int { 0 } } extension Optional where Wrapped == Int { var someZero: Int? { .some(0) } } protocol SomeProto { func foo() -> String } struct SomeProtoConformer : SomeProto { func foo() -> String { "howdy" } } class Base {} class Derived : Base {} extension Int { init() { self = 0 } } // MARK: - Notable Free Functions func identity<T>(_ t: T) -> T { t } internal func _fatalErrorFlags() -> UInt32 { return 0 } internal func _assertionFailure( _ prefix: StaticString, _ message: String, flags: UInt32 ) -> Never { fatalError() } internal func _diagnoseUnexpectedEnumCaseValue<SwitchedValue, RawValue>( type: SwitchedValue.Type, rawValue: RawValue ) -> Never { _assertionFailure("Fatal error", "unexpected enum case '\(type)(rawValue: \(rawValue))'", flags: _fatalErrorFlags()) } // MARK: - Free Functions func ff_nop() { } func ff_missing() -> String { } func ff_implicit() -> String { "hello" } func ff_explicit() -> String { return "hello" } func ff_explicitClosure() -> () -> Void { return { print("howdy") } } func ff_implicitClosure() -> () -> Void { { print("howdy") } } func ff_explicitMultilineClosure() -> () -> String { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } func ff_implicitMultilineClosure() -> () -> String { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } func ff_implicitWrong() -> String { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } func ff_explicitWrong() -> String { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } func ff_implicitMulti() -> String { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } func ff_explicitMulti() -> String { print("okay") return "all right" } func ff_effectfulUsed() -> String { logAndReturn("okay") } // Unused Returns func ff_effectfulIgnored() { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeVoid() -> Void { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeSwiftVoid() -> Swift.Void { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeMyVoidTypealias() -> MyOwnVoid { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeEmptyTuple() -> () { logAndReturn("okay") } // Stubs func ff_stubImplicitReturn() { fatalError() } func ff_stubExplicitReturnTypeVoid() -> Void { fatalError() } func ff_stubExplicitReturnTypeSwiftVoid() -> Swift.Void { fatalError() } func ff_stubExplicitReturnTypeMyVoidTypealias() -> MyOwnVoid { fatalError() } func ff_stubExplicitReturnTypeEmptyTuple() -> () { fatalError() } func ff_stubImplicitReturnNever() -> Never { fatalError() } func ff_stubExplicitReturnNever() -> Never { return fatalError() } func ff_stubExplicitReturnNeverAsMyOwnNever() -> MyOwnNever { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } func ff_stubExplicitReturnMyOwnNeverAsNever() -> Never { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } func ff_stubImplicitReturnNeverAsMyOwnNever() -> MyOwnNever { fatalError() } func ff_stubImplicitReturnMyOwnNeverAsNever() -> Never { myOwnFatalError() } func ff_stubReturnString() -> String { fatalError() } func ff_stubReturnGeneric<T>() -> T { fatalError() } // Trying func ff_tryExplicit() throws -> String { return try failableIdentity("shucks") } func ff_tryImplicit() throws -> String { try failableIdentity("howdy") } func ff_tryExplicitMissingThrows() -> String { return try failableIdentity("shucks") // expected-error {{errors thrown from here are not handled}} } func ff_tryImplicitMissingThrows() -> String { try failableIdentity("howdy") // expected-error {{errors thrown from here are not handled}} } // Forced Trying func ff_forceTryExplicit() -> String { return try! failableIdentity("howdy") } func ff_forceTryImplicit() -> String { try! failableIdentity("shucks") } func ff_forceTryExplicitAddingThrows() throws -> String { return try! failableIdentity("howdy") } func ff_forceTryImplicitAddingThrows() throws -> String { try! failableIdentity("shucks") } // Optional Trying func ff_optionalTryExplicit() -> String? { return try? failableIdentity("howdy") } func ff_optionalTryImplicit() -> String? { try? failableIdentity("shucks") } func ff_optionalTryExplicitAddingThrows() throws -> String? { return try? failableIdentity("shucks") } func ff_optionalTryImplicitAddingThrows() throws -> String? { try? failableIdentity("howdy") } // Inferred Return Types func ff_inferredIntegerLiteralInt() -> Int { 0 } func ff_inferredIntegerLiteralInt8() -> Int8 { 0 } func ff_inferredIntegerLiteralInt16() -> Int16 { 0 } func ff_inferredIntegerLiteralInt32() -> Int32 { 0 } func ff_inferredIntegerLiteralInt64() -> Int64 { 0 } func ff_inferredIntegerLiteralMyOwnInt() -> MyOwnInt { 0 } func ff_nilLiteralInt() -> Int? { nil } func ff_inferredFloatLiteralFloat() -> Float { 0.0 } func ff_inferredFloatLiteralDouble() -> Double { 0.0 } func ff_inferredFloatLiteralMyOwnDouble() -> MyOwnFloat { 0.0 } func ff_inferredBooleanLiteralBool() -> Bool { true } func ff_inferredBooleanLiteralMyOwnBoolean() -> MyOwnBoolean { true } func ff_inferredStringLiteralString() -> String { "howdy" } func ff_inferredStringLiteralMyOwnString() -> MyOwnString { "howdy" } func ff_inferredInterpolatedStringLiteralString() -> String { "\(0) \(1)" } func ff_inferredInterpolatedStringLiteralString() -> MyOwnInterpolation { "\(0) \(1)" } func ff_inferredMagicFile() -> StaticString { #file } func ff_inferredMagicLine() -> UInt { #line // expected-error {{#line directive was renamed to #sourceLocation}} } // expected-error {{parameterless closing #sourceLocation() directive without prior opening #sourceLocation(file:,line:) directive}} func ff_inferredMagicColumn() -> UInt { #column } func ff_inferredMagicFunction() -> StaticString { #function } func ff_inferredMagicDSOHandle() -> UnsafeRawPointer { #dsohandle } func ff_implicitDiscardExpr() { _ = 3 } func ff_implicitMetatype() -> String.Type { String.self } func ff_implicitMemberRef(_ instance: StructWithProperty) -> Int { instance.foo } func ff_implicitDynamicMember(_ s: DynamicStruct) -> String { s.foo } func ff_implicitParenExpr() -> Int { (3 + 5) } func ff_implicitTupleExpr() -> (Int, Int) { (3, 5) } func ff_implicitArrayExprArray() -> [Int] { [1, 3, 5] } func ff_implicitArrayExprSet() -> Set<Int> { [1, 3, 5] } func ff_implicitArrayExprMyOwnArray() -> MyOwnArray<Int> { [1, 3, 5] } func ff_implicitDictionaryExprDictionary() -> [Int : Int] { [1 : 1, 2 : 2] } func ff_implicitDictionaryExprMyOwnDictionary() -> MyOwnDictionary<Int, Int> { [1 : 1, 2 : 2] } func ff_implicitSubscriptExpr(_ s: SubscriptableStruct) -> Int { s[13] } func ff_implicitKeyPathExprWritableKeyPath() -> WritableKeyPath<Int, Int> { \Int.self } func ff_implicitKeyPathExprKeyPath() -> WritableKeyPath<Int, Int> { \Int.self.self } func ff_implicitTupleElementExpr() -> Int { (1,field:2).field } func ff_implicitBindExpr(_ opt: Int?) -> Int? { opt?.zero } func ff_implicitOptionalEvaluation(_ opt: Int?) -> Int? { (opt?.zero.zero).someZero } func ff_implicitForceValue(_ opt: Int?) -> Int { opt! } func ff_implicitTemporarilyEscapableExpr(_ cl: () -> Void) -> () -> Void { withoutActuallyEscaping(cl) { $0 } } func ff_implicitOpenExistentialExpr(_ f: SomeProto) -> String { f.foo() } func ff_implicitInjectIntoOptionalExpr(_ int: Int) -> Int? { int } func ff_implicitTupleShuffle(_ input: (one: Int, two: Int)) -> (two: Int, one: Int) { input // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}} } func ff_implicitCollectionUpcast(_ deriveds: [Derived]) -> [Base] { deriveds } func ff_implicitErasureExpr(_ conformer: SomeProtoConformer) -> SomeProto { conformer } func ff_implicitAnyHashableErasureExpr(_ int: Int) -> AnyHashable { int } func ff_implicitCallExpr<Input, Output>(input: Input, function: (Input) -> Output) -> Output { function(input) } func ff_implicitPrefixUnaryOperator(int: Int) -> Int { -int } func ff_implicitBinaryOperator(lhs: Int, rhs: Int) -> Int { lhs - rhs } func ff_implicitConstructorCallRefExpr(lhs: Int, rhs: Int) -> Int { Int() } func ff_implicitIsExpr<T>(t: T) -> Bool { t is Int } func ff_implicitCoerceExpr<T>() -> T.Type { T.self as T.Type } func ff_implicitConditionalCheckedCastExprAs<T>(t: T) -> Int? { t as? Int } func ff_implicitForceCheckedCastExpr<T>(t: T) -> Int { t as! Int } func ff_conditional(_ condition: Bool) -> Int { condition ? 1 : -1 } var __ff_implicitAssignExpr: Int = 0 func ff_implicitAssignExpr(newValue: Int) -> Void { __ff_implicitAssignExpr = newValue } func ff_implicitMemberAccessInit() -> Initable { .init() } func ff_implicitMemberAccessEnumCase() -> Unit { .only } // MARK: - Free Properties : Implicit Get var fv_nop: () { } // expected-error {{computed property must have accessors specified}} var fv_missing: String { } // expected-error {{computed property must have accessors specified}} var fv_implicit: String { "hello" } var fv_explicit: String { return "hello" } var fv_explicitClosure: () -> Void { return { print("howdy") } } var fv_implicitClosure: () -> Void { { print("howdy") } } var fv_explicitMultilineClosure: () -> String { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } var fv_implicitMultilineClosure: () -> String { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } var fv_implicitWrong: String { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } var fv_explicitWrong: String { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } var fv_implicitMulti: String { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } var fv_explicitMulti: String { print("okay") return "all right" } var fv_effectfulUsed: String { logAndReturn("okay") } // Unused returns var fv_effectfulIgnored: () { logAndReturn("okay") } var fv_effectfulIgnoredVoid: Void { logAndReturn("okay") } var fv_effectfulIgnoredSwiftVoid: Swift.Void { logAndReturn("okay") } // Stubs var fv_stubEmptyTuple: () { fatalError() } var fv_stubVoid: Void { fatalError() } var fv_stubSwiftVoid: Swift.Void { fatalError() } var fv_stubMyVoidTypealias: MyOwnVoid { fatalError() } var fv_stubImplicitReturnNever: Never { fatalError() } var fv_stubExplicitReturnNever: Never { return fatalError() } var fv_stubExplicitReturnNeverAsMyOwnNever: MyOwnNever { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } var fv_stubExplicitReturnMyOwnNeverAsNever: Never { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } var fv_stubImplicitReturnNeverAsMyOwnNever: MyOwnNever { fatalError() } var fv_stubImplicitReturnMyOwnNeverAsNever: Never { myOwnFatalError() } var fv_stubString: String { fatalError() } // Forced Trying var fv_forceTryUnusedExplicit: () { return try! failableLogAndReturn("oh") //expected-error {{unexpected non-void return value in void function}} } var fv_forceTryUnusedImplicit: () { try! failableLogAndReturn("uh") } var fv_forceTryExplicit: String { return try! failableIdentity("shucks") } var fv_forceTryImplicit: String { try! failableIdentity("howdy") } // Optional Trying var fv_optionalTryUnusedExplicit: () { return try? failableLogAndReturn("uh") //expected-error {{unexpected non-void return value in void function}} } var fv_optionalTryUnusedImplicit: () { try? failableLogAndReturn("oh") //expected-warning {{result of 'try?' is unused}} } var fv_optionalTryExplicit: String? { return try? failableIdentity("shucks") } var fv_optionalTryImplicit: String? { try? failableIdentity("howdy") } // MARK: - Free Properties : Get var fvg_nop: () { get { } } var fvg_missing: String { get { } } var fvg_implicit: String { get { "hello" } } var fvg_explicit: String { get { return "hello" } } var fvg_explicitClosure: () -> Void { get { return { print("howdy") } } } var fvg_implicitClosure: () -> Void { get { { print("howdy") } } } var fvg_explicitMultilineClosure: () -> String { get { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } var fvg_implicitMultilineClosure: () -> String { get { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } var fvg_implicitWrong: String { get { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } var fvg_explicitWrong: String { get { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } var fvg_implicitMulti: String { get { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } var fvg_explicitMulti: String { get { print("okay") return "all right" } } var fvg_effectfulUsed: String { get { logAndReturn("okay") } } // Unused returns var fvg_effectfulIgnored: () { get { logAndReturn("okay") } } var fvg_effectfulIgnoredVoid: Void { get { logAndReturn("okay") } } var fvg_effectfulIgnoredSwiftVoid: Swift.Void { get { logAndReturn("okay") } } // Stubs var fvg_stubEmptyTuple: () { get { fatalError() } } var fvg_stubVoid: Void { get { fatalError() } } var fvg_stubSwiftVoid: Swift.Void { get { fatalError() } } var fvg_stubMyVoidTypealias: MyOwnVoid { get { fatalError() } } var fvg_stubImplicitReturnNever: Never { get { fatalError() } } var fvg_stubExplicitReturnNever: Never { get { return fatalError() } } var fvg_stubExplicitReturnNeverAsMyOwnNever: MyOwnNever { get { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } } var fvg_stubExplicitReturnMyOwnNeverAsNever: Never { get { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } } var fvg_stubImplicitReturnNeverAsMyOwnNever: MyOwnNever { get { fatalError() } } var fvg_stubImplicitReturnMyOwnNeverAsNever: Never { get { myOwnFatalError() } } var fvg_stubString: String { get { fatalError() } } // Forced Trying var fvg_forceTryExplicit: String { get { return try! failableIdentity("shucks") } } var fvg_forceTryImplicit: String { get { try! failableIdentity("howdy") } } // Optional Trying var fvg_optionalTryExplicit: String? { get { return try? failableIdentity("shucks") } } var fvg_optionalTryImplicit: String? { get { try? failableIdentity("howdy") } } // MARK: - Free Properties : Set var fvs_nop: () { get {} set {} } var fvs_implicit: String { get { "ok" } set { "hello" // expected-warning {{string literal is unused}} } } var fvs_explicit: String { get { "ok" } set { return "hello" // expected-error {{unexpected non-void return value in void function}} } } var fvs_explicitClosure: () -> Void { get { return { print("howdy") } } set { return { print("howdy") } // expected-error {{unexpected non-void return value in void function}} } } var fvs_implicitClosure: () -> Void { get { { print("howdy") } } set { { print("howdy") } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} } } var fvs_implicitWrong: String { get { "ok" } set { 17 // expected-warning {{integer literal is unused}} } } var fvs_explicitWrong: String { get { "ok" } set { return 17 // expected-error {{unexpected non-void return value in void function}} } } var fvs_implicitMulti: String { get { "ok" } set { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } var fvs_explicitMulti: String { get { "ok" } set { print("okay") return "all right" // expected-error {{unexpected non-void return value in void function}} } } var fvs_effectfulUsed: String { get { "ok" } set { logAndReturn("okay") } } // Stubs var fvs_stub: () { get { () } set { fatalError() } } var fvs_stubMyOwnFatalError: () { get { () } set { myOwnFatalError() } } // Forced Trying var fvs_forceTryExplicit: String { get { "ok" } set { return try! failableIdentity("shucks") // expected-error {{unexpected non-void return value in void function}} } } var fvs_forceTryImplicit: String { get { "ok" } set { try! failableIdentity("howdy") // expected-warning {{result of call to 'failableIdentity' is unused}} } } // Optional Trying var fvs_optionalTryExplicit: String? { get { "ok" } set { return try? failableIdentity("shucks") // expected-error {{unexpected non-void return value in void function}} } } var fvs_optionalTryImplicit: String? { get { "ok" } set { try? failableIdentity("howdy") // expected-warning {{result of 'try?' is unused}} } } // MARK: - Free Properties : Read // MARK: - Free Properties : Modify // MARK: - Subscripts : Implicit Readonly enum S_nop { subscript() -> () { } // expected-error {{subscript must have accessors specified}} } enum S_missing { subscript() -> String { } // expected-error {{subscript must have accessors specified}} } enum S_implicit { subscript() -> String { "hello" } } enum S_explicit { subscript() -> String { return "hello" } } enum S_explicitClosure { subscript() -> () -> Void { return { print("howdy") } } } enum S_implicitClosure { subscript() -> () -> Void { { print("howdy") } } } enum S_explicitMultilineClosure { subscript() -> () -> String { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } enum S_implicitMultilineClosure { subscript() -> () -> String { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } enum S_implicitWrong { subscript() -> String { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } enum S_explicitWrong { subscript() -> String { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } enum S_implicitMulti { subscript() -> String { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } enum S_explicitMulti { subscript() -> String { print("okay") return "all right" } } enum S_effectfulUsed { subscript() -> String { logAndReturn("okay") } } // Unused returns enum S_effectfulIgnored { subscript() -> () { logAndReturn("okay") } } enum S_effectfulIgnoredVoid { subscript() -> Void { logAndReturn("okay") } } enum S_effectfulIgnoredSwiftVoid { subscript() -> Swift.Void { logAndReturn("okay") } } // Stubs enum S_stubEmptyTuple { subscript() -> () { fatalError() } } enum S_stubVoid { subscript() -> Void { fatalError() } } enum S_stubSwiftVoid { subscript() -> Swift.Void { fatalError() } } enum S_stubMyVoidTypealias { subscript() -> MyOwnVoid { fatalError() } } enum S_stubImplicitReturnNever { subscript() -> Never { fatalError() } } enum S_stubExplicitReturnNever { subscript() -> Never { return fatalError() } } enum S_stubExplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } } enum S_stubExplicitReturnMyOwnNeverAsNever { subscript() -> Never { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } } enum S_stubImplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { fatalError() } } enum S_stubImplicitReturnMyOwnNeverAsNever { subscript() -> Never { myOwnFatalError() } } enum S_stubString { subscript() -> String { fatalError() } } enum S_stubGeneric { subscript<T>() -> T { fatalError() } } // Forced Trying enum S_forceTryExplicit { subscript() -> String { return try! failableIdentity("shucks") } } enum S_forceTryImplicit { subscript() -> String { try! failableIdentity("howdy") } } // Optional Trying enum S_optionalTryExplicit { subscript() -> String? { return try? failableIdentity("shucks") } } enum S_optionalTryImplicit { subscript() -> String? { try? failableIdentity("howdy") } } // MARK: - Subscripts : Explicit Readonly enum SRO_nop { subscript() -> () { get { } } } enum SRO_missing { subscript() -> String { get { } } } enum SRO_implicit { subscript() -> String { get { "hello" } } } enum SRO_explicit { subscript() -> String { get { return "hello" } } } enum SRO_explicitClosure { subscript() -> () -> Void { get { return { print("howdy") } } } } enum SRO_implicitClosure { subscript() -> () -> Void { get { { print("howdy") } } } } enum SRO_explicitMultilineClosure { subscript() -> () -> String { get { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } } enum SRO_implicitMultilineClosure { subscript() -> () -> String { get { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } } enum SRO_implicitWrong { subscript() -> String { get { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } } enum SRO_explicitWrong { subscript() -> String { get { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } } enum SRO_implicitMulti { subscript() -> String { get { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } } enum SRO_explicitMulti { subscript() -> String { get { print("okay") return "all right" } } } enum SRO_effectfulUsed { subscript() -> String { get { logAndReturn("okay") } } } // Unused returns enum SRO_effectfulIgnored { subscript() -> () { get { logAndReturn("okay") } } } enum SRO_effectfulIgnoredVoid { subscript() -> Void { get { logAndReturn("okay") } } } enum SRO_effectfulIgnoredSwiftVoid { subscript() -> Swift.Void { get { logAndReturn("okay") } } } // Stubs enum SRO_stubEmptyTuple { subscript() -> () { get { fatalError() } } } enum SRO_stubVoid { subscript() -> Void { get { fatalError() } } } enum SRO_stubSwiftVoid { subscript() -> Swift.Void { get { fatalError() } } } enum SRO_stubMyVoidTypealias { subscript() -> MyOwnVoid { get { fatalError() } } } enum SRO_stubImplicitReturnNever { subscript() -> Never { get { fatalError() } } } enum SRO_stubExplicitReturnNever { subscript() -> Never { get { return fatalError() } } } enum SRO_stubExplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { get { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } } } enum SRO_stubExplicitReturnMyOwnNeverAsNever { subscript() -> Never { get { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } } } enum SRO_stubImplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { get { fatalError() } } } enum SRO_stubImplicitReturnMyOwnNeverAsNever { subscript() -> Never { get { myOwnFatalError() } } } enum SRO_stubString { subscript() -> String { get { fatalError() } } } enum SRO_stubGeneric { subscript<T>() -> T { get { fatalError() } } } // Forced Trying enum SRO_forceTryExplicit { subscript() -> String { get { return try! failableIdentity("shucks") } } } enum SRO_forceTryImplicit { subscript() -> String { get { try! failableIdentity("howdy") } } } // Optional Trying enum SRO_optionalTryExplicit { subscript() -> String? { get { return try? failableIdentity("shucks") } } } enum SRO_optionalTryImplicit { subscript() -> String? { get { try? failableIdentity("howdy") } } } // MARK: - Subscripts : Set // MARK: - Subscripts : Read/Modify // MARK: - Constructors struct C_nop { init() { } } struct C_missing { var i: Int init?() { } } struct C_implicitNil { init?() { nil } } struct C_explicitNil { init?() { return nil } } struct C_forcedMissing { var i: Int init!() { } } struct C_forcedImplicitNil { init!() { nil } } struct C_forcedExplicitNil { init?() { return nil } } struct C_implicit { init() { "hello" // expected-warning {{string literal is unused}} } } struct C_explicit { init() { return "hello" // expected-error {{'nil' is the only return value permitted in an initializer}} } } // MARK: - Destructors class D_nop { deinit { } } class D_implicit { deinit { "bye now" // expected-warning {{string literal is unused}} } } class D_explicit { deinit { return "bye now" // expected-error {{unexpected non-void return value in void function}} } } class D_implicitMulti { deinit { print("okay") "see ya" // expected-warning {{string literal is unused}} } } class D_explicitMulti { deinit { print("okay") return "see ya" // expected-error {{unexpected non-void return value in void function}} } } // Unused returns class D_effectfulIgnored { deinit { logAndReturn("bye now") } } // Stubs class D_stub { deinit { fatalError() } } class D_stubMyOwnDeinit { deinit { myOwnFatalError() } } // Forced Trying class D_forceTryUnusedExplicit { deinit { return try! failableLogAndReturn("uh") // expected-error {{unexpected non-void return value in void function}} } } class D_forceTryUnusedImplicit { deinit { try! failableLogAndReturn("oh") } } // Optional Trying class D_optionalTryUnusedExplicit { deinit { return try? failableLogAndReturn("uh") // expected-error {{unexpected non-void return value in void function}} } } class D_optionalTryUnusedImplicit { deinit { try? failableLogAndReturn("oh") // expected-warning {{result of 'try?' is unused}} } } // Miscellanceous class CSuperExpr_Base { init() {} } class CSuperExpr_Derived : CSuperExpr_Base { override init() { super.init() } } class CImplicitIdentityExpr { func gimme() -> CImplicitIdentityExpr { self } } class CImplicitDotSelfExpr { func gimme() -> CImplicitDotSelfExpr { self.self } } func badIs<T>(_ value: Any, anInstanceOf type: T.Type) -> Bool { value is type // expected-error {{cannot find type 'type' in scope}} } // Autoclosure Discriminators func embedAutoclosure_standard() -> Int { _helpEmbedAutoclosure_standard(42) } func _helpEmbedAutoclosure_standard<T>(_ value: @autoclosure () -> T) -> T { value() } func embedAutoclosure_never() -> Int { fatalError("unsupported") }
apache-2.0
f702dc48a427ada62a14e4e165a162ef
17.21408
135
0.607984
3.912855
false
false
false
false
apple/swift-driver
Sources/swift-driver/main.swift
1
4097
//===--------------- main.swift - Swift Driver Main Entrypoint ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftDriverExecution import SwiftDriver #if os(Windows) import CRT #elseif os(iOS) || os(macOS) || os(tvOS) || os(watchOS) import Darwin #else import Glibc #endif import Dispatch #if os(Windows) import WinSDK #endif import enum TSCBasic.ProcessEnv import func TSCBasic.exec import class TSCBasic.DiagnosticsEngine import class TSCBasic.Process import class TSCBasic.ProcessSet import protocol TSCBasic.DiagnosticData import var TSCBasic.localFileSystem import enum TSCUtility.Diagnostics let interruptSignalSource = DispatchSource.makeSignalSource(signal: SIGINT) let diagnosticsEngine = DiagnosticsEngine(handlers: [Driver.stderrDiagnosticsHandler]) var driverInterrupted = false func getExitCode(_ code: Int32) -> Int32 { if driverInterrupted { interruptSignalSource.cancel() #if os(Windows) TerminateProcess(GetCurrentProcess(), UINT(0xC0000000 | UINT(2))) #else signal(SIGINT, SIG_DFL) kill(getpid(), SIGINT) #endif fatalError("Invalid state, could not kill process") } return code } do { #if !os(Windows) signal(SIGINT, SIG_IGN) #endif let processSet = ProcessSet() interruptSignalSource.setEventHandler { // Terminate running compiler jobs and let the driver exit gracefully, remembering // to return a corresponding exit code when done. processSet.terminate() driverInterrupted = true } interruptSignalSource.resume() if ProcessEnv.vars["SWIFT_ENABLE_EXPLICIT_MODULE"] != nil { CommandLine.arguments.append("-explicit-module-build") } let (mode, arguments) = try Driver.invocationRunMode(forArgs: CommandLine.arguments) if case .subcommand(let subcommand) = mode { // We are running as a subcommand, try to find the subcommand adjacent to the executable we are running as. // If we didn't find the tool there, let the OS search for it. let subcommandPath = Process.findExecutable(CommandLine.arguments[0])?.parentDirectory.appending(component: subcommand) ?? Process.findExecutable(subcommand) guard let subcommandPath = subcommandPath, localFileSystem.exists(subcommandPath) else { throw Driver.Error.unknownOrMissingSubcommand(subcommand) } // Pass the full path to subcommand executable. var arguments = arguments arguments[0] = subcommandPath.pathString // Execute the subcommand. try exec(path: subcommandPath.pathString, args: arguments) } let executor = try SwiftDriverExecutor(diagnosticsEngine: diagnosticsEngine, processSet: processSet, fileSystem: localFileSystem, env: ProcessEnv.vars) var driver = try Driver(args: arguments, diagnosticsEngine: diagnosticsEngine, executor: executor, integratedDriver: false) // FIXME: The following check should be at the end of Driver.init, but current // usage of the DiagnosticVerifier in tests makes this difficult. guard !driver.diagnosticEngine.hasErrors else { throw Diagnostics.fatalError } let jobs = try driver.planBuild() try driver.run(jobs: jobs) if driver.diagnosticEngine.hasErrors { exit(getExitCode(EXIT_FAILURE)) } exit(getExitCode(0)) } catch Diagnostics.fatalError { exit(getExitCode(EXIT_FAILURE)) } catch let diagnosticData as DiagnosticData { diagnosticsEngine.emit(.error(diagnosticData)) exit(getExitCode(EXIT_FAILURE)) } catch { print("error: \(error)") exit(getExitCode(EXIT_FAILURE)) }
apache-2.0
1f1a48867565aecb47e532ef4942fb02
33.141667
123
0.694899
4.552222
false
false
false
false
hunk3000/Tiny-Stone
SwiftLearning/SwiftLearning/FirstViewController.swift
1
5153
// // FirstViewController.swift // SwiftLearning // // Created by Hunk on 14-6-16. // Copyright (c) 2014 dianxinOS. All rights reserved. // import UIKit import AVFoundation import QuartzCore class FirstViewController: UIViewController { var titleLabel:UILabel! var subtitleLabel:UILabel! var captureDevice:AVCaptureDevice! var waterBackgroundView:WaterView! var circleView:CircleView! var ringView:CircleRingView! var bgView:UIImageView! override func loadView() { super.loadView() bgView = UIImageView(image: UIImage(named: "bg_iphone5")) self.view.addSubview(bgView) // //Speed Ring View // ringView = CircleRingView(frame: CGRectZero) // self.view.addSubview(ringView) // //Water background // waterBackgroundView = WaterView(frame: CGRectZero) // self.view.addSubview(waterBackgroundView) // //Ring View // circleView = CircleView(frame: CGRectZero) // self.view.addSubview(circleView) // circleView.layer.addAnimation(ani, forKey: "animation") // //Text // self.view.backgroundColor = UIColor.whiteColor() // var attStr:NSMutableAttributedString = NSMutableAttributedString(string: "100 M") // attStr.addAttribute(NSForegroundColorAttributeName, // value: UIColor.redColor(), range: NSMakeRange(0, 5)) // attStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(33), range: NSMakeRange(0, 5)) // titleLabel = UILabel() // titleLabel.font = UIFont.systemFontOfSize(14.0) // titleLabel.textAlignment = .Center // titleLabel.attributedText = attStr; // self.view.addSubview(titleLabel) // subtitleLabel = UILabel() // subtitleLabel.text = "free memeory" // self.view.addSubview(subtitleLabel) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let f = self.view.bounds bgView.frame = f // titleLabel.frame = CGRectMake(100, 130, 120, 30) // subtitleLabel.frame = CGRectMake(100, 160, 120, 30) // waterBackgroundView.frame = f // circleView.frame = CGRectMake(160, 160, 120, 120) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // HKUtility.playVibrate() // HKUtility.showMessageBox(HKUtility.dateStrWithFormat("HH:mm")); // // initTorch() // torchOn(); // let torchOffSel = Selector("torchOff") // NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: torchOffSel, userInfo: nil, repeats: false) // // var nn = [1,23,3,42,5,6] // println(nn) // sort(nn,<=) // println(nn) // // var RSSI:Int = 80 // var distance = 0.0 // // for RSSI in 40...100 { // var temp:Double = Double(RSSI - 50) / 38 // distance = pow(10.0, temp); // println("dbm = -\(RSSI) distance = \(distance)") // } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) ringView = CircleRingView(frame: CGRectZero) ringView.frame = CGRectMake(20, 80, 280, 280) self.view.addSubview(ringView) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) ringView.removeFromSuperview() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //HKAnimation.animationCubeFromRight(self.view) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Torch related functions func initTorch() { if(captureDevice == .None) { captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) } } func torchOn() { var err:NSError? if captureDevice.hasTorch { let locked = captureDevice.lockForConfiguration(&err) if locked { captureDevice.torchMode = .On self.captureDevice.unlockForConfiguration() } else { HKUtility.showMessageBox("lock configuration error.") } } else { HKUtility.showMessageBox("Your device does not have a torch.") } } func torchOff() { var err:NSError? if captureDevice.hasTorch { let locked = captureDevice.lockForConfiguration(&err) if locked { captureDevice.torchMode = .Off self.captureDevice.unlockForConfiguration() } else { HKUtility.showMessageBox("lock configuration error.") } } else { HKUtility.showMessageBox("Your device does not have a torch.") } } }
bsd-2-clause
c6575b43b69303df00ef4518d046eda7
29.856287
119
0.592276
4.680291
false
false
false
false
fthomasmorel/insapp-iOS
Insapp/SplashScreenViewController.swift
1
6691
// // SplashScreenViewController.swift // Insapp // // Created by Florent THOMAS-MOREL on 9/13/16. // Copyright © 2016 Florent THOMAS-MOREL. All rights reserved. // import Foundation import UserNotifications import UIKit class SpashScreenViewController: UIViewController { @IBOutlet weak var loader: UIActivityIndicatorView! @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() if let credentials = Credentials.fetch() { self.login(credentials) }else{ self.signin() } } override func viewWillAppear(_ animated: Bool) { self.lightStatusBar() self.loader.alpha = 0 } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 0.5) { self.imageView.frame.origin.y -= self.imageView.frame.width/2 self.loader.alpha = 1 } } func login(_ credentials:Credentials){ APIManager.login(credentials, controller: self, completion: { (opt_cred, opt_user) in guard let _ = opt_cred else { self.signin() ; return } guard let _ = opt_user else { self.signin() ; return } self.displayTabViewController() }) } func signin(){ DispatchQueue.main.async { self.loadViewController(name: "TutorialViewController") } } func displayTabViewController(){ let appDelegate = UIApplication.shared.delegate as! AppDelegate var completion: ((UIViewController) -> Void)? = nil if let notification = appDelegate.notification { completion = { viewController in guard let type = notification["type"] as? String, let content = notification["content"] as? String else { return } switch type { case kNotificationTypeEvent: self.loadEventViewController(viewController as! UITabBarController, event_id: content) break case kNotificationTypePost: self.loadPostViewController(viewController as! UITabBarController, post_id: content) break case kNotificationTypeTag: guard let comment = notification["comment"] as? String else { return } self.loadCommentViewController(viewController as! UITabBarController, post_id: content, comment_id: comment) break default: break } } } self.loadViewController(name: "TabViewController", completion: completion) } func loadEventViewController(_ controller: UITabBarController, event_id: String){ let navigationController = (controller.selectedViewController as! UINavigationController) let viewController = navigationController.topViewController controller.selectedIndex = 3 APIManager.fetchEvent(event_id: event_id, controller: viewController!, completion: { (opt_event) in guard let event = opt_event else { return } DispatchQueue.main.async { let controller = (controller.selectedViewController as! UINavigationController).topViewController (controller as! NotificationCellDelegate).open(event: event) } }) } func loadPostViewController(_ controller: UITabBarController, post_id: String){ let navigationController = (controller.selectedViewController as! UINavigationController) let viewController = navigationController.topViewController controller.selectedIndex = 3 APIManager.fetchPost(post_id: post_id, controller: viewController!, completion: { (opt_post) in guard let post = opt_post else { return } DispatchQueue.main.async { let controller = (controller.selectedViewController as! UINavigationController).topViewController (controller as! NotificationCellDelegate).open(post: post) } }) } func loadCommentViewController(_ controller: UITabBarController, post_id: String, comment_id: String){ let navigationController = (controller.selectedViewController as! UINavigationController) let viewController = navigationController.topViewController controller.selectedIndex = 3 APIManager.fetchPost(post_id: post_id, controller: viewController!, completion: { (opt_post) in guard let post = opt_post else { return } DispatchQueue.main.async { let controller = (controller.selectedViewController as! UINavigationController).topViewController (controller as! NotificationCellDelegate).open(post: post, withCommentId: comment_id) } }) } func loadCommentViewController(_ controller: UITabBarController, event_id: String, comment_id: String){ let navigationController = (controller.selectedViewController as! UINavigationController) let viewController = navigationController.topViewController controller.selectedIndex = 3 APIManager.fetchEvent(event_id: event_id, controller: viewController!, completion: { (opt_event) in guard let event = opt_event else { return } DispatchQueue.main.async { let controller = (controller.selectedViewController as! UINavigationController).topViewController (controller as! NotificationCellDelegate).open(event: event, withCommentId: comment_id) } }) } func loadViewController(name: String, completion: ((_ vc: UIViewController) -> Void)? = nil){ let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: name) if name == "TabViewController" { (vc as! UITabBarController).delegate = UIApplication.shared.delegate as! UITabBarControllerDelegate? DispatchQueue.global().async { APIManager.fetchNotifications(controller: self, completion: { (notifs) in let badge = notifs.filter({ (notif) -> Bool in return !notif.seen }).count DispatchQueue.main.async { guard badge > 0 else { return } (vc as! UITabBarController).tabBar.items?[3].badgeValue = "\(badge)" } }) } } self.present(vc, animated: true) { guard let _ = completion else { return } completion!(vc) } } }
mit
d827058b9c97f5fc0f1181e4011b6715
43.304636
130
0.628251
5.533499
false
false
false
false
ludoded/ReceiptBot
Pods/Material/Sources/iOS/ToolbarController.swift
2
8365
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit extension UIViewController { /** A convenience property that provides access to the ToolbarController. This is the recommended method of accessing the ToolbarController through child UIViewControllers. */ public var toolbarController: ToolbarController? { var viewController: UIViewController? = self while nil != viewController { if viewController is ToolbarController { return viewController as? ToolbarController } viewController = viewController?.parent } return nil } } @objc(ToolbarControllerDelegate) public protocol ToolbarControllerDelegate { /// Delegation method that executes when the floatingViewController will open. @objc optional func toolbarControllerWillOpenFloatingViewController(toolbarController: ToolbarController) /// Delegation method that executes when the floatingViewController will close. @objc optional func toolbarControllerWillCloseFloatingViewController(toolbarController: ToolbarController) /// Delegation method that executes when the floatingViewController did open. @objc optional func toolbarControllerDidOpenFloatingViewController(toolbarController: ToolbarController) /// Delegation method that executes when the floatingViewController did close. @objc optional func toolbarControllerDidCloseFloatingViewController(toolbarController: ToolbarController) } @objc(ToolbarController) open class ToolbarController: StatusBarController { /** A Display value to indicate whether or not to display the rootViewController to the full view bounds, or up to the toolbar height. */ open var toolbarDisplay = Display.partial { didSet { layoutSubviews() } } /// Reference to the Toolbar. @IBInspectable open let toolbar = Toolbar() /// Internal reference to the floatingViewController. private var internalFloatingViewController: UIViewController? /// Delegation handler. open weak var delegate: ToolbarControllerDelegate? /// A floating UIViewController. open var floatingViewController: UIViewController? { get { return internalFloatingViewController } set(value) { if let v = internalFloatingViewController { v.view.layer.rasterizationScale = Screen.scale v.view.layer.shouldRasterize = true delegate?.toolbarControllerWillCloseFloatingViewController?(toolbarController: self) internalFloatingViewController = nil UIView.animate(withDuration: 0.5, animations: { [weak self] in guard let s = self else { return } v.view.center.y = 2 * s.view.bounds.height s.toolbar.alpha = 1 s.rootViewController.view.alpha = 1 }) { [weak self] _ in guard let s = self else { return } v.willMove(toParentViewController: nil) v.view.removeFromSuperview() v.removeFromParentViewController() v.view.layer.shouldRasterize = false s.isUserInteractionEnabled = true s.toolbar.isUserInteractionEnabled = true DispatchQueue.main.async { [weak self] in guard let s = self else { return } s.delegate?.toolbarControllerDidCloseFloatingViewController?(toolbarController: s) } } } if let v = value { // Add the noteViewController! to the view. addChildViewController(v) v.view.frame = view.bounds v.view.center.y = 2 * view.bounds.height v.view.isHidden = true view.insertSubview(v.view, aboveSubview: toolbar) v.view.layer.zPosition = 1500 v.didMove(toParentViewController: self) v.view.isHidden = false v.view.layer.rasterizationScale = Screen.scale v.view.layer.shouldRasterize = true view.layer.rasterizationScale = Screen.scale view.layer.shouldRasterize = true internalFloatingViewController = v isUserInteractionEnabled = false toolbar.isUserInteractionEnabled = false delegate?.toolbarControllerWillOpenFloatingViewController?(toolbarController: self) UIView.animate(withDuration: 0.5, animations: { [weak self, v = v] in guard let s = self else { return } v.view.center.y = s.view.bounds.height / 2 s.toolbar.alpha = 0.5 s.rootViewController.view.alpha = 0.5 }) { [weak self, v = v] _ in guard let s = self else { return } v.view.layer.shouldRasterize = false s.view.layer.shouldRasterize = false DispatchQueue.main.async { [weak self] in guard let s = self else { return } s.delegate?.toolbarControllerDidOpenFloatingViewController?(toolbarController: s) } } } } } open override func layoutSubviews() { super.layoutSubviews() let y = Application.shouldStatusBarBeHidden || statusBar.isHidden ? 0 : statusBar.height toolbar.y = y toolbar.width = view.width switch toolbarDisplay { case .partial: let h = y + toolbar.height rootViewController.view.y = h rootViewController.view.height = view.height - h case .full: rootViewController.view.frame = view.bounds } } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open override func prepare() { super.prepare() prepareStatusBar() prepareToolbar() } } extension ToolbarController { /// Prepares the statusBar. fileprivate func prepareStatusBar() { shouldHideStatusBarOnRotation = false } /// Prepares the toolbar. fileprivate func prepareToolbar() { toolbar.depthPreset = .depth1 view.addSubview(toolbar) } }
lgpl-3.0
9982d3e555fa9a1cfa9cdc25eda3be0a
36.34375
110
0.63682
5.182776
false
false
false
false
swiftmi/swiftmi-app
swiftmi/swiftmi/CodeDal.swift
2
3653
// // CodeDal.swift // swiftmi // // Created by yangyin on 15/4/30. // Copyright (c) 2015年 swiftmi. All rights reserved. // import Foundation import CoreData import SwiftyJSON class CodeDal: NSObject { func addList(_ items:JSON) { for po in items { self.addCode(po.1, save: false) } CoreDataManager.shared.save() } func addCode(_ obj:JSON,save:Bool){ let context=CoreDataManager.shared.managedObjectContext; let model = NSEntityDescription.entity(forEntityName: "Codedown", in: context) let codeDown = ShareCode(entity: model!, insertInto: context) if model != nil { self.obj2ManagedObject(obj, codeDown: codeDown) if(save) { CoreDataManager.shared.save() } } } func deleteAll(){ CoreDataManager.shared.deleteTable(request: NSFetchRequest<ShareCode>(),tableName: "Codedown") } func save(){ let context=CoreDataManager.shared.managedObjectContext; do { try context.save() } catch _ { } } func getCodeList()->[AnyObject]? { let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Codedown") let sort1=NSSortDescriptor(key: "createTime", ascending: false) // var sort2=NSSortDescriptor(key: "postId", ascending: false) request.fetchLimit = 30 request.sortDescriptors = [sort1] request.resultType = NSFetchRequestResultType.dictionaryResultType let result = CoreDataManager.shared.executeFetchRequest(request) return result } func obj2ManagedObject(_ obj:JSON,codeDown:ShareCode){ var data = obj codeDown.author = data["author"].string codeDown.categoryId = data["categoryId"].int64Value codeDown.categoryName = data["categoryName"].string codeDown.codeId = data["codeId"].int64Value codeDown.commentCount = data["commentCount"].int32Value codeDown.content = data["content"].string codeDown.contentLength = data["contentLength"].doubleValue codeDown.createTime = data["createTime"].int64Value codeDown.desc = data["desc"].string codeDown.devices = data["devices"].string codeDown.downCount = data["downCount"].int32Value codeDown.downUrl = data["downUrl"].stringValue codeDown.isHtml = data["isHtml"].int32Value codeDown.keywords = data["keywords"].string if data["lastCommentId"].int64 != nil { codeDown.lastCommentId = data["lastCommentId"].int64Value } codeDown.lastCommentTime = data["lastCommentTime"].int64Value codeDown.licence = data["licence"].string codeDown.platform = data["platform"].string codeDown.preview = data["preview"].stringValue codeDown.sourceName = data["sourceName"].stringValue codeDown.sourceType = data["sourceType"].int32Value codeDown.sourceUrl = data["sourceUrl"].stringValue codeDown.state = data["state"].int32Value codeDown.tags = data["tags"].string codeDown.title = data["title"].string codeDown.updateTime = data["updateTime"].int64Value codeDown.userId = data["userId"].int64Value codeDown.username = data["username"].stringValue codeDown.viewCount = data["viewCount"].int32Value } }
mit
bebb9a188dc65d21bca4444cb37d182c
31.309735
102
0.606135
4.803947
false
false
false
false
1170197998/SinaWeibo
SFWeiBo/SFWeiBo/Classes/Home/Compose/PhotoSelector/PhotoSelectorViewController.swift
1
9588
// // PhotoSelectorViewController.swift // 01-图片选择器 // // Created by mac on 15/9/18. // Copyright © 2015年 ShaoFeng. All rights reserved. // import UIKit private let PhotoSelectorCellReuseIdentifier = "PhotoSelectorCellReuseIdentifier" class PhotoSelectorViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupUI() } private func setupUI() { // 1.添加子控件 view.addSubview(collcetionView) // 2.布局子控件 collcetionView.translatesAutoresizingMaskIntoConstraints = false var cons = [NSLayoutConstraint]() cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collcetionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collcetionView": collcetionView]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collcetionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collcetionView": collcetionView]) view.addConstraints(cons) } // MARK: - 懒加载 private lazy var collcetionView: UICollectionView = { let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoSelectorViewLayout()) clv.registerClass(PhotoSelectorCell.self, forCellWithReuseIdentifier: PhotoSelectorCellReuseIdentifier) clv.backgroundColor = UIColor.grayColor() clv.dataSource = self return clv }() lazy var pictureImages = [UIImage]() } extension PhotoSelectorViewController: UICollectionViewDataSource, PhotoSelectorCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pictureImages.count + 1 // return 10 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collcetionView.dequeueReusableCellWithReuseIdentifier(PhotoSelectorCellReuseIdentifier, forIndexPath: indexPath) as! PhotoSelectorCell cell.PhotoCellDelegate = self cell.backgroundColor = UIColor.greenColor() /* count = 2 item = 0 count = 2 item = 1 count = 2 item = 2 */ cell.image = (pictureImages.count == indexPath.item) ? nil : pictureImages[indexPath.item] // 0 1 // print(pictureImages.count) // print(indexPath.item) return cell } func photoDidAddSelector(cell: PhotoSelectorCell) { // print(__FUNCTION__) /* case PhotoLibrary 照片库(所有的照片,拍照&用 iTunes & iPhoto `同步`的照片 - 不能删除) case SavedPhotosAlbum 相册 (自己拍照保存的, 可以随便删除) case Camera 相机 */ // 1.判断能否打开照片库 if !UIImagePickerController.isSourceTypeAvailable( UIImagePickerControllerSourceType.PhotoLibrary) { print("不能打开相册") return } // 2.创建图片选择器 let vc = UIImagePickerController() vc.delegate = self // 设置允许用户编辑选中的图片 // 开发中如果需要上传头像, 那么请让用户编辑之后再上传 // 这样可以得到一张正方形的图片, 以便于后期处理(圆形) // vc.allowsEditing = true presentViewController(vc, animated: true, completion: nil) } /** 选中相片之后调用 :param: picker 促发事件的控制器 :param: image 当前选中的图片 :param: editingInfo 编辑之后的图片 */ func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { /* 注意: 一般情况下,只要涉及到从相册中获取图片的功能, 都需要处理内存 一般情况下一个应用程序启动会占用20M左右的内存, 当内存飙升到500M左右的时候系统就会发送内存警告, 此时就需要释放内存 , 否则就会闪退 只要内存释放到100M左右, 那么系统就不会闪退我们的应用程序 也就是说一个应用程序占用的内存20~100时是比较安全的内容范围 */ print(image) // print(editingInfo) /* // 注意: 1.如果是通过JPEG来压缩图片, 图片压缩之后是不保真的 // 2.苹果官方不推荐我们使用JPG图片,因为现实JPG图片的时候解压缩非常消耗性能 let data1 = UIImageJPEGRepresentation(image, 1.0) data1?.writeToFile("/Users/xiaomage/Desktop/1.jpg", atomically: true) let data2 = UIImageJPEGRepresentation(image, 0.1) data2?.writeToFile("/Users/xiaomage/Desktop/2.jpg", atomically: true) */ let newImage = image.imageWithScale(300) // let data2 = UIImageJPEGRepresentation(newImage, 1.0) // data2?.writeToFile("/Users/xiaomage/Desktop/2.jpg", atomically: true) // 1.将当前选中的图片添加到数组中 pictureImages.append(newImage) collcetionView.reloadData() // 注意: 如果实现了该方法, 需要我们自己关闭图片选择器 picker.dismissViewControllerAnimated(true, completion: nil) } func photoDidRemoveSelector(cell: PhotoSelectorCell) { // print(__FUNCTION__) // 1.从数组中移除"当前点击"的图片 let indexPath = collcetionView.indexPathForCell(cell) pictureImages.removeAtIndex(indexPath!.item) // 2.刷新表格 collcetionView.reloadData() } } @objc protocol PhotoSelectorCellDelegate : NSObjectProtocol { optional func photoDidAddSelector(cell: PhotoSelectorCell) optional func photoDidRemoveSelector(cell: PhotoSelectorCell) } class PhotoSelectorCell: UICollectionViewCell { weak var PhotoCellDelegate: PhotoSelectorCellDelegate? var image: UIImage? { didSet{ if image != nil{ removeButton.hidden = false addButton.setBackgroundImage(image!, forState: UIControlState.Normal) addButton.userInteractionEnabled = false }else { removeButton.hidden = true addButton.userInteractionEnabled = true addButton.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal) } } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } private func setupUI() { // 1.添加子控件 contentView.addSubview(addButton) contentView.addSubview(removeButton) // 2.布局子控件 addButton.translatesAutoresizingMaskIntoConstraints = false removeButton.translatesAutoresizingMaskIntoConstraints = false var cons = [NSLayoutConstraint]() cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton": addButton]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton": addButton]) cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[removeButton]-2-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton": removeButton]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-2-[removeButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton": removeButton]) contentView.addConstraints(cons) } // MARK: - 懒加载 private lazy var removeButton: UIButton = { let btn = UIButton() btn.hidden = true btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal) btn.addTarget(self, action: #selector(PhotoSelectorCell.removeBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() private lazy var addButton: UIButton = { let btn = UIButton() btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal) btn.addTarget(self, action: #selector(PhotoSelectorCell.addBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() func addBtnClick() { PhotoCellDelegate?.photoDidAddSelector!(self) } func removeBtnClick() { PhotoCellDelegate?.photoDidRemoveSelector!(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class PhotoSelectorViewLayout: UICollectionViewFlowLayout { override func prepareLayout() { super.prepareLayout() itemSize = CGSize(width: 80, height: 80) minimumInteritemSpacing = 10 minimumLineSpacing = 10 sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } }
apache-2.0
e1c4374d477c50c5ffea6eacb0816a41
33.784861
194
0.649525
4.842485
false
false
false
false
Ericdowney/GameOfGuilds
Guilds/Guilds/CreateAccountViewController.swift
1
1621
// // CreateAccountViewController.swift // Guilds // // Created by Downey, Eric on 11/18/15. // Copyright © 2015 ICCT. All rights reserved. // import UIKit public class CreateAccountViewController: UIViewController { public var accountLogic: AccountViewLogic? @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var confirmPassword: UITextField! @IBOutlet weak var firstName: UITextField! @IBOutlet weak var lastName: UITextField! @IBOutlet weak var email: UITextField! @IBOutlet weak var confirmEmail: UITextField! @IBOutlet weak var phoneNum: UITextField! override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if self.accountLogic == nil { let wrapper = (UIApplication.sharedApplication().delegate as! AppDelegate).parseWrapper self.accountLogic = AccountViewLogic(wrapper: wrapper) } } // MARK: - Actions @IBAction public func create(sender: AnyObject) { let account = GuildAccount(username: self.username.text!, password: self.password.text!, name: (self.firstName.text!,self.lastName.text!), email: self.email.text!, phoneNumber: self.phoneNum.text!) self.accountLogic?.createAccount(self, account: account, confirmation: (self.confirmPassword.text!, self.confirmEmail.text!)) { success in if success { self.navigationController?.popToRootViewControllerAnimated(true) } } } }
mit
9d4e5ea5b1dd7e77d97f835ef2b51038
35.022222
205
0.681481
4.792899
false
false
false
false
gmission/gmission-ios
gmission/gmission/AskVC.swift
1
3152
// // AskVC.swift // gmission // // Created by CHEN Zhao on 3/1/2016. // Copyright © 2016 CHEN Zhao. All rights reserved. // import Foundation import GoogleMaps class AskVC:EnhancedVC, UINavigationControllerDelegate, UIImagePickerControllerDelegate{ override func viewDidLoad() { super.viewDidLoad() self.title = "a new HIT" self.navigationItem.setRightBarButtonItem(UIBarButtonItem(title: "Request", style: UIBarButtonItemStyle.Plain, target: self, action: "request"), animated: true) } @IBOutlet weak var creditTextField: UITextField! @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var descriptionTextField: UITextField! @IBOutlet weak var maxAnswerTextField: UITextField! @IBOutlet weak var imageView: UIImageView! var locName:String! = nil var clLoc: CLLocation! = nil var imagePicker: UIImagePickerController! @IBAction func takePhotoClicked(sender: AnyObject) { imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .Camera presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func choosePhotoClicked(sender: AnyObject) { imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .PhotoLibrary presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { imageView.image = image imageView.contentMode = .ScaleAspectFit dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func hitDict()->[String:AnyObject]{ let dict:[String:AnyObject] = ["type":"image", "title":titleTextField.text!, "description":descriptionTextField.text!, "required_answer_count":maxAnswerTextField.text!, "credit":creditTextField.text!, "requester_id":UserManager.currentUser.id] return dict } func request(){ LocationManager.global.newCustomLocation(locName, clLoc: clLoc){ location in var dict = self.hitDict() dict["location_id"] = location.id if let image = self.imageView.image{ Attachment.newWithImage(image) { (att) -> () in dict["attachment_id"] = att.id print("got att id") Hit.postOne(Hit(dict: dict), done: { (hit:Hit) -> Void in print("asked with image") self.navigationController?.popViewControllerAnimated(true) }) } }else{ Hit.postOne(Hit(dict: dict), done: { (hit:Hit) -> Void in print("asked without image") self.navigationController?.popViewControllerAnimated(true) }) } } } }
mit
48ef8b0bfac9b0df79d51ec2b02f7a2a
36.52381
251
0.642018
5.165574
false
false
false
false
HcomCoolCode/hotelowy
ListOfHotelsTests/EANRequestBuilderTests.swift
1
1621
// // EANRequestBuilderTests.swift // ListOfHotels // // Created by Maciej Matyjas on 4/21/16. // Copyright © 2016 Expedia. All rights reserved. // import XCTest @testable import ListOfHotels class EANRequestBuilderTests: XCTestCase { var mockKeys = EANAPIKeys(fileNamed: "MockEANAPIKeys") override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testEANRequestBuilderReturnsURLs() { let builder = EANRequestBuilder(keys: mockKeys) let url = builder.build() XCTAssertNotNil(url) } func testEANRequestContainsCID() { let builder = EANRequestBuilder(keys: mockKeys) let url = builder.build() XCTAssertNotNil(url) XCTAssertTrue(url!.absoluteString.containsString(String(mockKeys.clientId!))) } func testCityQuery() { let builder = EANRequestBuilder(keys: mockKeys) builder.forCity("paris") let url = builder.build() XCTAssertTrue(url!.absoluteString.containsString("city=paris")) } func testShouldUseAmpersandsBetweenQueryParams() { let builder = EANRequestBuilder(keys: mockKeys) builder.forCity("paris") let url = builder.build() XCTAssertTrue(url!.absoluteString.containsString("&")) XCTAssertFalse(url!.absoluteString.hasSuffix("&")) } }
mit
8463db17d7794805d939ae7f37f4efd8
29.566038
111
0.664198
4.438356
false
true
false
false
scotlandyard/expocity
expocity/Model/Chat/Main/MChat.swift
1
886
import Foundation class MChat { var title:String var access:FDatabaseModelRoom.Access var presentation:FDatabaseModelRoom.Presentation var items:[MChatItem] var displayOption:MChatDisplayOptionsItem let annotations:MChatDisplayAnnotations let owner:String let created:TimeInterval let meOwner:Bool init(firebaseRoom:FDatabaseModelRoom) { title = firebaseRoom.name access = firebaseRoom.access presentation = firebaseRoom.presentation items = [] displayOption = MChatDisplayOptionsItemFill() annotations = MChatDisplayAnnotations() owner = firebaseRoom.owner created = firebaseRoom.created if owner == MSession.sharedInstance.user!.userId! { meOwner = true } else { meOwner = false } } }
mit
15eea941ef11d7ea2e6b5890283d2b40
24.314286
57
0.642212
4.977528
false
false
false
false
ios-archy/Sinaweibo_swift
SinaWeibo_swift/SinaWeibo_swift/Classess/Tools/Emotion/FindEmoticon.swift
1
2319
// // FindEmoticon.swift // Emotion // // Created by yuqi on 16/11/20. // Copyright © 2016年 archy. All rights reserved. // import UIKit class FindEmoticon: NSObject { // MARK:- 实际单例对象 static let shareInstance : FindEmoticon = FindEmoticon () // MARK:- 表情素材 private lazy var manager : EmoticonManager = EmoticonManager() //查找属性字符串的方法 func findAttrisString(statusText : String ,font : UIFont) -> NSMutableAttributedString? { //1.创建匹配规则 let patter = "\\[.*?\\]" //匹配表情 //2.创建正则表达式对象 guard let regex = try? NSRegularExpression(pattern: patter, options: []) else { return nil } //3.开始匹配 let results = regex.matchesInString(statusText, options: [], range: NSRange(location: 0, length: statusText.characters.count)) //4.获取结果 let attrMstr = NSMutableAttributedString(string: statusText) for var i = results.count - 1; i >= 0; i-- { //4.0获取结果 let result = results[i] //4.1获取chs let chs = (statusText as NSString).substringWithRange(result.range) //4.2根据chs,获取图片路径 guard let pngPath = findPngPath(chs) else { return nil } //4.3创建属性字符串 let attachment = NSTextAttachment() attachment.image = UIImage(contentsOfFile: pngPath) attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight) let attrImageStr = NSAttributedString(attachment: attachment) //4.将属性字符串替换到来源的文字位置 attrMstr.replaceCharactersInRange(result.range, withAttributedString: attrImageStr) } //返回结果 return attrMstr } private func findPngPath(chs : String) -> String? { for package in manager.packages { for emoticon in package.emoticons { if emoticon.chs == chs{ return emoticon.pngPath } } } return nil } }
mit
756c2358cb17acf1cd76835c32ea0b9d
28.722222
134
0.552804
4.592275
false
false
false
false