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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ziogaschr/SwiftPasscodeLock | PasscodeLockDemo/LockSplashView.swift | 1 | 1880 | //
// LockSplashView.swift
// PasscodeLock
//
// Created by Chris Ziogas on 19/12/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
open class LockSplashView: UIView {
fileprivate lazy var logo: UIImageView = {
let image = UIImage(named: "fake-logo")
let view = UIImageView(image: image)
view.contentMode = UIViewContentMode.center
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
///////////////////////////////////////////////////////
// MARK: - Initializers
///////////////////////////////////////////////////////
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
addSubview(logo)
setupLayout()
}
convenience init() {
self.init(frame: UIScreen.main.bounds)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
///////////////////////////////////////////////////////
// MARK: - Layout
///////////////////////////////////////////////////////
fileprivate func setupLayout() {
let views = ["logo": logo]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[logo]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[logo]", options: [], metrics: nil, views: views))
addConstraint(NSLayoutConstraint(item: logo, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: logo, attribute: .centerY, multiplier: 1, constant: 0))
}
}
| mit | 949810c3f9406c4435daaf2b4ca3c929 | 31.396552 | 156 | 0.546567 | 5.368571 | false | false | false | false |
mauryat/firefox-ios | Account/FirefoxAccount.swift | 1 | 13304 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
import SwiftyJSON
private let log = Logger.syncLogger
// The version of the account schema we persist.
let AccountSchemaVersion = 2
/// A FirefoxAccount mediates access to identity attached services.
///
/// All data maintained as part of the account or its state should be
/// considered sensitive and stored appropriately. Usually, that means
/// storing account data in the iOS keychain.
///
/// Non-sensitive but persistent data should be maintained outside of
/// the account itself.
open class FirefoxAccount {
/// The email address identifying the account. A Firefox Account is uniquely identified on a particular server
/// (auth endpoint) by its email address.
open let email: String
/// The auth endpoint user identifier identifying the account. A Firefox Account is uniquely identified on a
/// particular server (auth endpoint) by its assigned uid.
open let uid: String
open var deviceRegistration: FxADeviceRegistration?
open let configuration: FirefoxAccountConfiguration
open var pushRegistration: PushRegistration?
fileprivate let stateCache: KeychainCache<FxAState>
open var syncAuthState: SyncAuthState! // We can't give a reference to self if this is a let.
// To prevent advance() consumers racing, we maintain a shared advance() deferred (`advanceDeferred`). If an
// advance() is in progress, the shared deferred will be returned. (Multiple consumers can chain off a single
// deferred safely.) If no advance() is in progress, a new shared deferred will be scheduled and returned. To
// prevent data races against the shared deferred, advance() locks accesses to `advanceDeferred` using
// `advanceLock`.
fileprivate var advanceLock = OSSpinLock()
fileprivate var advanceDeferred: Deferred<FxAState>?
open var actionNeeded: FxAActionNeeded {
return stateCache.value!.actionNeeded
}
public convenience init(configuration: FirefoxAccountConfiguration, email: String, uid: String, deviceRegistration: FxADeviceRegistration?, stateKeyLabel: String, state: FxAState) {
self.init(configuration: configuration, email: email, uid: uid, deviceRegistration: deviceRegistration, stateCache: KeychainCache(branch: "account.state", label: stateKeyLabel, value: state))
}
public init(configuration: FirefoxAccountConfiguration, email: String, uid: String, deviceRegistration: FxADeviceRegistration?, stateCache: KeychainCache<FxAState>) {
self.email = email
self.uid = uid
self.deviceRegistration = deviceRegistration
self.configuration = configuration
self.stateCache = stateCache
self.stateCache.checkpoint()
self.syncAuthState = FirefoxAccountSyncAuthState(account: self,
cache: KeychainCache.fromBranch("account.syncAuthState", withLabel: self.stateCache.label, factory: syncAuthStateCachefromJSON))
}
open class func from(_ configuration: FirefoxAccountConfiguration, andJSON data: JSON) -> FirefoxAccount? {
guard let email = data["email"].string ,
let uid = data["uid"].string,
let sessionToken = data["sessionToken"].string?.hexDecodedData,
let keyFetchToken = data["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = data["unwrapBKey"].string?.hexDecodedData else {
return nil
}
let verified = data["verified"].bool ?? false
return FirefoxAccount.from(configuration: configuration,
andParametersWithEmail: email, uid: uid, deviceRegistration: nil, verified: verified,
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
open class func from(_ configuration: FirefoxAccountConfiguration,
andLoginResponse response: FxALoginResponse,
unwrapkB: Data) -> FirefoxAccount {
return FirefoxAccount.from(configuration: configuration,
andParametersWithEmail: response.remoteEmail, uid: response.uid, deviceRegistration: nil, verified: response.verified,
sessionToken: response.sessionToken as Data, keyFetchToken: response.keyFetchToken as Data, unwrapkB: unwrapkB)
}
fileprivate class func from(configuration: FirefoxAccountConfiguration,
andParametersWithEmail email: String,
uid: String,
deviceRegistration: FxADeviceRegistration?,
verified: Bool,
sessionToken: Data,
keyFetchToken: Data,
unwrapkB: Data) -> FirefoxAccount {
var state: FxAState! = nil
if !verified {
let now = Date.now()
state = EngagedBeforeVerifiedState(knownUnverifiedAt: now,
lastNotifiedUserAt: now,
sessionToken: sessionToken,
keyFetchToken: keyFetchToken,
unwrapkB: unwrapkB
)
} else {
state = EngagedAfterVerifiedState(
sessionToken: sessionToken,
keyFetchToken: keyFetchToken,
unwrapkB: unwrapkB
)
}
let account = FirefoxAccount(
configuration: configuration,
email: email,
uid: uid,
deviceRegistration: deviceRegistration,
stateKeyLabel: Bytes.generateGUID(),
state: state
)
return account
}
open func dictionary() -> [String: Any] {
var dict: [String: Any] = [:]
dict["version"] = AccountSchemaVersion
dict["email"] = email
dict["uid"] = uid
dict["deviceRegistration"] = deviceRegistration
dict["pushRegistration"] = pushRegistration
dict["configurationLabel"] = configuration.label.rawValue
dict["stateKeyLabel"] = stateCache.label
return dict
}
open class func fromDictionary(_ dictionary: [String: Any]) -> FirefoxAccount? {
if let version = dictionary["version"] as? Int {
// As of this writing, the current version, v2, is backward compatible with v1. The only
// field added is pushRegistration, which is ok to be nil. If it is nil, then the app
// will attempt registration when it starts up.
if version <= AccountSchemaVersion {
return FirefoxAccount.fromDictionaryV1(dictionary)
}
}
return nil
}
fileprivate class func fromDictionaryV1(_ dictionary: [String: Any]) -> FirefoxAccount? {
var configurationLabel: FirefoxAccountConfigurationLabel? = nil
if let rawValue = dictionary["configurationLabel"] as? String {
configurationLabel = FirefoxAccountConfigurationLabel(rawValue: rawValue)
}
if let
configurationLabel = configurationLabel,
let email = dictionary["email"] as? String,
let uid = dictionary["uid"] as? String {
let deviceRegistration = dictionary["deviceRegistration"] as? FxADeviceRegistration
let stateCache = KeychainCache.fromBranch("account.state", withLabel: dictionary["stateKeyLabel"] as? String, withDefault: SeparatedState(), factory: state)
let account = FirefoxAccount(
configuration: configurationLabel.toConfiguration(),
email: email, uid: uid,
deviceRegistration: deviceRegistration,
stateCache: stateCache)
account.pushRegistration = dictionary["pushRegistration"] as? PushRegistration
return account
}
return nil
}
public enum AccountError: MaybeErrorType {
case notMarried
public var description: String {
switch self {
case .notMarried: return "Not married."
}
}
}
public class NotATokenStateError: MaybeErrorType {
let state: FxAState?
init(state: FxAState?) {
self.state = state
}
public var description: String {
return "Not in a Token State: \(state?.label.rawValue ?? "Empty State")"
}
}
// Fetch the devices list from FxA then replace the current stored remote devices.
open func updateFxADevices(remoteDevices: RemoteDevices) -> Success {
guard let session = stateCache.value as? TokenState else {
return deferMaybe(NotATokenStateError(state: stateCache.value))
}
let client = FxAClient10(endpoint: self.configuration.authEndpointURL)
return client.devices(withSessionToken: session.sessionToken as NSData) >>== { resp in
return remoteDevices.replaceRemoteDevices(resp.devices)
}
}
@discardableResult open func notify(deviceIDs: [GUID], collectionsChanged collections: [String]) -> Deferred<Maybe<FxANotifyResponse>> {
guard let session = stateCache.value as? TokenState else {
return deferMaybe(NotATokenStateError(state: stateCache.value))
}
let client = FxAClient10(endpoint: self.configuration.authEndpointURL)
return client.notify(deviceIDs: deviceIDs, collectionsChanged: collections, withSessionToken: session.sessionToken as NSData)
}
@discardableResult open func advance() -> Deferred<FxAState> {
OSSpinLockLock(&advanceLock)
if let deferred = advanceDeferred {
// We already have an advance() in progress. This consumer can chain from it.
log.debug("advance already in progress; returning shared deferred.")
OSSpinLockUnlock(&advanceLock)
return deferred
}
// Alright, we haven't an advance() in progress. Schedule a new deferred to chain from.
let cachedState = stateCache.value!
var registration = succeed()
if let session = cachedState as? TokenState {
registration = FxADeviceRegistrator.registerOrUpdateDevice(self, sessionToken: session.sessionToken as NSData).bind { result in
if result.successValue != FxADeviceRegistrationResult.alreadyRegistered {
NotificationCenter.default.post(name: NotificationFirefoxAccountDeviceRegistrationUpdated, object: nil)
}
return succeed()
}
}
let deferred: Deferred<FxAState> = registration.bind { _ in
let client = FxAClient10(endpoint: self.configuration.authEndpointURL)
let stateMachine = FxALoginStateMachine(client: client)
let now = Date.now()
return stateMachine.advance(fromState: cachedState, now: now).map { newState in
self.stateCache.value = newState
return newState
}
}
advanceDeferred = deferred
log.debug("no advance() in progress; setting and returning new shared deferred.")
OSSpinLockUnlock(&advanceLock)
deferred.upon { _ in
// This advance() is complete. Clear the shared deferred.
OSSpinLockLock(&self.advanceLock)
if let existingDeferred = self.advanceDeferred, existingDeferred === deferred {
// The guard should not be needed, but should prevent trampling racing consumers.
self.advanceDeferred = nil
log.debug("advance() completed and shared deferred is existing deferred; clearing shared deferred.")
} else {
log.warning("advance() completed but shared deferred is not existing deferred; ignoring potential bug!")
}
OSSpinLockUnlock(&self.advanceLock)
}
return deferred
}
open func marriedState() -> Deferred<Maybe<MarriedState>> {
return advance().map { newState in
if newState.label == FxAStateLabel.married {
if let married = newState as? MarriedState {
return Maybe(success: married)
}
}
return Maybe(failure: AccountError.notMarried)
}
}
@discardableResult open func makeSeparated() -> Bool {
log.info("Making Account State be Separated.")
self.stateCache.value = SeparatedState()
return true
}
@discardableResult open func makeDoghouse() -> Bool {
log.info("Making Account State be Doghouse.")
self.stateCache.value = DoghouseState()
return true
}
open func makeCohabitingWithoutKeyPair() -> Bool {
if let married = self.stateCache.value as? MarriedState {
log.info("Making Account State be CohabitingWithoutKeyPair.")
self.stateCache.value = married.withoutKeyPair()
return true
}
log.info("Cannot make Account State be CohabitingWithoutKeyPair from state with label \(self.stateCache.value?.label ??? "nil").")
return false
}
}
| mpl-2.0 | b2b1b870c5e2b5002cdb553febff33e4 | 43.945946 | 199 | 0.647023 | 5.632515 | false | true | false | false |
RxSugar/RxSugar | RxSugar/Sugar.swift | 1 | 1535 | import Foundation
import RxSwift
public struct Sugar<HostType> {
public let host:HostType
public init(host: HostType) {
self.host = host
}
}
public protocol RXSObject: AnyObject {}
public extension RXSObject {
typealias RxsSelfType = Self
var rxs: Sugar<RxsSelfType> { return Sugar(host: self) }
}
extension NSObject: RXSObject {}
private var disposeBagKey: UInt8 = 0
public extension Sugar where HostType: RXSObject {
/**
An Observable<Void> that will send a Next and Completed event upon deinit
*/
var onDeinit: Observable<Void> {
let bag = disposeBag
return Observable.create { [weak bag] observer in
bag?.insert(Disposables.create(with: {
observer.onNext(())
observer.onCompleted()
}))
return Disposables.create()
}
}
/**
A DisposeBag that will dispose upon deinit
*/
var disposeBag: DisposeBag {
objc_sync_enter(host)
let bag = objc_getAssociatedObject(host, &disposeBagKey) as? DisposeBag ?? createAssociatedDisposeBag()
objc_sync_exit(host)
return bag
}
private func createAssociatedDisposeBag() -> DisposeBag {
let bag = DisposeBag()
objc_setAssociatedObject(host, &disposeBagKey, bag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return bag
}
func valueSetter<T>(_ setter: @escaping (HostType, T)->()) -> AnyObserver<T> {
return ValueSetter<HostType, T>(host: host, setter: setter).asObserver()
}
}
| mit | 8146ffba476b205b868e40a6378d1962 | 24.583333 | 111 | 0.644951 | 4.263889 | false | false | false | false |
lcddhr/DouyuTV | Pods/Moya/Source/Plugins/NetworkLoggerPlugin.swift | 3 | 3540 | import Foundation
import Result
/// Logs network activity (outgoing requests and incoming responses).
public final class NetworkLoggerPlugin: PluginType {
private let loggerId = "Moya_Logger"
private let dateFormatString = "dd/MM/yyyy HH:mm:ss"
private let dateFormatter = NSDateFormatter()
private let separator = ", "
private let terminator = "\n"
private let output: (items: Any..., separator: String, terminator: String) -> Void
/// If true, also logs response body data.
public let verbose: Bool
public init(verbose: Bool = false, output: (items: Any..., separator: String, terminator: String) -> Void = print) {
self.verbose = verbose
self.output = output
}
public func willSendRequest(request: RequestType, target: TargetType) {
output(items: logNetworkRequest(request.request), separator: separator, terminator: terminator)
}
public func didReceiveResponse(result: Result<Moya.Response, Moya.Error>, target: TargetType) {
if case .Success(let response) = result {
output(items: logNetworkResponse(response.response, data: response.data, target: target), separator: separator, terminator: terminator)
} else {
output(items: logNetworkResponse(nil, data: nil, target: target), separator: separator, terminator: terminator)
}
}
}
private extension NetworkLoggerPlugin {
private var date: String {
dateFormatter.dateFormat = dateFormatString
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return dateFormatter.stringFromDate(NSDate())
}
private func format(loggerId: String, date: String, identifier: String, message: String) -> String {
return "\(loggerId): [\(date)] \(identifier): \(message)"
}
func logNetworkRequest(request: NSURLRequest?) -> [String] {
var output = [String]()
output += [format(loggerId, date: date, identifier: "Request", message: request?.description ?? "(invalid request)")]
if let headers = request?.allHTTPHeaderFields {
output += [format(loggerId, date: date, identifier: "Request Headers", message: headers.description)]
}
if let bodyStream = request?.HTTPBodyStream {
output += [format(loggerId, date: date, identifier: "Request Body Stream", message: bodyStream.description)]
}
if let httpMethod = request?.HTTPMethod {
output += [format(loggerId, date: date, identifier: "HTTP Request Method", message: httpMethod)]
}
if let body = request?.HTTPBody where verbose == true {
if let stringOutput = NSString(data: body, encoding: NSUTF8StringEncoding) as? String {
output += [format(loggerId, date: date, identifier: "Request Body", message: stringOutput)]
}
}
return output
}
func logNetworkResponse(response: NSURLResponse?, data: NSData?, target: TargetType) -> [String] {
guard let response = response else {
return [format(loggerId, date: date, identifier: "Response", message: "Received empty network response for \(target).")]
}
var output = [String]()
output += [format(loggerId, date: date, identifier: "Response", message: response.description)]
if let data = data, let stringData = NSString(data: data, encoding: NSUTF8StringEncoding) as? String where verbose == true {
output += [stringData]
}
return output
}
}
| mit | f8c7b8fe654029719b1755e275b69b79 | 39.227273 | 147 | 0.65452 | 4.809783 | false | false | false | false |
nasser0099/Express | Express/Express.swift | 1 | 3399 | //===--- Express.swift ----------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
import ExecutionContext
import BrightFutures
public func express() -> Express {
return Express()
}
public class Express : RouterType {
var routes:Array<RouteType> = []
var server:ServerType?
public let views:Views = Views()
public let errorHandler:AggregateErrorHandler = AggregateErrorHandler()
func routeForId(id:String) -> RouteType? {
//TODO: hash it
return routes.findFirst { route in
route.id == id
}
}
func handleInternal<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType, E: ErrorType>(matcher:UrlMatcherType, handler:Request<RequestContent> -> Future<Action<ResponseContent>, E>) -> Void {
let routeId = NSUUID().UUIDString
let factory:TransactionFactory = { head, out in
return Transaction(app: self, routeId: routeId, head: head, out: out, handler: handler)
}
let route = Route(id: routeId, matcher: matcher, factory: factory)
routes.append(route)
}
func handleInternal<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(matcher:UrlMatcherType, handler:Request<RequestContent> throws -> Action<ResponseContent>) -> Void {
handleInternal(matcher) { request in
//execute synchronous request aside from main queue (on a user queue)
future(ExecutionContext.user) {
return try handler(request)
}
}
}
}
public extension Express {
//sync
func handle<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType>(matcher:UrlMatcherType, handler:Request<RequestContent> throws -> Action<ResponseContent>) -> Void {
handleInternal(matcher, handler: handler)
}
//async
func handle<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType, E: ErrorType>(matcher:UrlMatcherType, handler:Request<RequestContent> -> Future<Action<ResponseContent>, E>) -> Void {
handleInternal(matcher, handler: handler)
}
//action
func handle<ResponseContent : FlushableContentType>(matcher:UrlMatcherType, action:Action<ResponseContent>) -> Void {
return handle(matcher) { (request:Request<AnyContent>) -> Action<ResponseContent> in
return action
}
}
}
public protocol AppContext {
var app:Express {get}
}
| gpl-3.0 | 1675459d6fb1a2aedfc4045bb75f9780 | 36.766667 | 225 | 0.663725 | 5.088323 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCBannerNavigationViewController.swift | 2 | 5602 | //
// NCBannerNavigationViewController.swift
// Neocom
//
// Created by Artem Shimanski on 02.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
import Appodeal
import ASReceipt
import StoreKit
class NCBannerNavigationViewController: NCNavigationController {
lazy var bannerView: APDBannerView? = {
let bannerView = APDBannerView(size: kAppodealUnitSize_320x50, rootViewController: self)
bannerView.translatesAutoresizingMaskIntoConstraints = false
bannerView.widthAnchor.constraint(equalToConstant: kAppodealUnitSize_320x50.width).isActive = true
bannerView.heightAnchor.constraint(equalToConstant: kAppodealUnitSize_320x50.height).isActive = true
bannerView.delegate = self
return bannerView
}()
lazy var bannerContainerView: UIView? = {
guard let bannerView = self.bannerView else {return nil}
let bannerContainerView = NCBackgroundView(frame: .zero)
bannerContainerView.translatesAutoresizingMaskIntoConstraints = false
bannerContainerView.addSubview(bannerView)
bannerView.centerXAnchor.constraint(equalTo: bannerContainerView.centerXAnchor).isActive = true
bannerView.topAnchor.constraint(equalTo: bannerContainerView.topAnchor, constant: 4).isActive = true
return bannerContainerView
}()
private var isInitialized = false
override func viewDidLoad() {
super.viewDidLoad()
#if targetEnvironment(simulator)
GDPR.requestConsent().then(on: .main) { [weak self] hasConsent in
guard let strongSelf = self else {return}
Appodeal.setTestingEnabled(true)
Appodeal.setLocationTracking(false)
Appodeal.initialize(withApiKey: NCApoodealKey, types: [.banner], hasConsent: hasConsent)
strongSelf.isInitialized = true
strongSelf.view.setNeedsLayout()
strongSelf.view.layoutIfNeeded()
strongSelf.bannerView?.loadAd()
SKPaymentQueue.default().add(strongSelf)
}
#else
Receipt.fetchValidReceipt(refreshIfNeeded: false) { [weak self] (result) in
guard let strongSelf = self else {return}
if case let .success(receipt) = result, receipt.inAppPurchases?.contains(where: {$0.inAppType == .autoRenewableSubscription && !$0.isExpired}) == true {
return
}
else {
let firstLaunchDate = UserDefaults.standard.object(forKey: UserDefaults.Key.NCFirstLaunchDate) as? Date ?? Date()
if firstLaunchDate.timeIntervalSinceNow < -TimeInterval.NCBannerStartTime {
GDPR.requestConsent().then(on: .main) { hasConsent in
#if DEBUG
Appodeal.setTestingEnabled(true)
#endif
Appodeal.setLocationTracking(false)
Appodeal.initialize(withApiKey: NCApoodealKey, types: [.banner], hasConsent: hasConsent)
}.catch(on: .main) { _ in
#if DEBUG
Appodeal.setTestingEnabled(true)
#endif
Appodeal.setLocationTracking(false)
Appodeal.initialize(withApiKey: NCApoodealKey, types: [.banner], hasConsent: false)
}.finally(on: .main) { [weak self] in
guard let strongSelf = self else {return}
strongSelf.isInitialized = true
strongSelf.view.setNeedsLayout()
strongSelf.view.layoutIfNeeded()
strongSelf.bannerView?.loadAd()
SKPaymentQueue.default().add(strongSelf)
}
}
}
}
#endif
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard isInitialized else {return}
if let bannerContainerView = self.bannerContainerView, bannerContainerView.superview != nil {
view.subviews.first?.frame = view.bounds.insetBy(UIEdgeInsets(top: 0, left: 0, bottom: bannerContainerView.bounds.height, right: 0))
}
else {
view.subviews.first?.frame = view.bounds
}
}
//MARK: - Private
private func showBanner() {
guard let bannerContainerView = bannerContainerView,
let bannerView = bannerView,
bannerContainerView.superview == nil else {return}
view.addSubview(bannerContainerView)
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: [], metrics: nil, views: ["view": bannerContainerView]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-0-|", options: [], metrics: nil, views: ["view": bannerContainerView]))
bannerView.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor).isActive = true
}
private func hideBanner() {
guard let bannerContainerView = bannerContainerView,
bannerContainerView.superview != nil else {return}
if #available(iOS 11.0, *) {
additionalSafeAreaInsets.bottom = 0
}
bannerContainerView.removeFromSuperview()
}
private func removeBanner() {
bannerContainerView?.removeFromSuperview()
bannerContainerView = nil
bannerView = nil
SKPaymentQueue.default().remove(self)
}
}
extension NCBannerNavigationViewController: AppodealBannerViewDelegate {
func bannerViewDidLoadAd(_ bannerView: APDBannerView, isPrecache precache: Bool) {
showBanner()
}
func bannerView(_ bannerView: APDBannerView, didFailToLoadAdWithError error: Error) {
hideBanner()
}
}
extension NCBannerNavigationViewController: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
guard bannerContainerView != nil else {return}
if transactions.contains(where: {$0.transactionState == .purchased || $0.transactionState == .restored}) {
Receipt.fetchValidReceipt(refreshIfNeeded: false) { [weak self] (result) in
if case let .success(receipt) = result, receipt.inAppPurchases?.contains(where: {$0.inAppType == .autoRenewableSubscription && !$0.isExpired}) == true {
self?.removeBanner()
}
}
}
}
}
| lgpl-2.1 | d426686d599bd5de9877fdf418410ab9 | 34.449367 | 164 | 0.75058 | 4.262557 | false | false | false | false |
marinehero/Safe | Source/select.swift | 2 | 4990 | /*
* Select (select.swift) - Please be Safe
*
* Copyright (C) 2015 ONcast, LLC. All Rights Reserved.
* Created by Josh Baker ([email protected])
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import Foundation
private protocol ItemAny {
func register(cond: Cond)
func unregister(cond: Cond)
func get() -> Bool;
func call()
}
private class Item<T> : ItemAny {
var closed = false
var msg : T?
var chan : Chan<T>?
var caseBlock : ((T?)->())?
var defBlock : (()->())?
init(_ chan: Chan<T>?, _ caseBlock: ((T?)->())?, _ defBlock: (()->())?){
(self.chan, self.caseBlock, self.defBlock) = (chan, caseBlock, defBlock)
}
func register(cond: Cond){
if let chan = chan {
chan.cond.mutex.lock()
defer { chan.cond.mutex.unlock() }
chan.gconds += [cond]
}
}
func unregister(cond: Cond){
if let chan = chan {
chan.cond.mutex.lock()
defer { chan.cond.mutex.unlock() }
for var i = 0; i < chan.gconds.count; i++ {
if chan.gconds[i] === cond {
chan.gconds.removeAtIndex(i)
return
}
}
}
}
func get() -> Bool {
if let chan = chan {
let (msg, closed, ready) = chan.receive(false)
if ready {
self.msg = msg
self.closed = closed
return true
}
}
return false
}
func call() {
if let block = caseBlock {
block(msg)
} else if let block = defBlock {
block()
}
}
}
private class ChanGroup {
var cond = Cond(Mutex())
var items = [Int: ItemAny]()
var ids = [Int]()
func addCase<T>(chan: Chan<T>, _ block: (T?)->()){
if items[chan.id] != nil {
fatalError("selecting channel twice")
}
items[chan.id] = Item<T>(chan, block, nil)
ids.append(chan.id)
}
func addDefault(block: ()->()){
if items[0] != nil {
fatalError("selecting default twice")
}
items[0] = Item<Void>(nil, nil, block)
}
func select(){
let rids = randomInts(ids.count)
var citems = [ItemAny]()
for i in rids {
if let item = items[ids[i]] {
citems.append(item)
}
}
var ret : ItemAny?
for item in citems {
item.register(cond)
}
defer {
for item in citems {
item.unregister(cond)
}
if let item = ret {
item.call()
}
}
for ;; {
for item in citems {
if item.get() {
ret = item
return
}
}
if items[0] != nil {
ret = items[0]
return
}
cond.mutex.lock()
cond.wait(0.25)
cond.mutex.unlock()
}
}
func randomInts(count : Int) -> [Int]{
var ints = [Int](count: count, repeatedValue:0)
for var i = 0; i < count; i++ {
ints[i] = i
}
for var i = 0; i < count; i++ {
let r = Int(arc4random()) % count
let t = ints[i]
ints[i] = ints[r]
ints[r] = t
}
return ints
}
}
private let selectMutex = Mutex()
private var selectStack : [ChanGroup] = []
/**
A "select" statement chooses which of a set of possible send or receive operations will proceed.
It looks similar to a "switch" statement but with the cases all referring to communication operations.
```
var c1 Chan<String>()
var c2 Chan<String>()
// Each channel will receive a value after some amount of time, to simulate e.g. blocking RPC operations executing in concurrent operations.
dispatch {
sleep(1)
c1 <- "one"
}
dispatch {
sleep(2)
c2 <- "two"
}
// We’ll use select to await both of these values simultaneously, printing each one as it arrives.
for var i = 0; i < 2; i++ {
_select {
_case (msg1) { c1 in
print("received", msg1)
}
_case (msg2) { c2 in
print("received", msg2)
}
}
}
```
*/
public func _select(block: ()->()){
let group = ChanGroup()
selectMutex.lock()
selectStack += [group]
block()
selectStack.removeLast()
selectMutex.unlock()
group.select()
}
/**
A "case" statement reads messages from a channel.
*/
public func _case<T>(chan: Chan<T>, block: (T?)->()){
if let group = selectStack.last{
group.addCase(chan, block)
}
}
/**
A "default" statement will run if the "case" channels are not ready.
*/
public func _default(block: ()->()){
if let group = selectStack.last{
group.addDefault(block)
}
}
| mit | 2b99fceed4681dc1f73fa146fd70e705 | 24.319797 | 140 | 0.501804 | 3.899922 | false | false | false | false |
aschwaighofer/swift | test/Frontend/dependencies-fine.swift | 2 | 6997 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-dependencies-path - -resolve-imports "%S/../Inputs/empty file.swift" | %FileCheck -check-prefix=CHECK-BASIC %s
// RUN: %target-swift-frontend -emit-reference-dependencies-path - -typecheck -primary-file "%S/../Inputs/empty file.swift" > %t.swiftdeps
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s <%t-processed.swiftdeps
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file "%S/../Inputs/empty file.swift"
// RUN: %FileCheck -check-prefix=CHECK-BASIC %s < %t.d
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s < %t-processed.swiftdeps
// CHECK-BASIC-LABEL: - :
// CHECK-BASIC: Inputs/empty\ file.swift
// CHECK-BASIC: Swift.swiftmodule
// CHECK-BASIC-NOT: {{ }}:{{ }}
// CHECK-BASIC-YAML-NOT: externalDepend {{.*}}empty
// CHECK-BASIC-YAML: externalDepend {{.*}} '{{.*}}Swift.swiftmodule{{(/.+[.]swiftmodule)?}}'
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck "%S/../Inputs/empty file.swift" 2>&1 | %FileCheck -check-prefix=NO-PRIMARY-FILE %s
// NO-PRIMARY-FILE: warning: ignoring -emit-reference-dependencies (requires -primary-file)
// RUN: %target-swift-frontend -emit-dependencies-path - -emit-module "%S/../Inputs/empty file.swift" -o "%t/empty file.swiftmodule" -emit-module-doc-path "%t/empty file.swiftdoc" -emit-objc-header-path "%t/empty file.h" -emit-module-interface-path "%t/empty file.swiftinterface" | %FileCheck -check-prefix=CHECK-MULTIPLE-OUTPUTS %s
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftmodule :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftdoc :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftinterface :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.h :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-NOT: {{ }}:{{ }}
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -track-system-dependencies -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT-TRACK-SYSTEM %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file %s
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-IMPORT-YAML %s <%t-processed.swiftdeps
// CHECK-IMPORT-LABEL: - :
// CHECK-IMPORT: dependencies-fine.swift
// CHECK-IMPORT-DAG: Swift.swiftmodule
// CHECK-IMPORT-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-DAG: Inputs/dependencies{{/|\\}}UserClangModule.h
// CHECK-IMPORT-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-DAG: Inputs/dependencies{{/|\\}}module.modulemap
// CHECK-IMPORT-DAG: ObjectiveC.swift
// CHECK-IMPORT-DAG: Foundation.swift
// CHECK-IMPORT-DAG: CoreGraphics.swift
// CHECK-IMPORT-NOT: {{[^\\]}}:
// CHECK-IMPORT-TRACK-SYSTEM-LABEL: - :
// CHECK-IMPORT-TRACK-SYSTEM: dependencies-fine.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Swift.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: SwiftOnoneSupport.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreFoundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreGraphics.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Foundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: ObjectiveC.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies{{/|\\}}UserClangModule.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies{{/|\\}}module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: swift{{/|\\}}shims{{/|\\}}module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreFoundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreGraphics.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreGraphics.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}Foundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}NSObject.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}ObjectiveC.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}module.map
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}objc.h
// CHECK-IMPORT-TRACK-SYSTEM-NOT: {{[^\\]}}:
// CHECK-IMPORT-YAML-NOT: externalDepend {{.*}}dependencies-fine.swift
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\}}Swift.swiftmodule{{(/.+[.]swiftmodule)?}}'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies/$$$$$.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies{{/|\\\\}}UserClangModule.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies/extra-header.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies{{/|\\\\}}module.modulemap'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}ObjectiveC.swift'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}Foundation.swift'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}CoreGraphics.swift'
// CHECK-ERROR-YAML: # Dependencies are unknown because a compilation error occurred.
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -typecheck %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -typecheck -primary-file %s - %FileCheck -check-prefix=CHECK-ERROR-YAML %s
import Foundation
import UserClangModule
class Test: NSObject {}
_ = A()
_ = USER_VERSION
_ = EXTRA_VERSION
_ = MONEY
#if ERROR
_ = someRandomUndefinedName
#endif
| apache-2.0 | 9e728b1a9ef2938e098974eb2b07ab4c | 58.803419 | 332 | 0.71302 | 3.514314 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/Exporters/Prometheus/PrometheusExporterHttpServer.swift | 1 | 4291 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import NIO
import NIOHTTP1
public class PrometheusExporterHttpServer {
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
private var host: String
private var port: Int
var exporter: PrometheusExporter
public init(exporter: PrometheusExporter) {
self.exporter = exporter
let url = URL(string: exporter.options.url)
host = url?.host ?? "localhost"
port = url?.port ?? 9184
}
public func start() throws {
do {
let channel = try serverBootstrap.bind(host: host, port: port).wait()
print("Listening on \(String(describing: channel.localAddress))...")
try channel.closeFuture.wait()
} catch let error {
throw error
}
}
public func stop() {
do {
try group.syncShutdownGracefully()
} catch let error {
print("Error shutting down \(error.localizedDescription)")
exit(0)
}
print("Client connection closed")
}
private var serverBootstrap: ServerBootstrap {
return ServerBootstrap(group: group)
// Specify backlog and enable SO_REUSEADDR for the server itself
.serverChannelOption(ChannelOptions.backlog, value: 256)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
// Set the handlers that are appled to the accepted Channels
.childChannelInitializer { channel in
// Ensure we don't read faster than we can write by adding the BackPressureHandler into the pipeline.
channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).flatMap {
channel.pipeline.addHandler(PrometheusHTTPHandler(exporter: self.exporter))
}
}
// Enable SO_REUSEADDR for the accepted Channels
.childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 1)
}
private final class PrometheusHTTPHandler: ChannelInboundHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias OutboundOut = HTTPServerResponsePart
var exporter: PrometheusExporter
init(exporter: PrometheusExporter) {
self.exporter = exporter
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let reqPart = unwrapInboundIn(data)
switch reqPart {
case let .head(request):
if request.uri.unicodeScalars.starts(with: "/metrics".unicodeScalars) {
let channel = context.channel
let head = HTTPResponseHead(version: request.version,
status: .ok)
let part = HTTPServerResponsePart.head(head)
_ = channel.write(part)
let metrics = PrometheusExporterExtensions.writeMetricsCollection(exporter: exporter)
var buffer = channel.allocator.buffer(capacity: metrics.count)
buffer.writeString(metrics)
let bodypart = HTTPServerResponsePart.body(.byteBuffer(buffer))
_ = channel.write(bodypart)
let endpart = HTTPServerResponsePart.end(nil)
_ = channel.writeAndFlush(endpart).flatMap {
channel.close()
}
}
case .body:
break
case .end: break
}
}
// Flush it out. This can make use of gathering writes if multiple buffers are pending
public func channelReadComplete(context: ChannelHandlerContext) {
context.flush()
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
print("error: ", error)
// As we are not really interested getting notified on success or failure we just pass nil as promise to
// reduce allocations.
context.close(promise: nil)
}
}
}
| apache-2.0 | 92e6a8a3cd9d875aafa099887976452b | 35.364407 | 117 | 0.60289 | 5.5511 | false | false | false | false |
huangboju/Moots | 算法学习/数据结构/DataStructures/DataStructures/Classes/BinaryTree.swift | 1 | 2491 | //
// BinaryTree.swift
// DataStructures
//
// Created by 黄伯驹 on 2020/3/29.
// Copyright © 2020 黄伯驹. All rights reserved.
//
import Foundation
class TreeNode<T> {
var data: T
var leftNode: TreeNode?
var rightNode: TreeNode?
init(data: T,
leftNode: TreeNode? = nil,
rightNode: TreeNode? = nil) {
self.data = data
self.leftNode = leftNode
self.rightNode = rightNode
}
}
class BinaryTree<T: Comparable & CustomStringConvertible> {
private var rootNode: TreeNode<T>?
func insert(element: T) {
let node = TreeNode(data: element)
if let rootNode = self.rootNode {
self.insert(rootNode, node)
} else {
self.rootNode = node
}
}
// RECURSIVE FUNCTION
private func insert(_ rootNode: TreeNode<T>, _ node: TreeNode<T>) {
if rootNode.data > node.data {
if let leftNode = rootNode.leftNode {
self.insert(leftNode, node)
} else {
rootNode.leftNode = node
}
} else {
if let rightNode = rootNode.rightNode {
self.insert(rightNode, node)
} else {
rootNode.rightNode = node
}
}
}
}
extension BinaryTree {
func traverse() {
print("\nPRE-ORDER TRAVERSE")
self.preorder(self.rootNode)
print("\n\nIN-ORDER TRAVERSE")
self.inorder(self.rootNode)
print("\n\nPOST-ORDER TRAVERSE")
self.postorder(self.rootNode)
print("\n")
}
// NOTE : LEFT IS ALWAYS LEFT OF RIGHT
// NLR : NODE(i.e. Root/Parent Node) LEFT RIGHT
// LNR : LEFT NODE RIGHT
private func inorder(_ node: TreeNode<T>?) {
guard let _ = node else { return }
self.inorder(node?.leftNode)
print("\(node!.data)", terminator: " ")
self.inorder(node?.rightNode)
}
// NLR : NODE LEFT RIGHT
private func preorder(_ node: TreeNode<T>?) {
guard let _ = node else { return }
print("\(node!.data)", terminator: " ")
self.preorder(node?.leftNode)
self.preorder(node?.rightNode)
}
// LRN : LEFT RIGHT NODE
private func postorder(_ node: TreeNode<T>?) {
guard let _ = node else { return }
self.postorder(node?.leftNode)
self.postorder(node?.rightNode)
print("\(node!.data)", terminator: " ")
}
}
| mit | 0de2d79cd67217832313729542bbf7fa | 25.084211 | 71 | 0.546812 | 4.157718 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/wwdc_demo/ImageFeed/Layouts/MosaicLayout.swift | 1 | 5916 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Custom view flow layout for mosaic-style appearance.
*/
import UIKit
enum MosaicSegmentStyle {
case fullWidth
case fiftyFifty
case twoThirdsOneThird
case oneThirdTwoThirds
}
class MosaicLayout: UICollectionViewLayout {
var contentBounds = CGRect.zero
var cachedAttributes = [UICollectionViewLayoutAttributes]()
/// - Tag: PrepareMosaicLayout
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
// Reset cached information.
cachedAttributes.removeAll()
contentBounds = CGRect(origin: .zero, size: collectionView.bounds.size)
// For every item in the collection view:
// - Prepare the attributes.
// - Store attributes in the cachedAttributes array.
// - Combine contentBounds with attributes.frame.
let count = collectionView.numberOfItems(inSection: 0)
var currentIndex = 0
var segment: MosaicSegmentStyle = .fullWidth
var lastFrame: CGRect = .zero
let cvWidth = collectionView.bounds.size.width
while currentIndex < count {
let segmentFrame = CGRect(x: 0, y: lastFrame.maxY + 1.0, width: cvWidth, height: 200.0)
var segmentRects = [CGRect]()
switch segment {
case .fullWidth:
segmentRects = [segmentFrame]
case .fiftyFifty:
let horizontalSlices = segmentFrame.dividedIntegral(fraction: 0.5, from: .minXEdge)
segmentRects = [horizontalSlices.first, horizontalSlices.second]
case .twoThirdsOneThird:
let horizontalSlices = segmentFrame.dividedIntegral(fraction: (2.0 / 3.0), from: .minXEdge)
let verticalSlices = horizontalSlices.second.dividedIntegral(fraction: 0.5, from: .minYEdge)
segmentRects = [horizontalSlices.first, verticalSlices.first, verticalSlices.second]
case .oneThirdTwoThirds:
let horizontalSlices = segmentFrame.dividedIntegral(fraction: (1.0 / 3.0), from: .minXEdge)
let verticalSlices = horizontalSlices.first.dividedIntegral(fraction: 0.5, from: .minYEdge)
segmentRects = [verticalSlices.first, verticalSlices.second, horizontalSlices.second]
}
// Create and cache layout attributes for calculated frames.
for rect in segmentRects {
let attributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: currentIndex, section: 0))
attributes.frame = rect
cachedAttributes.append(attributes)
contentBounds = contentBounds.union(lastFrame)
currentIndex += 1
lastFrame = rect
}
// Determine the next segment style.
switch count - currentIndex {
case 1:
segment = .fullWidth
case 2:
segment = .fiftyFifty
default:
switch segment {
case .fullWidth:
segment = .fiftyFifty
case .fiftyFifty:
segment = .twoThirdsOneThird
case .twoThirdsOneThird:
segment = .oneThirdTwoThirds
case .oneThirdTwoThirds:
segment = .fiftyFifty
}
}
}
}
/// - Tag: CollectionViewContentSize
override var collectionViewContentSize: CGSize {
return contentBounds.size
}
/// - Tag: ShouldInvalidateLayout
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
guard let collectionView = collectionView else { return false }
return !newBounds.size.equalTo(collectionView.bounds.size)
}
/// - Tag: LayoutAttributesForItem
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cachedAttributes[indexPath.item]
}
/// - Tag: LayoutAttributesForElements
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributesArray = [UICollectionViewLayoutAttributes]()
// Find any cell that sits within the query rect.
guard let lastIndex = cachedAttributes.indices.last,
let firstMatchIndex = binSearch(rect, start: 0, end: lastIndex) else { return attributesArray }
// Starting from the match, loop up and down through the array until all the attributes
// have been added within the query rect.
for attributes in cachedAttributes[..<firstMatchIndex].reversed() {
guard attributes.frame.maxY >= rect.minY else { break }
attributesArray.append(attributes)
}
for attributes in cachedAttributes[firstMatchIndex...] {
guard attributes.frame.minY <= rect.maxY else { break }
attributesArray.append(attributes)
}
return attributesArray
}
// Perform a binary search on the cached attributes array.
func binSearch(_ rect: CGRect, start: Int, end: Int) -> Int? {
if end < start { return nil }
let mid = (start + end) / 2
let attr = cachedAttributes[mid]
if attr.frame.intersects(rect) {
return mid
} else {
if attr.frame.maxY < rect.minY {
return binSearch(rect, start: (mid + 1), end: end)
} else {
return binSearch(rect, start: start, end: (mid - 1))
}
}
}
}
| mit | 5d185247bd7b67f7679112949d0a152a | 36.66879 | 121 | 0.595536 | 5.5635 | false | false | false | false |
Czajnikowski/TrainTrippin | Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift | 3 | 10236 | //
// DelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#if SWIFT_PACKAGE && !os(Linux)
import RxCocoaRuntime
#endif
#endif
var delegateAssociatedTag: UInt8 = 0
var dataSourceAssociatedTag: UInt8 = 0
/**
Base class for `DelegateProxyType` protocol.
This implementation is not thread safe and can be used only from one thread (Main thread).
*/
open class DelegateProxy : _RXDelegateProxy {
private var sentMessageForSelector = [Selector: PublishSubject<[Any]>]()
private var methodInvokedForSelector = [Selector: PublishSubject<[Any]>]()
/**
Parent object associated with delegate proxy.
*/
weak private(set) var parentObject: AnyObject?
/**
Initializes new instance.
- parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object.
*/
public required init(parentObject: AnyObject) {
self.parentObject = parentObject
MainScheduler.ensureExecutingOnScheduler()
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
super.init()
}
/**
Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*.
Only methods that have `void` return value can be observed using this method because
those methods are used as a notification mechanism. It doesn't matter if they are optional
or not. Observing is performed by installing a hidden associated `PublishSubject` that is
used to dispatch messages to observers.
Delegate methods that have non `void` return value can't be observed directly using this method
because:
* those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism
* there is no sensible automatic way to determine a default return value
In case observing of delegate methods that have return type is required, it can be done by
manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method.
e.g.
// delegate proxy part (RxScrollViewDelegateProxy)
let internalSubject = PublishSubject<CGPoint>
public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool {
internalSubject.on(.next(arg1))
return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue
}
....
// reactive property implementation in a real class (`UIScrollView`)
public var property: Observable<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxyForObject(base)
return proxy.internalSubject.asObservable()
}
**In case calling this method prints "Delegate proxy is already implementing `\(selector)`,
a more performant way of registering might exist.", that means that manual observing method
is required analog to the example above because delegate method has already been implemented.**
- parameter selector: Selector used to filter observed invocations of delegate methods.
- returns: Observable sequence of arguments passed to `selector` method.
*/
open func sentMessage(_ selector: Selector) -> Observable<[Any]> {
checkSelectorIsObservable(selector)
let subject = sentMessageForSelector[selector]
if let subject = subject {
return subject
}
else {
let subject = PublishSubject<[Any]>()
sentMessageForSelector[selector] = subject
return subject
}
}
/**
Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*.
Only methods that have `void` return value can be observed using this method because
those methods are used as a notification mechanism. It doesn't matter if they are optional
or not. Observing is performed by installing a hidden associated `PublishSubject` that is
used to dispatch messages to observers.
Delegate methods that have non `void` return value can't be observed directly using this method
because:
* those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism
* there is no sensible automatic way to determine a default return value
In case observing of delegate methods that have return type is required, it can be done by
manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method.
e.g.
// delegate proxy part (RxScrollViewDelegateProxy)
let internalSubject = PublishSubject<CGPoint>
public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool {
internalSubject.on(.next(arg1))
return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue
}
....
// reactive property implementation in a real class (`UIScrollView`)
public var property: Observable<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxyForObject(base)
return proxy.internalSubject.asObservable()
}
**In case calling this method prints "Delegate proxy is already implementing `\(selector)`,
a more performant way of registering might exist.", that means that manual observing method
is required analog to the example above because delegate method has already been implemented.**
- parameter selector: Selector used to filter observed invocations of delegate methods.
- returns: Observable sequence of arguments passed to `selector` method.
*/
open func methodInvoked(_ selector: Selector) -> Observable<[Any]> {
checkSelectorIsObservable(selector)
let subject = methodInvokedForSelector[selector]
if let subject = subject {
return subject
}
else {
let subject = PublishSubject<[Any]>()
methodInvokedForSelector[selector] = subject
return subject
}
}
private func checkSelectorIsObservable(_ selector: Selector) {
MainScheduler.ensureExecutingOnScheduler()
if hasWiredImplementation(for: selector) {
print("Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.")
}
// It's important to see if super class reponds to selector and not self,
// because super class (_RxDelegateProxy) returns all methods delegate proxy
// can respond to.
// Because of https://github.com/ReactiveX/RxSwift/issues/907 , and possibly
// some other reasons, subclasses could overrride `responds(to:)`, but it shouldn't matter
// for this case.
if !super.responds(to: selector) {
rxFatalError("This class doesn't respond to selector \(selector)")
}
}
@available(*, deprecated, renamed: "methodInvoked")
open func observe(_ selector: Selector) -> Observable<[Any]> {
return sentMessage(selector)
}
// proxy
open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) {
sentMessageForSelector[selector]?.on(.next(arguments))
}
open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) {
methodInvokedForSelector[selector]?.on(.next(arguments))
}
/**
Returns tag used to identify associated object.
- returns: Associated object tag.
*/
open class func delegateAssociatedObjectTag() -> UnsafeRawPointer {
return _pointer(&delegateAssociatedTag)
}
/**
Initializes new instance of delegate proxy.
- returns: Initialized instance of `self`.
*/
open class func createProxyForObject(_ object: AnyObject) -> AnyObject {
return self.init(parentObject: object)
}
/**
Returns assigned proxy for object.
- parameter object: Object that can have assigned delegate proxy.
- returns: Assigned delegate proxy or `nil` if no delegate proxy is assigned.
*/
open class func assignedProxyFor(_ object: AnyObject) -> AnyObject? {
let maybeDelegate = objc_getAssociatedObject(object, self.delegateAssociatedObjectTag())
return castOptionalOrFatalError(maybeDelegate.map { $0 as AnyObject })
}
/**
Assigns proxy to object.
- parameter object: Object that can have assigned delegate proxy.
- parameter proxy: Delegate proxy object to assign to `object`.
*/
open class func assignProxy(_ proxy: AnyObject, toObject object: AnyObject) {
precondition(proxy.isKind(of: self.classForCoder()))
objc_setAssociatedObject(object, self.delegateAssociatedObjectTag(), proxy, .OBJC_ASSOCIATION_RETAIN)
}
/**
Sets reference of normal delegate that receives all forwarded messages
through `self`.
- parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
- parameter retainDelegate: Should `self` retain `forwardToDelegate`.
*/
open func setForwardToDelegate(_ delegate: AnyObject?, retainDelegate: Bool) {
self._setForward(toDelegate: delegate, retainDelegate: retainDelegate)
}
/**
Returns reference of normal delegate that receives all forwarded messages
through `self`.
- returns: Value of reference if set or nil.
*/
open func forwardToDelegate() -> AnyObject? {
return self._forwardToDelegate
}
deinit {
for v in sentMessageForSelector.values {
v.on(.completed)
}
for v in methodInvokedForSelector.values {
v.on(.completed)
}
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
// MARK: Pointer
class func _pointer(_ p: UnsafeRawPointer) -> UnsafeRawPointer {
return p
}
}
#endif
| mit | 0cf3547871e122bde4a9675d2dac4dad | 35.423488 | 124 | 0.679336 | 5.372703 | false | false | false | false |
debugsquad/nubecero | nubecero/View/OnboardForm/VOnboardFormHeader.swift | 1 | 3649 | import UIKit
class VOnboardFormHeader:UICollectionReusableView
{
private weak var controller:COnboardForm?
private weak var labelTitle:UILabel!
private let kButtonCancelWidth:CGFloat = 100
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.image = #imageLiteral(resourceName: "assetGenericLogoNegative")
let buttonCancel:UIButton = UIButton()
buttonCancel.translatesAutoresizingMaskIntoConstraints = false
buttonCancel.clipsToBounds = true
buttonCancel.setTitleColor(UIColor.main, for:UIControlState.normal)
buttonCancel.setTitleColor(UIColor.black, for:UIControlState.highlighted)
buttonCancel.setTitle(
NSLocalizedString("VOnboardFormHeader_buttonCancel", comment:""),
for:UIControlState.normal)
buttonCancel.titleLabel!.font = UIFont.medium(size:18)
buttonCancel.addTarget(
self,
action:#selector(actionCancel(sender:)),
for:UIControlEvents.touchUpInside)
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.font = UIFont.regular(size:18)
labelTitle.textColor = UIColor.black
self.labelTitle = labelTitle
addSubview(imageView)
addSubview(labelTitle)
addSubview(buttonCancel)
let views:[String:UIView] = [
"imageView":imageView,
"buttonCancel":buttonCancel,
"labelTitle":labelTitle]
let metrics:[String:CGFloat] = [
"buttonCancelWidth":kButtonCancelWidth]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[imageView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[buttonCancel(buttonCancelWidth)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-20-[labelTitle(250)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-20-[buttonCancel(44)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-22-[imageView(40)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:[labelTitle(20)]-15-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
//MARK: actions
func actionCancel(sender button:UIButton)
{
controller?.cancel()
}
//MARK: config
func config(controller:COnboardForm)
{
self.controller = controller
labelTitle.text = controller.model.title
}
}
| mit | 4fdcc14f038c50b835fb43aa885a55f0 | 33.102804 | 81 | 0.623733 | 5.981967 | false | false | false | false |
fonkadelic/Macoun | WoidKonf/Behaviours/TextValidationBehaviour.swift | 1 | 1334 | //
// TextValidationBehaviour.swift
// WoidKonf
//
// Copyright © 2017 Raised by Wolves. All rights reserved.
//
import UIKit
@objc protocol TextValidationRule {
func evaluate(with string: String) -> Bool
}
final class TextLengthRule: NSObject, TextValidationRule {
@IBInspectable var minCharacterCount: Int = 0
@IBInspectable var maxCharacterCount: Int = 255
func evaluate(with string: String) -> Bool {
let range = minCharacterCount...maxCharacterCount
return range.contains(string.count)
}
}
class TextValidationBehaviour: Behaviour {
@IBOutlet var rules: [TextValidationRule]!
@IBOutlet var controls: [UIControl]! {
didSet {
updateValidation()
}
}
@IBOutlet weak var textField: UITextField? {
didSet {
guard let textField = textField else { return }
textField.addTarget(self, action: #selector(updateValidation), for: .editingChanged)
updateValidation()
}
}
func validateText() -> Bool {
let text = textField?.text ?? ""
return !rules.contains { !$0.evaluate(with: text) }
}
@objc private func updateValidation() {
let isValid = validateText()
controls?.forEach { $0.isEnabled = isValid }
sendActions(for: .valueChanged)
}
}
| mit | 3ca2cbd246d05739d5cf64de19a0f629 | 25.137255 | 96 | 0.63991 | 4.518644 | false | false | false | false |
proxyco/RxBluetoothKit | Source/Service.swift | 1 | 4160 | // The MIT License (MIT)
//
// Copyright (c) 2016 Polidea
//
// 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 CoreBluetooth
import RxSwift
// swiftlint:disable line_length
/**
Service is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with [`CBService`](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBService_Class/)
*/
public class Service {
let service: RxServiceType
/// Peripheral to which this service belongs
public let peripheral: Peripheral
/// True if service is primary service
public var isPrimary: Bool {
return service.isPrimary
}
/// Service's UUID
public var UUID: CBUUID {
return service.uuid
}
/// Service's included services
public var includedServices: [Service]? {
return service.includedServices?.map {
Service(peripheral: peripheral, service: $0)
} ?? nil
}
/// Service's characteristics
public var characteristics: [Characteristic]? {
return service.characteristics?.map {
Characteristic(characteristic: $0, service: self)
} ?? nil
}
init(peripheral: Peripheral, service: RxServiceType) {
self.service = service
self.peripheral = peripheral
}
/**
Function that triggers characteristics discovery for specified Services and identifiers. Discovery is called after
subscribtion to `Observable` is made.
- Parameter identifiers: Identifiers of characteristics that should be discovered. If `nil` - all of the
characteristics will be discovered. If you'll pass empty array - none of them will be discovered.
- Returns: Observable that emits `Next` with array of `Characteristic` instances, once they're discovered.
Immediately after that `.Complete` is emitted.
*/
public func discoverCharacteristics(identifiers: [CBUUID]?) -> Observable<[Characteristic]> {
return peripheral.discoverCharacteristics(identifiers, service: self)
}
/**
Function that triggers included services discovery for specified services. Discovery is called after
subscribtion to `Observable` is made.
- Parameter includedServiceUUIDs: Identifiers of included services that should be discovered. If `nil` - all of the
included services will be discovered. If you'll pass empty array - none of them will be discovered.
- Returns: Observable that emits `Next` with array of `Service` instances, once they're discovered.
Immediately after that `.Complete` is emitted.
*/
public func discoverIncludedServices(includedServiceUUIDs: [CBUUID]?) -> Observable<[Service]> {
return peripheral.discoverIncludedServices(includedServiceUUIDs, forService: self)
}
}
extension Service: Equatable {}
/**
Compare if services are equal. They are if theirs uuids are the same.
- parameter lhs: First service
- parameter rhs: Second service
- returns: True if services are the same.
*/
public func == (lhs: Service, rhs: Service) -> Bool {
return lhs.service == rhs.service
}
| mit | d449ecb2bfa42c4916d361ae980e26c2 | 39.38835 | 216 | 0.724279 | 4.9642 | false | false | false | false |
kidaa/codecombat-ios | CodeCombat/TomeInventoryViewController.swift | 2 | 7899 | //
// TomeInventoryViewController.swift
// CodeCombat
//
// Created by Michael Schmatz on 8/11/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
import UIKit
class TomeInventoryViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
private var inventory: TomeInventory!
private var inventoryLoaded = false
var inventoryView: UIScrollView!
private var draggedView: UIView!
private var draggedProperty: TomeInventoryItemProperty!
init() {
inventory = TomeInventory()
super.init(nibName: "", bundle: nil)
}
required convenience init?(coder aDecoder: NSCoder) {
self.init()
}
override func viewDidLoad() {
super.viewDidLoad()
inventoryView = UIScrollView()
inventoryView.delegate = self
let DragAndDropRecognizer = UIPanGestureRecognizer(
target: self,
action: "handleDrag:")
DragAndDropRecognizer.delegate = self
inventoryView.addGestureRecognizer(DragAndDropRecognizer)
inventoryView.panGestureRecognizer.requireGestureRecognizerToFail(DragAndDropRecognizer)
inventoryView.bounces = false
inventoryView.backgroundColor = UIColor.clearColor()
view.addSubview(inventoryView)
addScriptMessageNotificationObservers()
}
func setUpInventory() {
let subviewsToRemove = inventoryView.subviews
for var index = subviewsToRemove.count - 1; index >= 0; --index {
subviewsToRemove[index].removeFromSuperview()
}
var itemHeight = 0
let itemMargin = 3
for item in inventory.items {
let width = Int(inventoryView.frame.width) - itemMargin
let height = Int(inventoryView.frame.height) - itemHeight - itemMargin
let itemFrame = CGRect(x: itemMargin / 2, y: itemHeight + itemMargin / 2, width: width, height: height)
let itemView = TomeInventoryItemView(item: item, frame: itemFrame)
if itemView.showsProperties {
inventoryView.addSubview(itemView)
itemHeight += Int(itemView.frame.height) + itemMargin
}
}
inventoryView.contentSize = CGSize(width: inventoryView.frame.width, height: CGFloat(itemHeight))
}
private func addScriptMessageNotificationObservers() {
// let webManager = WebManager.sharedInstance
// webManager.subscribe(self, channel: "tome:palette-cleared", selector: Selector("onInventoryCleared:"))
// webManager.subscribe(self, channel: "tome:palette-updated", selector: Selector("onInventoryUpdated:"))
}
func onInventoryCleared(note: NSNotification) {
//println("inventory cleared: \(note)")
}
func onInventoryUpdated(note: NSNotification) {
if inventoryLoaded { return }
inventoryLoaded = true
inventory = TomeInventory()
let userInfo = note.userInfo as! [String: AnyObject]
let entryGroupsJSON = userInfo["entryGroups"] as! String
let entryGroups = JSON.parse(entryGroupsJSON)
for (entryGroupName, entryGroup) in entryGroups.asDictionary! {
let entries = entryGroup["props"].asArray!
let entryNames: [String] = entries.map({entry in entry["name"].asString!}) as [String]
let entryNamesJSON = entryNames.joinWithSeparator("\", \"")
var imageInfoData = entryGroup["item"].asDictionary!
let imageURL = imageInfoData["imageURL"]!
let itemDataJSON = "{\"name\":\"\(entryGroupName)\",\"programmableProperties\":[\"\(entryNamesJSON)\"],\"imageURL\":\"\(imageURL)\"}"
let itemData = JSON.parse(itemDataJSON)
let item = TomeInventoryItem(itemData: itemData)
for entry in entries {
let property = TomeInventoryItemProperty(propertyData: entry, primary: true)
item.addProperty(property)
}
inventory.addInventoryItem(item)
}
setUpInventory()
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
//Make more specific to simultaneous uipangesturerecognizers if other gesture recognizers fire unintentionally
return true
}
func handleDrag(recognizer:UIPanGestureRecognizer) {
if recognizer == inventoryView.panGestureRecognizer {
return
}
let Parent = parentViewController as! PlayViewController
//Change this to reference editor view controller, rather than editor view
let EditorView = Parent.textViewController.textView
let LocationInParentView = recognizer.locationInView(Parent.view)
let LocationInEditorContainerView = recognizer.locationInView(Parent.editorContainerView)
let locationInEditorTextView = recognizer.locationInView(Parent.textViewController.textView)
switch recognizer.state {
case .Began:
//Find the item view which received the click
let ItemView:TomeInventoryItemView! = itemViewAtLocation(recognizer.locationInView(inventoryView))
if ItemView == nil || ItemView.tomeInventoryItemPropertyAtLocation(recognizer.locationInView(ItemView)) == nil {
// This weird code is the way to get the drag and drop recognizer to send
// failure to the scroll gesture recognizer
recognizer.enabled = false
recognizer.enabled = true
break
}
recognizer.enabled = true
let ItemProperty = ItemView.tomeInventoryItemPropertyAtLocation(recognizer.locationInView(ItemView))
draggedProperty = ItemProperty
let DragView = UILabel()
DragView.font = EditorView.font
let adjustedCodeSnippet = Parent.textViewController.replacePlaceholderInString(ItemProperty!.codeSnippetForLanguage("python")!, replacement: "")
DragView.text = adjustedCodeSnippet
DragView.sizeToFit()
DragView.center = LocationInParentView
DragView.backgroundColor = UIColor.clearColor()
Parent.view.addSubview(DragView)
draggedView = DragView
Parent.textViewController.handleItemPropertyDragBegan()
break
case .Changed:
let yDelta = LocationInParentView.y - draggedView.center.y
draggedView.center = LocationInParentView
Parent.textViewController.handleItemPropertyDragChangedAtLocation(locationInEditorTextView,
locParentView: LocationInParentView,
yDelta: yDelta)
if EditorView.frame.contains(LocationInEditorContainerView) {
var Snippet = draggedProperty.codeSnippetForLanguage("python")
if Snippet != nil {
Snippet = draggedProperty.name
}
} else {
EditorView.removeLineDimmingOverlay()
}
break
case .Ended:
draggedView.removeFromSuperview()
var Snippet = draggedProperty.codeSnippetForLanguage("python")
if Snippet == nil {
Snippet = draggedProperty.name
}
if EditorView.frame.contains(LocationInEditorContainerView) {
Parent.textViewController.handleItemPropertyDragEndedAtLocation(locationInEditorTextView, code: Snippet!)
} else {
EditorView.removeDragHintView()
EditorView.removeLineDimmingOverlay()
}
draggedView = nil
break
default:
break
}
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if draggedView != nil {
return false
}
if gestureRecognizer != inventoryView.panGestureRecognizer && gestureRecognizer is UIPanGestureRecognizer {
if itemViewAtLocation(gestureRecognizer.locationInView(inventoryView)) == nil {
return false
}
}
return true
}
func itemViewAtLocation(location:CGPoint) -> TomeInventoryItemView! {
var ItemView:TomeInventoryItemView! = nil
for subview in inventoryView.subviews {
if subview is TomeInventoryItemView && subview.frame.contains(location) {
ItemView = subview as! TomeInventoryItemView
}
}
return ItemView
}
override func loadView() {
view = UIView(frame: UIScreen.mainScreen().bounds)
}
}
| mit | 5c7ed3c1c208e835410ee789708b05c7 | 37.91133 | 170 | 0.718952 | 5.297787 | false | false | false | false |
benlangmuir/swift | test/attr/attr_discardableResult.swift | 4 | 6499 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
// ---------------------------------------------------------------------------
// Mark function's return value as discardable and silence warning
// ---------------------------------------------------------------------------
@discardableResult
func f1() -> [Int] { }
func f2() -> [Int] { }
func f3() { }
func f4<R>(blah: () -> R) -> R { return blah() }
func testGlobalFunctions() -> [Int] {
f1() // okay
f2() // expected-warning {{result of call to 'f2()' is unused}}
_ = f2() // okay
f3() // okay
f4 { 5 } // expected-warning {{result of call to 'f4(blah:)' is unused}}
f4 { } // okay
return f2() // okay
}
attr_discardableResult.f1()
attr_discardableResult.f2() // expected-warning {{result of call to 'f2()' is unused}}
class C1 {
@discardableResult
static func f1Static() -> Int { }
static func f2Static() -> Int { }
@discardableResult
class func f1Class() -> Int { }
class func f2Class() -> Int { }
@discardableResult init() { }
init(foo: Int) { }
@discardableResult
func f1() -> Int { }
func f2() -> Int { }
@discardableResult
func f1Optional() -> Int? { }
func f2Optional() -> Int? { }
@discardableResult
func me() -> Self { return self }
func reallyMe() -> Self { return self }
}
class C2 : C1 {}
func testFunctionsInClass(c1 : C1, c2: C2) {
C1.f1Static() // okay
C1.f2Static() // expected-warning {{result of call to 'f2Static()' is unused}}
_ = C1.f2Static() // okay
C1.f1Class() // okay
C1.f2Class() // expected-warning {{result of call to 'f2Class()' is unused}}
_ = C1.f2Class() // okay
C1() // okay, marked @discardableResult
_ = C1() // okay
C1(foo: 5) // expected-warning {{result of 'C1' initializer is unused}}
_ = C1(foo: 5) // okay
c1.f1() // okay
c1.f2() // expected-warning {{result of call to 'f2()' is unused}}
_ = c1.f2() // okay
c1.f1Optional() // okay
c1.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}}
_ = c1.f2Optional() // okay
c1.me() // okay
c2.me() // okay
c1.reallyMe() // expected-warning {{result of call to 'reallyMe()' is unused}}
c2.reallyMe() // expected-warning {{result of call to 'reallyMe()' is unused}}
_ = c1.reallyMe() // okay
_ = c2.reallyMe() // okay
}
struct S1 {
@discardableResult
static func f1Static() -> Int { }
static func f2Static() -> Int { }
@discardableResult init() { }
init(foo: Int) { }
@discardableResult
func f1() -> Int { }
func f2() -> Int { }
@discardableResult
func f1Optional() -> Int? { }
func f2Optional() -> Int? { }
}
func testFunctionsInStruct(s1 : S1) {
S1.f1Static() // okay
S1.f2Static() // expected-warning {{result of call to 'f2Static()' is unused}}
_ = S1.f2Static() // okay
S1() // okay, marked @discardableResult
_ = S1() // okay
S1(foo: 5) // expected-warning {{result of 'S1' initializer is unused}}
_ = S1(foo: 5) // okay
s1.f1() // okay
s1.f2() // expected-warning {{result of call to 'f2()' is unused}}
_ = s1.f2() // okay
s1.f1Optional() // okay
s1.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}}
_ = s1.f2Optional() // okay
}
protocol P1 {
@discardableResult
func me() -> Self
func reallyMe() -> Self
}
func testFunctionsInExistential(p1 : P1) {
p1.me() // okay
p1.reallyMe() // expected-warning {{result of call to 'reallyMe()' is unused}}
_ = p1.reallyMe() // okay
}
let x = 4
"Hello \(x+1) world" // expected-warning {{string literal is unused}}
func f(a : () -> Int) {
42 // expected-warning {{integer literal is unused}}
4 + 5 // expected-warning {{result of operator '+' is unused}}
a() // expected-warning {{result of call to function returning 'Int' is unused}}
}
@warn_unused_result func g() -> Int { } // expected-warning {{'warn_unused_result' attribute behavior is now the default}} {{1-21=}}
class X {
@warn_unused_result // expected-warning {{'warn_unused_result' attribute behavior is now the default}} {{3-23=}}
@objc
func h() -> Int { }
}
func testOptionalChaining(c1: C1?, s1: S1?) {
c1?.f1() // okay
c1!.f1() // okay
c1?.f1Optional() // okay
c1!.f1Optional() // okay
c1?.f2() // expected-warning {{result of call to 'f2()' is unused}}
c1!.f2() // expected-warning {{result of call to 'f2()' is unused}}
c1?.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}}
c1!.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}}
s1?.f1() // okay
s1!.f1() // okay
s1?.f1Optional() // okay
s1!.f1Optional() // okay
s1?.f2() // expected-warning {{result of call to 'f2()' is unused}}
s1!.f2() // expected-warning {{result of call to 'f2()' is unused}}
s1?.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}}
s1!.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}}
}
// https://github.com/apple/swift/issues/45542
@discardableResult func f_45542(_ closure: @escaping ()->()) -> (()->()) {
closure()
return closure
}
do {
f_45542({}) // okay
}
// https://github.com/apple/swift/issues/50104
class C1_50104 {
@discardableResult required init(input: Int) { }
}
class C2_50104 : C1_50104 {}
do {
C1_50104(input: 10) // okay
C2_50104(input: 10) // okay
}
protocol FooProtocol {}
extension FooProtocol {
@discardableResult
static func returnSomething() -> Bool? {
return true
}
}
class Foo {
var myOptionalFooProtocol: FooProtocol.Type?
func doSomething() {
myOptionalFooProtocol?.returnSomething() // okay
}
}
class Discard {
@discardableResult func bar() -> Int {
return 0
}
func baz() {
self.bar // expected-error {{function is unused}}
bar // expected-error {{function is unused}}
}
}
// https://github.com/apple/swift/issues/54699
struct S_54699 {
@discardableResult
func bar1() -> () -> Void {
return {}
}
@discardableResult
static func bar2() -> () -> Void {
return {}
}
}
do {
S_54699().bar1() // Okay
S_54699.bar2() // Okay
S_54699().bar1 // expected-error {{function is unused}}
S_54699.bar2 // expected-error {{function is unused}}
}
| apache-2.0 | 545ef72a817dc1fc9176be0fc1859e22 | 24.996 | 132 | 0.574088 | 3.304016 | false | false | false | false |
walkingsmarts/ReactiveCocoa | ReactiveCocoaTests/AppKit/NSImageViewSpec.swift | 1 | 1153 | import Quick
import Nimble
import ReactiveSwift
import ReactiveCocoa
import AppKit
import enum Result.NoError
class NSImageViewSpec: QuickSpec {
override func spec() {
var imageView: NSImageView!
weak var _imageView: NSImageView?
beforeEach {
imageView = NSImageView(frame: .zero)
_imageView = imageView
}
afterEach {
imageView = nil
expect(_imageView).to(beNil())
}
it("should accept changes from bindings to its enabling state") {
imageView.isEnabled = false
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
imageView.reactive.isEnabled <~ SignalProducer(pipeSignal)
observer.send(value: true)
expect(imageView.isEnabled) == true
observer.send(value: false)
expect(imageView.isEnabled) == false
}
it("should accept changes from bindings to its image") {
let (pipeSignal, observer) = Signal<NSImage?, NoError>.pipe()
imageView.reactive.image <~ SignalProducer(pipeSignal)
let theImage = NSImage(named: NSImageNameUser)
observer.send(value: theImage)
expect(imageView.image) == theImage
observer.send(value: nil)
expect(imageView.image).to(beNil())
}
}
}
| mit | 3a0f5d6efb6a0eab728f23b91d236fea | 21.607843 | 67 | 0.718994 | 3.882155 | false | false | false | false |
domenicosolazzo/practice-swift | Multimedia/Capturing Thumbnails from Video Files/Capturing Thumbnails from Video Files/ViewController.swift | 1 | 5318 | //
// ViewController.swift
// Capturing Thumbnails from Video Files
//
// Created by Domenico on 23/05/15.
// License MIT
//
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var moviePlayer: MPMoviePlayerController?
var playButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
playButton = UIButton(type:.system) as UIButton
if let button = playButton{
/* Add our button to the screen. Pressing this button
will start the video playback */
button.frame = CGRect(x: 0, y: 0, width: 70, height: 37)
button.center = view.center
button.autoresizingMask =
.flexibleBottomMargin
button.addTarget(self,
action: #selector(ViewController.startPlayingVideo),
for: .touchUpInside)
button.setTitle("Play", for: UIControlState())
view.addSubview(button)
}
}
func videoHasFinishedPlaying(_ notification: Notification){
print("Video finished playing")
/* Find out what the reason was for the player to stop */
let reason =
(notification as NSNotification).userInfo![MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]
as! NSNumber?
if let theReason = reason{
let reasonValue = MPMovieFinishReason(rawValue: theReason.intValue)
switch reasonValue!{
case .playbackEnded:
/* The movie ended normally */
print("Playback Ended")
case .playbackError:
/* An error happened and the movie ended */
print("Error happened")
case .userExited:
/* The user exited the player */
print("User exited")
default:
print("Another event happened")
}
print("Finish Reason = \(theReason)")
stopPlayingVideo()
}
}
func videoThumbnailIsAvailable(_ notification: Notification){
if moviePlayer != nil{
print("Thumbnail is available")
/* Now get the thumbnail out of the user info dictionary */
let thumbnail =
(notification as NSNotification).userInfo![MPMoviePlayerThumbnailImageKey] as? UIImage
if let image = thumbnail{
/* We got the thumbnail image. You can now use it here */
print("Thumbnail image = \(image)")
}
}
}
func stopPlayingVideo() {
if let player = moviePlayer{
NotificationCenter.default.removeObserver(self)
player.stop()
player.view.removeFromSuperview()
}
}
func startPlayingVideo(){
/* First let's construct the URL of the file in our application bundle
that needs to get played by the movie player */
let mainBundle = Bundle.main
let url = mainBundle.url(forResource: "Sample", withExtension: "m4v")
/* If we have already created a movie player before,
let's try to stop it */
if moviePlayer != nil{
stopPlayingVideo()
}
/* Now create a new movie player using the URL */
moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = moviePlayer{
/* Listen for the notification that the movie player sends us
whenever it finishes playing */
NotificationCenter.default.addObserver(self,
selector: #selector(ViewController.videoHasFinishedPlaying(_:)),
name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(ViewController.videoThumbnailIsAvailable(_:)),
name: NSNotification.Name.MPMoviePlayerThumbnailImageRequestDidFinish,
object: nil)
print("Successfully instantiated the movie player")
/* Scale the movie player to fit the aspect ratio */
player.scalingMode = .aspectFit
view.addSubview(player.view)
player.setFullscreen(true, animated: true)
/* Let's start playing the video in full screen mode */
player.play()
/* Capture the frame at the third second into the movie */
let thirdSecondThumbnail = 3.0
/* We can ask to capture as many frames as we
want. But for now, we are just asking to capture one frame
Ask the movie player to capture this frame for us */
player.requestThumbnailImages(atTimes: [thirdSecondThumbnail],
timeOption: .nearestKeyFrame)
} else {
print("Failed to instantiate the movie player")
}
}
}
| mit | e33ba27c837a90bee58f96fdc55c7422 | 32.031056 | 99 | 0.54513 | 6.070776 | false | false | false | false |
andrealufino/Luminous | Sources/Luminous/Luminous+Carrier.swift | 1 | 2497 | //
// Luminous+Carrier.swift
// Luminous
//
// Created by Andrea Mario Lufino on 10/11/2019.
//
import CoreTelephony
import Foundation
extension Luminous {
// MARK: Carrier
/// The Carrier information.
public struct Carrier {
/// The name of the carrier or nil if not available.
public static var name: String? {
let netInfo = CTTelephonyNetworkInfo()
if let carrier = netInfo.subscriberCellularProvider {
return carrier.carrierName
}
return nil
}
/// The carrier ISO code or nil if not available.
public static var ISOCountryCode: String? {
let netInfo = CTTelephonyNetworkInfo()
if let carrier = netInfo.subscriberCellularProvider {
return carrier.isoCountryCode
}
return nil
}
/// The carrier mobile country code or nil if not available.
public static var mobileCountryCode: String? {
let netInfo = CTTelephonyNetworkInfo()
if let carrier = netInfo.subscriberCellularProvider {
return carrier.mobileCountryCode
}
return nil
}
/// The carrier network country code or nil if not available
@available(*, deprecated, message: "Use mobileNetworkCode instead")
public static var networkCountryCode: String? {
let netInfo = CTTelephonyNetworkInfo()
if let carrier = netInfo.subscriberCellularProvider {
return carrier.mobileNetworkCode
}
return nil
}
/// The carrier network country code or nil if not available.
public static var mobileNetworkCode: String? {
let netInfo = CTTelephonyNetworkInfo()
if let carrier = netInfo.subscriberCellularProvider {
return carrier.mobileNetworkCode
}
return nil
}
/// Check if the carrier allows Voip.
public static var isVoipAllowed: Bool? {
let netInfo = CTTelephonyNetworkInfo()
if let carrier = netInfo.subscriberCellularProvider {
return carrier.allowsVOIP
}
return nil
}
}
}
| mit | 6f43396047810ac65f4a72952a22c53d | 27.701149 | 75 | 0.539848 | 6.519582 | false | false | false | false |
tipparti/PodImage | PodImage/ImageLRUCache.swift | 1 | 2472 | //
// ImageLRUCache.swift
// PodImage
//
// Created by Etienne Goulet-Lang on 12/4/16.
// Copyright © 2016 Etienne Goulet-Lang. All rights reserved.
//
import Foundation
import BaseUtils
open class ImageLRUCache: LRUCache<String, UIImage> {
public init(lruName: String) {
super.init()
self.lruName = lruName
self.load()
}
open var lruName: String!
open func get(entryForKey key: String) -> ImageCacheEntry? {
return self.get(objForKey: key) as? ImageCacheEntry
}
open func new(string: String) -> String? {
return string
}
open func get(imageForKey key: String) -> UIImage? {
return self.get(objForKey: key)?.value
}
open func get(etagForKey key: String) -> String? {
return (self.get(objForKey: key) as? ImageCacheEntry)?.etag
}
open func get(lastModifiedForKey key: String) -> String? {
return (self.get(objForKey: key) as? ImageCacheEntry)?.lastModified
}
open func put(key: String, image: UIImage) {
self.put(key: key, obj: ImageCacheEntry(image: image))
}
open func put(key: String, image: UIImage, etag: String?, lastModified: String?) {
self.put(key: key, obj: ImageCacheEntry(image: image, etag: etag, lastModified: lastModified))
}
open func save() {
let data: Data = NSKeyedArchiver.archivedData(withRootObject: self.getCache())
do {
let fileURL = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true).appendingPathComponent(lruName)
try data.write(to: fileURL, options: .atomic)
} catch {
print(error)
}
}
open func load() {
do {
let fileURL = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true).appendingPathComponent(lruName)
let data = try Data(contentsOf: fileURL)
let dictionary = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String : ImageCacheEntry]
self.setCache(cache: dictionary)
} catch {
print(error)
}
}
}
| mit | 2a2ca8363a295770c6a35ae384db688b | 28.771084 | 105 | 0.559692 | 4.575926 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAccountPicker/Tests/AccountPickerRowViewTests.swift | 1 | 11708 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainNamespace
import ComposableArchitecture
@testable import FeatureAccountPickerUI
import FeatureCardPaymentDomain
import MoneyKit
@testable import PlatformKit
@testable import PlatformKitMock
@testable import PlatformUIKit
import RxSwift
import SnapshotTesting
import SwiftUI
import XCTest
class AccountPickerRowViewTests: XCTestCase {
var isShowingMultiBadge = false
let accountGroupIdentifier = UUID()
let singleAccountIdentifier = UUID()
lazy var accountGroup = AccountPickerRow.AccountGroup(
id: accountGroupIdentifier,
title: "All Wallets",
description: "Total Balance"
)
lazy var singleAccount = AccountPickerRow.SingleAccount(
id: singleAccountIdentifier,
title: "BTC Trading Wallet",
description: "Bitcoin"
)
lazy var linkedBankAccountModel = AccountPickerRow.LinkedBankAccount(
id: self.linkedBankAccount.identifier,
title: "Title",
description: "Description"
)
// swiftlint:disable:next force_try
let linkedBankData = try! LinkedBankData(
response: LinkedBankResponse(
json: [
"id": "id",
"currency": "GBP",
"partner": "YAPILY",
"bankAccountType": "SAVINGS",
"name": "Name",
"accountName": "Account Name",
"accountNumber": "123456",
"routingNumber": "123456",
"agentRef": "040004",
"isBankAccount": false,
"isBankTransferAccount": true,
"state": "PENDING",
"attributes": [
"entity": "Safeconnect(UK)"
]
]
)
)!
lazy var linkedBankAccount = LinkedBankAccount(
label: "LinkedBankAccount",
accountNumber: "0",
accountId: "0",
bankAccountType: .checking,
currency: .USD,
paymentType: .bankAccount,
partner: .yapily,
data: linkedBankData
)
let paymentMethodFunds = PaymentMethodAccount(
paymentMethodType: .account(
FundData(
balance: .init(
currency: .fiat(.GBP),
available: .init(amount: 2500000, currency: .fiat(.GBP)),
withdrawable: .init(amount: 2500000, currency: .fiat(.GBP)),
pending: .zero(currency: .GBP)
),
max: .init(amount: 100000000, currency: .GBP)
)
),
paymentMethod: .init(
type: .funds(.fiat(.GBP)),
max: .init(amount: 1000000, currency: .GBP),
min: .init(amount: 500, currency: .GBP),
isEligible: true,
isVisible: true
),
priceService: PriceServiceMock()
)
let paymentMethodCard = PaymentMethodAccount(
paymentMethodType: .card(
CardData(
ownerName: "John Smith",
number: "4000 0000 0000 0000",
expirationDate: "12/30",
cvv: "000"
)!
),
paymentMethod: .init(
type: .card([.visa]),
max: .init(amount: 120000, currency: .USD),
min: .init(amount: 500, currency: .USD),
isEligible: true,
isVisible: true
),
priceService: PriceServiceMock()
)
private func paymentMethodRowModel(for account: PaymentMethodAccount) -> AccountPickerRow.PaymentMethod {
AccountPickerRow.PaymentMethod(
id: account.identifier,
title: account.label,
description: account.paymentMethodType.balance.displayString,
badgeView: account.logoResource.image,
badgeBackground: Color(account.logoBackgroundColor)
)
}
@ViewBuilder private func badgeView(for identifier: AnyHashable) -> some View {
switch identifier {
case singleAccount.id:
BadgeImageViewRepresentable(
viewModel: {
let model: BadgeImageViewModel = .default(
image: CryptoCurrency.bitcoin.logoResource,
cornerRadius: .round,
accessibilityIdSuffix: ""
)
model.marginOffsetRelay.accept(0)
return model
}(),
size: 32
)
case accountGroup.id:
BadgeImageViewRepresentable(
viewModel: {
let model: BadgeImageViewModel = .primary(
image: .local(name: "icon-wallet", bundle: .platformUIKit),
cornerRadius: .round,
accessibilityIdSuffix: "walletBalance"
)
model.marginOffsetRelay.accept(0)
return model
}(),
size: 32
)
case linkedBankAccountModel.id:
BadgeImageViewRepresentable(
viewModel: .default(
image: .local(name: "icon-bank", bundle: .platformUIKit),
cornerRadius: .round,
accessibilityIdSuffix: ""
),
size: 32
)
default:
EmptyView()
}
}
@ViewBuilder private func multiBadgeView(for identity: AnyHashable) -> some View {
if isShowingMultiBadge {
switch identity {
case linkedBankAccount.identifier:
MultiBadgeViewRepresentable(
viewModel: SingleAccountBadgeFactory(withdrawalService: MockWithdrawalServiceAPI())
.badge(account: linkedBankAccount, action: .withdraw)
.map {
MultiBadgeViewModel(
layoutMargins: LinkedBankAccountCellPresenter.multiBadgeInsets,
height: 24.0,
badges: $0
)
}
.asDriver(onErrorJustReturn: .init())
)
case singleAccount.id:
MultiBadgeViewRepresentable(
viewModel: .just(MultiBadgeViewModel(
layoutMargins: UIEdgeInsets(
top: 8,
left: 60,
bottom: 16,
right: 24
),
height: 24,
badges: [
DefaultBadgeAssetPresenter.makeLowFeesBadge(),
DefaultBadgeAssetPresenter.makeFasterBadge()
]
))
)
default:
EmptyView()
}
} else {
EmptyView()
}
}
@ViewBuilder private func iconView(for _: AnyHashable) -> some View {
BadgeImageViewRepresentable(
viewModel: {
let model: BadgeImageViewModel = .template(
image: .local(name: "ic-private-account", bundle: .platformUIKit),
templateColor: CryptoCurrency.bitcoin.brandUIColor,
backgroundColor: .white,
cornerRadius: .round,
accessibilityIdSuffix: ""
)
model.marginOffsetRelay.accept(1)
return model
}(),
size: 16
)
}
@ViewBuilder private func view(
row: AccountPickerRow,
fiatBalance: String? = nil,
cryptoBalance: String? = nil,
currencyCode: String? = nil
) -> some View {
AccountPickerRowView(
model: row,
send: { _ in },
badgeView: badgeView(for:),
iconView: iconView(for:),
multiBadgeView: multiBadgeView(for:),
withdrawalLocksView: { EmptyView() },
fiatBalance: fiatBalance,
cryptoBalance: cryptoBalance,
currencyCode: currencyCode
)
.app(App.preview)
.fixedSize()
}
override func setUp() {
super.setUp()
isRecording = false
}
func testAccountGroup() {
let accountGroupRow = AccountPickerRow.accountGroup(
accountGroup
)
let view = view(
row: accountGroupRow,
fiatBalance: "$2,302.39",
cryptoBalance: "0.21204887 BTC",
currencyCode: "USD"
)
assertSnapshot(matching: view, as: .image)
}
func testAccountGroupLoading() {
let accountGroupRow = AccountPickerRow.accountGroup(
accountGroup
)
assertSnapshot(matching: view(row: accountGroupRow), as: .image)
}
func testSingleAccount() {
let singleAccountRow = AccountPickerRow.singleAccount(
singleAccount
)
let view = view(
row: singleAccountRow,
fiatBalance: "$2,302.39",
cryptoBalance: "0.21204887 BTC",
currencyCode: nil
)
assertSnapshot(matching: view, as: .image)
isShowingMultiBadge = true
assertSnapshot(matching: view, as: .image)
}
func testSingleAccountLoading() {
let singleAccountRow = AccountPickerRow.singleAccount(
singleAccount
)
assertSnapshot(matching: view(row: singleAccountRow), as: .image)
}
func testButton() {
let buttonRow = AccountPickerRow.button(
.init(
id: UUID(),
text: "+ Add New"
)
)
assertSnapshot(matching: view(row: buttonRow), as: .image)
}
func testLinkedAccount() {
let linkedAccountRow = AccountPickerRow.linkedBankAccount(
linkedBankAccountModel
)
assertSnapshot(matching: view(row: linkedAccountRow), as: .image)
isShowingMultiBadge = true
assertSnapshot(matching: view(row: linkedAccountRow), as: .image)
}
func testPaymentMethod_funds() {
let linkedAccountRow = AccountPickerRow.paymentMethodAccount(
paymentMethodRowModel(for: paymentMethodFunds)
)
assertSnapshot(matching: view(row: linkedAccountRow), as: .image)
}
func testPaymentMethod_card() {
let linkedAccountRow = AccountPickerRow.paymentMethodAccount(
paymentMethodRowModel(for: paymentMethodCard)
)
assertSnapshot(matching: view(row: linkedAccountRow), as: .image)
}
}
struct MockWithdrawalServiceAPI: WithdrawalServiceAPI {
func withdrawFeeAndLimit(
for currency: FiatCurrency,
paymentMethodType: PaymentMethodPayloadType
) -> Single<WithdrawalFeeAndLimit> {
.just(.init(
maxLimit: .zero(currency: currency),
minLimit: .zero(currency: currency),
fee: .zero(currency: currency)
))
}
func withdrawal(
for checkout: WithdrawalCheckoutData
) -> Single<Result<FiatValue, Error>> {
fatalError("Not implemented")
}
func withdrawalFee(
for currency: FiatCurrency,
paymentMethodType: PaymentMethodPayloadType
) -> Single<FiatValue> {
fatalError("Not implemented")
}
func withdrawalMinAmount(
for currency: FiatCurrency,
paymentMethodType: PaymentMethodPayloadType
) -> Single<FiatValue> {
fatalError("Not implemented")
}
}
| lgpl-3.0 | afa2b82607c79d94ce911be5c629b572 | 30.555256 | 109 | 0.537371 | 5.641928 | false | false | false | false |
denizsokmen/Raid | Raid/ViewController.swift | 1 | 1708 | //
// ViewController.swift
// Raid
//
// Created by student7 on 17/12/14.
// Copyright (c) 2014 student7. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var net: NetworkManager!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
net = NetworkManager()
net.connect()
net.send("asdsadd")
let userDefaults = NSUserDefaults.standardUserDefaults()
if let defaultItems = userDefaults.dataForKey("database") {
Database.sharedInstance.load()
}
else {
Database.sharedInstance.save()
}
}
@IBAction func loginClicked(sender: AnyObject) {
mainSegue()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "register" {
let vc = segue.destinationViewController as RegisterViewController
vc.net = self.net
}
}
func mainSegue() {
if Database.sharedInstance.auth(username.text, pass: password.text) {
let main = self.storyboard?.instantiateViewControllerWithIdentifier("Main") as UINavigationController
self.presentViewController(main, animated: true, completion: nil)
}
}
}
| gpl-2.0 | 4f7ded78da520a9e5f815e457cb7871b | 25.276923 | 113 | 0.603044 | 5.354232 | false | false | false | false |
tjw/swift | stdlib/public/core/ObjectIdentifier.swift | 1 | 3808 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A unique identifier for a class instance or metatype.
///
/// In Swift, only class instances and metatypes have unique identities. There
/// is no notion of identity for structs, enums, functions, or tuples.
@_fixed_layout // FIXME(sil-serialize-all)
public struct ObjectIdentifier {
@usableFromInline // FIXME(sil-serialize-all)
internal let _value: Builtin.RawPointer
/// Creates an instance that uniquely identifies the given class instance.
///
/// The following example creates an example class `A` and compares instances
/// of the class using their object identifiers and the identical-to
/// operator (`===`):
///
/// class IntegerRef {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
/// }
///
/// let x = IntegerRef(10)
/// let y = x
///
/// print(ObjectIdentifier(x) == ObjectIdentifier(y))
/// // Prints "true"
/// print(x === y)
/// // Prints "true"
///
/// let z = IntegerRef(10)
/// print(ObjectIdentifier(x) == ObjectIdentifier(z))
/// // Prints "false"
/// print(x === z)
/// // Prints "false"
///
/// - Parameter x: An instance of a class.
@inlinable // FIXME(sil-serialize-all)
public init(_ x: AnyObject) {
self._value = Builtin.bridgeToRawPointer(x)
}
/// Creates an instance that uniquely identifies the given metatype.
///
/// - Parameter: A metatype.
@inlinable // FIXME(sil-serialize-all)
public init(_ x: Any.Type) {
self._value = unsafeBitCast(x, to: Builtin.RawPointer.self)
}
}
extension ObjectIdentifier : CustomDebugStringConvertible {
/// A textual representation of the identifier, suitable for debugging.
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
return "ObjectIdentifier(\(_rawPointerToString(_value)))"
}
}
extension ObjectIdentifier: Equatable {
@inlinable // FIXME(sil-serialize-all)
public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value))
}
}
extension ObjectIdentifier: Comparable {
@inlinable // FIXME(sil-serialize-all)
public static func < (lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool {
return UInt(bitPattern: lhs) < UInt(bitPattern: rhs)
}
}
extension ObjectIdentifier: Hashable {
// FIXME: Better hashing algorithm
/// The identifier's hash value.
///
/// The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
@inlinable // FIXME(sil-serialize-all)
public var hashValue: Int {
return Int(Builtin.ptrtoint_Word(_value))
}
}
extension UInt {
/// Creates an integer that captures the full value of the given object
/// identifier.
@inlinable // FIXME(sil-serialize-all)
public init(bitPattern objectID: ObjectIdentifier) {
self.init(Builtin.ptrtoint_Word(objectID._value))
}
}
extension Int {
/// Creates an integer that captures the full value of the given object
/// identifier.
@inlinable // FIXME(sil-serialize-all)
public init(bitPattern objectID: ObjectIdentifier) {
self.init(bitPattern: UInt(bitPattern: objectID))
}
}
| apache-2.0 | a3dff6bffcf24886fe30d225786d09b1 | 32.113043 | 80 | 0.641544 | 4.307692 | false | false | false | false |
mmllr/CleanTweeter | CleanTweeter/CleanTweeterDependencies.swift | 1 | 1155 |
import Foundation
import UIKit
class CleanTweeterDependencies : TweetListRoutingDelegate, NewPostRoutingDelegate {
let userRepository: DemoUserRepository
let tweetListWireframe: TweetListWireframe
let newPostWireframe: NewPostWireframe
var mainNavigationController: UINavigationController!
var rootViewController: UIViewController {
let controller: TweetListTableViewController = self.tweetListWireframe.viewController
controller.routingDelegate = self
self.mainNavigationController = UINavigationController(rootViewController: controller)
return mainNavigationController
}
init() {
userRepository = DemoUserRepository()
tweetListWireframe = TweetListWireframe(userRepository: userRepository)
newPostWireframe = NewPostWireframe(userRepository: userRepository)
}
func createNewPost() {
let vc = newPostWireframe.viewController
vc.routingDelegate = self
let nav = UINavigationController(rootViewController: vc)
self.mainNavigationController.present(nav, animated: true, completion: nil)
}
func hideNewPostView() {
self.mainNavigationController.presentedViewController?.dismiss(animated: true, completion: nil)
}
}
| mit | 76af4d64b9a144683fe0a224c668cea1 | 32.970588 | 97 | 0.828571 | 5.065789 | false | false | false | false |
jriehn/moody-ios-client | Moody/Pods/Socket.IO-Client-Swift/SocketIOClientSwift/SocketEngine.swift | 2 | 24887 | //
// SocketEngine.swift
// Socket.IO-Swift
//
// Created by Erik Little on 3/3/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
private typealias ProbeWaitQueue = [Probe]
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var closed = false
private var _connected = false
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingInterval:Int?
private var pingTimer:NSTimer?
private var pingTimeout = 0 {
didSet {
pongsMissedMax = pingTimeout / (pingInterval ?? 25)
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var postWait = [String]()
private var _polling = true
private var probing = false
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
let logType = "SocketEngine"
var connected:Bool {
return _connected
}
weak var client:SocketEngineClient?
var cookies:[NSHTTPCookie]?
var log = false
var polling:Bool {
return _polling
}
var sid = ""
var socketPath = ""
var urlPolling:String?
var urlWebSocket:String?
var websocket:Bool {
return _websocket
}
var ws:WebSocket?
public enum PacketType:Int {
case OPEN = 0
case CLOSE = 1
case PING = 2
case PONG = 3
case MESSAGE = 4
case UPGRADE = 5
case NOOP = 6
init?(str:String?) {
if let value = str?.toInt(), raw = PacketType(rawValue: value) {
self = raw
} else {
return nil
}
}
}
public init(client:SocketEngineClient, sessionDelegate:NSURLSessionDelegate?) {
self.client = client
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: sessionDelegate, delegateQueue: workQueue)
}
public convenience init(client:SocketEngineClient, opts:NSDictionary?) {
self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate)
forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false
forcePolling = opts?["forcePolling"] as? Bool ?? false
cookies = opts?["cookies"] as? [NSHTTPCookie]
log = opts?["log"] as? Bool ?? false
socketPath = opts?["path"] as? String ?? ""
}
deinit {
SocketLogger.log("Engine is being deinit", client: self)
}
public func close(#fast:Bool) {
SocketLogger.log("Engine is being closed. Fast: %@", client: self, args: fast)
pingTimer?.invalidate()
closed = true
ws?.disconnect()
if fast || polling {
write("", withType: PacketType.CLOSE, withData: nil)
client?.engineDidClose("Disconnect")
}
stopPolling()
}
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
var mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return (mutData, nil)
} else {
var str = "b4"
str += data.base64EncodedStringWithOptions(
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
return (nil, str)
}
}
private func createURLs(params:[String: AnyObject]?) -> (String?, String?) {
if client == nil {
return (nil, nil)
}
let path = socketPath == "" ? "/socket.io" : socketPath
var url = "\(client!.socketURL)\(path)/?transport="
var urlPolling:String
var urlWebSocket:String
if client!.secure {
urlPolling = "https://" + url + "polling"
urlWebSocket = "wss://" + url + "websocket"
} else {
urlPolling = "http://" + url + "polling"
urlWebSocket = "ws://" + url + "websocket"
}
if params != nil {
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
}
}
return (urlPolling, urlWebSocket)
}
private func createWebsocket(andConnect connect:Bool) {
ws = WebSocket(url: NSURL(string: urlWebSocket! + "&sid=\(sid)")!,
cookies: cookies)
ws?.queue = handleQueue
ws?.delegate = self
if connect {
ws?.connect()
}
}
private func doFastUpgrade() {
if waitingForPoll {
SocketLogger.err("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", client: self)
}
sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
_websocket = true
_polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func doPoll() {
if websocket || waitingForPoll || !connected {
return
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
doRequest(req)
}
private func doRequest(req:NSMutableURLRequest) {
if !polling {
return
}
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
SocketLogger.log("Doing polling request", client: self)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil {
if this.polling {
this.handlePollingFailed(err.localizedDescription)
} else {
SocketLogger.err(err.localizedDescription, client: this)
}
return
}
SocketLogger.log("Got polling response", client: this)
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
dispatch_async(this.parseQueue) {[weak this] in
this?.parsePollingMessage(str)
}
}
this.waitingForPoll = false
if this.fastUpgrade {
this.doFastUpgrade()
} else if !this.closed && this.polling {
this.doPoll()
}
}}.resume()
}
private func flushProbeWait() {
SocketLogger.log("Flushing probe wait", client: self)
dispatch_async(emitQueue) {[weak self] in
if let this = self {
for waiter in this.probeWait {
this.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
this.probeWait.removeAll(keepCapacity: false)
if this.postWait.count != 0 {
this.flushWaitingForPostToWebSocket()
}
}
}
}
private func flushWaitingForPost() {
if postWait.count == 0 || !connected {
return
} else if websocket {
flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in postWait {
let len = count(packet)
postStr += "\(len):\(packet)"
}
postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
waitingForPost = true
SocketLogger.log("POSTing: %@", client: self, args: postStr)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil && this.polling {
this.handlePollingFailed(err.localizedDescription)
return
} else if err != nil {
NSLog(err.localizedDescription)
return
}
this.waitingForPost = false
dispatch_async(this.emitQueue) {[weak this] in
if !(this?.fastUpgrade ?? true) {
this?.flushWaitingForPost()
this?.doPoll()
}
}
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
for msg in postWait {
ws?.writeString(msg)
}
postWait.removeAll(keepCapacity: true)
}
private func handleClose() {
if polling {
client?.engineDidClose("Disconnect")
}
}
private func checkIfMessageIsBase64Binary(var message:String) {
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters), client = client {
dispatch_async(client.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
}
}
private func handleMessage(message:String) {
if let client = client {
dispatch_async(client.handleQueue) {[weak client] in
client?.parseSocketMessage(message)
}
}
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData:String) {
var err:NSError?
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments,
error: &err) as? NSDictionary, sid = json["sid"] as? String {
self.sid = sid
_connected = true
if !forcePolling && !forceWebsockets {
createWebsocket(andConnect: true)
}
if let pingInterval = json["pingInterval"] as? Int, pingTimeout = json["pingTimeout"] as? Int {
self.pingInterval = pingInterval / 1000
self.pingTimeout = pingTimeout / 1000
}
} else {
client?.didError("Engine failed to handshake")
return
}
startPingTimer()
if !forceWebsockets {
doPoll()
}
}
private func handlePong(pongMessage:String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
upgradeTransport()
}
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason:String) {
_connected = false
ws?.disconnect()
pingTimer?.invalidate()
waitingForPoll = false
waitingForPost = false
// If cancelled we were already closing
if client == nil || reason == "cancelled" {
return
}
if !closed {
client?.didError(reason)
client?.engineDidClose(reason)
}
}
public func open(opts:[String: AnyObject]? = nil) {
if connected {
SocketLogger.err("Tried to open while connected", client: self)
client?.didError("Tried to open while connected")
return
}
SocketLogger.log("Starting engine", client: self)
SocketLogger.log("Handshaking", client: self)
closed = false
(urlPolling, urlWebSocket) = createURLs(opts)
if forceWebsockets {
_polling = false
_websocket = true
createWebsocket(andConnect: true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
doRequest(reqPolling)
}
// Translatation of engine.io-parser#decodePayload
private func parsePollingMessage(str:String) {
if count(str) == 1 {
return
}
// println(str)
let strArray = Array(str)
var length = ""
var n = 0
var msg = ""
func testLength(length:String, inout n:Int) -> Bool {
if let num = length.toInt() {
n = num
return false
} else {
return true
}
}
for var i = 0, l = count(str); i < l; i++ {
let chr = String(strArray[i])
if chr != ":" {
length += chr
} else {
if length == "" || testLength(length, &n) {
SocketLogger.err("Parsing error: %@", client: self, args: str)
handlePollingFailed("Error parsing XHR message")
return
}
msg = String(strArray[i+1...i+n])
if let lengthInt = length.toInt() where lengthInt != count(msg) {
SocketLogger.err("Parsing error: %@", client: self, args: str)
return
}
if count(msg) != 0 {
// Be sure to capture the value of the msg
dispatch_async(handleQueue) {[weak self, msg] in
self?.parseEngineMessage(msg, fromPolling: true)
}
}
i += n
length = ""
}
}
}
private func parseEngineData(data:NSData) {
if let client = client {
dispatch_async(client.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
}
}
private func parseEngineMessage(var message:String, fromPolling:Bool) {
SocketLogger.log("Got message: %@", client: self, args: message)
if fromPolling {
fixDoubleUTF8(&message)
}
let type = PacketType(str: (message["^(\\d)"].groups()?[1])) ?? {
self.checkIfMessageIsBase64Binary(message)
return PacketType.NOOP
}()
switch type {
case PacketType.MESSAGE:
message.removeAtIndex(message.startIndex)
handleMessage(message)
case PacketType.NOOP:
handleNOOP()
case PacketType.PONG:
handlePong(message)
case PacketType.OPEN:
message.removeAtIndex(message.startIndex)
handleOpen(message)
case PacketType.CLOSE:
handleClose()
default:
SocketLogger.log("Got unknown packet type", client: self)
}
}
private func probeWebSocket() {
if websocketConnected {
sendWebSocketMessage("probe", withType: PacketType.PING)
}
}
/// Send an engine message (4)
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
if probing {
probeWait.append((msg, PacketType.MESSAGE, datas))
} else {
write(msg, withType: PacketType.MESSAGE, withData: datas)
}
}
@objc private func sendPing() {
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
++pongsMissed
write("", withType: PacketType.PING, withData: nil)
}
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending poll: %@ as type: %@", client: self, args: msg, type.rawValue)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = createBinaryDataForSend(data)
postWait.append(b64Data!)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending ws: %@ as type: %@", client: self, args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = createBinaryDataForSend(data)
if data != nil {
ws?.writeData(data!)
}
}
}
}
// Starts the ping timer
private func startPingTimer() {
if pingInterval == nil {
return
}
pingTimer?.invalidate()
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if let this = self {
this.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(this.pingInterval!),
target: this,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
}
func stopPolling() {
session.invalidateAndCancel()
}
private func upgradeTransport() {
if websocketConnected {
SocketLogger.log("Upgrading transport to WebSockets", client: self)
fastUpgrade = true
sendPollMessage("", withType: PacketType.NOOP)
// After this point, we should not send anymore polling messages
}
}
/**
Write a message, independent of transport.
*/
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
dispatch_async(emitQueue) {[weak self] in
if let this = self where this.connected {
if this.websocket {
SocketLogger.log("Writing ws: %@ has data: %@", client: this,
args: msg, data == nil ? false : true)
this.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
SocketLogger.log("Writing poll: %@ has data: %@", client: this,
args: msg, data == nil ? false : true)
this.sendPollMessage(msg, withType: type, datas: data)
}
}
}
}
/**
Write a message, independent of transport. For Objective-C. withData should be an NSArray of NSData
*/
public func writeObjc(msg:String, withType type:Int, withData data:NSArray?) {
if let pType = PacketType(rawValue: type) {
var arr = ContiguousArray<NSData>()
if data != nil {
for d in data! {
arr.append(d as! NSData)
}
}
write(msg, withType: pType, withData: arr)
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
websocketConnected = true
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
_connected = true
probing = false
_polling = false
}
}
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
websocketConnected = false
probing = false
if closed {
client?.engineDidClose("Disconnect")
return
}
if websocket {
pingTimer?.invalidate()
_connected = false
_websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
client?.didError(reason)
}
client?.engineDidClose(reason)
} else {
flushProbeWait()
}
}
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
parseEngineData(data)
}
}
| mit | a000f9fe992654842336ade46a0ed1a6 | 31.832454 | 112 | 0.530196 | 5.440971 | false | false | false | false |
dnevera/IMProcessing | IMProcessing/Classes/Adjustments/IMPCurvesFilter.swift | 1 | 4483 | //
// IMPCurveFilter.swift
// IMProcessing
//
// Created by denis svinarchuk on 12.01.16.
// Copyright © 2016 Dehancer.photo. All rights reserved.
//
import Foundation
import Metal
public class IMPCurvesFilter:IMPFilter,IMPAdjustmentProtocol{
public class Splines: IMPTextureProvider,IMPContextProvider {
public var context:IMPContext!
public static let scale:Float = 1
public static let minValue = 0
public static let maxValue = 255
public static let defaultControls = [float2(minValue.float,minValue.float),float2(maxValue.float,maxValue.float)]
public static let defaultRange = Float.range(0..<maxValue)
public static let defaultCurve = defaultRange.cubicSpline(defaultControls, scale: scale) as [Float]
var _redCurve:[Float] = Splines.defaultCurve
var _greenCurve:[Float] = Splines.defaultCurve
var _blueCurve:[Float] = Splines.defaultCurve
public var channelCurves:[[Float]]{
get{
return [_redCurve,_greenCurve,_blueCurve]
}
}
public var redCurve:[Float]{
get{
return _redCurve
}
}
public var greenCurve:[Float]{
get{
return _greenCurve
}
}
public var blueCurve:[Float]{
get{
return _greenCurve
}
}
var doNotUpdate = false
public var redControls = Splines.defaultControls {
didSet{
_redCurve = Splines.defaultRange.cubicSpline(redControls, scale: Splines.scale) as [Float]
if !doNotUpdate {
updateTexture()
}
}
}
public var greenControls = Splines.defaultControls{
didSet{
_greenCurve = Splines.defaultRange.cubicSpline(greenControls, scale: Splines.scale) as [Float]
if !doNotUpdate {
updateTexture()
}
}
}
public var blueControls = Splines.defaultControls{
didSet{
_blueCurve = Splines.defaultRange.cubicSpline(blueControls, scale: Splines.scale) as [Float]
if !doNotUpdate {
updateTexture()
}
}
}
public var compositeControls = Splines.defaultControls{
didSet{
doNotUpdate = true
redControls = compositeControls
greenControls = compositeControls
blueControls = compositeControls
doNotUpdate = false
updateTexture()
}
}
public var texture:MTLTexture?
public var filter:IMPFilter?
public required init(context:IMPContext){
self.context = context
updateTexture()
}
func updateTexture(){
if texture == nil {
texture = context.device.texture1DArray(channelCurves)
}
else {
texture?.update(channelCurves)
}
if filter != nil {
filter?.dirty = true
}
}
}
public static let defaultAdjustment = IMPAdjustment(
blending: IMPBlending(mode: IMPBlendingMode.LUMNINOSITY, opacity: 1))
public var adjustment:IMPAdjustment!{
didSet{
self.updateBuffer(&adjustmentBuffer, context:context, adjustment:&adjustment, size:sizeofValue(adjustment))
self.dirty = true
}
}
public var adjustmentBuffer:MTLBuffer?
public var kernel:IMPFunction!
public var splines:Splines!
public required init(context: IMPContext) {
super.init(context: context)
kernel = IMPFunction(context: self.context, name: "kernel_adjustCurve")
addFunction(kernel)
splines = Splines(context: context)
splines.filter = self
defer{
adjustment = IMPCurvesFilter.defaultAdjustment
}
}
public override func configure(function: IMPFunction, command: MTLComputeCommandEncoder) {
if kernel == function {
command.setTexture(splines.texture, atIndex: 2)
command.setBuffer(adjustmentBuffer, offset: 0, atIndex: 0)
}
}
} | mit | 144ab31aebe875e8c02bc4014d34b89f | 30.570423 | 121 | 0.556225 | 5.211628 | false | false | false | false |
shahmishal/swift | test/IDE/print_swift_module.swift | 3 | 1590 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/print_swift_module.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_swift_module.swiftdoc %s
// RUN: %target-swift-ide-test -print-module -print-interface -no-empty-line-between-members -module-to-print=print_swift_module -I %t -source-filename=%s > %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt
public protocol P1 {
/// foo1 comment from P1
func foo1()
/// foo2 comment from P1
func foo2()
}
public class C1 : P1 {
public func foo1() {
}
/// foo2 comment from C1
public func foo2() {
}
}
/// Alias comment
public typealias Alias<T> = (T, T)
/// returnsAlias() comment
public func returnsAlias() -> Alias<Int> {
return (0, 0)
}
@_functionBuilder
struct BridgeBuilder {}
public struct City {
public init(@BridgeBuilder builder: () -> ()) {}
}
// CHECK1: /// Alias comment
// CHECK1-NEXT: typealias Alias<T> = (T, T)
// CHECK1: public class C1 : print_swift_module.P1 {
// CHECK1-NEXT: /// foo1 comment from P1
// CHECK1-NEXT: public func foo1()
// CHECK1-NEXT: /// foo2 comment from C1
// CHECK1-NEXT: public func foo2()
// CHECK1-NEXT: }
// CHECK1: public init(@print_swift_module.BridgeBuilder builder: () -> ())
// CHECK1: public protocol P1 {
// CHECK1-NEXT: /// foo1 comment from P1
// CHECK1-NEXT: func foo1()
// CHECK1-NEXT: /// foo2 comment from P1
// CHECK1-NEXT: func foo2()
// CHECK1-NEXT: }
// CHECK1: /// returnsAlias() comment
// CHECK1-NEXT: func returnsAlias() -> print_swift_module.Alias<Int>
| apache-2.0 | 8dfa19f89aa6e3afc0959ce0252eb74f | 27.909091 | 167 | 0.654088 | 2.977528 | false | false | false | false |
naturaln0va/Doodler_iOS | Doodler/AutoHideView.swift | 1 | 639 |
import UIKit
class AutoHideView: UIView {
let animationDuration = 0.25
var timer: Timer?
func show() {
UIView.animate(withDuration: animationDuration) {
self.alpha = 1
}
if let t = timer {
if t.isValid {
timer?.invalidate()
}
}
timer = Timer.scheduledTimer(timeInterval: animationDuration * 2, target: self, selector: #selector(hide), userInfo: nil, repeats: false)
}
@objc func hide() {
UIView.animate(withDuration: animationDuration) {
self.alpha = 0
}
}
}
| mit | a09ee7fa67bc6f5cfd933724a4b9ea0b | 21.034483 | 145 | 0.527387 | 4.733333 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Dynamic Programming/303_Range Sum Query - Immutable.swift | 1 | 1298 | // 303_Range Sum Query - Immutable
// https://leetcode.com/problems/range-sum-query-immutable/
//
// Created by Honghao Zhang on 9/21/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
//
//Example:
//
//Given nums = [-2, 0, 3, -5, 2, -1]
//
//sumRange(0, 2) -> 1
//sumRange(2, 5) -> -1
//sumRange(0, 5) -> -3
//Note:
//
//You may assume that the array does not change.
//There are many calls to sumRange function.
//
import Foundation
class Num303 {
// Caching the sum until the index
class NumArray {
let nums: [Int]
// returns the sum stops at index, inclusive
// [1, 2, 3]
// sumForIndex[0] == 1
// sumForIndex[1] == 3
// sumForIndex[2] == 6
var sumForIndex: [Int: Int] = [:]
init(_ nums: [Int]) {
self.nums = nums
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
sumForIndex[i] = sum
}
}
func sumRange(_ i: Int, _ j: Int) -> Int {
return sumForIndex[j]! - ((i - 1 < 0) ? 0 : sumForIndex[i - 1]!)
}
}
/**
* Your NumArray object will be instantiated and called as such:
* let obj = NumArray(nums)
* let ret_1: Int = obj.sumRange(i, j)
*/
}
| mit | 3ff635bcd145ab372327833b9aab56d3 | 22.125 | 104 | 0.576062 | 3.197531 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | SwiftGL-Demo/Source/iOS/FaceGameScene.swift | 1 | 6145 | //
// FaceGameScene.swift
// SwiftGL
//
// Created by CSC NTHU on 2015/8/15.
// Copyright © 2015年 Jerry Chan. All rights reserved.
//
import UIKit
import SpriteKit
import SwiftGL
/*func uIntColor(red:UInt8,green:UInt8,blue:UInt8,alpha:UInt8)->UIColor
{
return UIColor(red: CGFloat(red)/255, green: CGFloat(green)/255, blue: CGFloat(blue)/255, alpha: CGFloat(alpha)/255)
}*/
class FaceGameScene: SKScene {
//let player = SKSpriteNode(imageNamed: "doraemon")
var faceGameStageLevelGenerator:FaceGameStageLevelGenerator!
var ansRect:SKNode!
var quesRect:SKNode!
var quesPositions:[CGPoint]!
var ansComponents:FaceComponentSet!
var pointNum:Int = 10
var difficulty = 1
var hintImg:SKSpriteNode!//(imageNamed: "imghint")
var levelName: FaceGameViewController.FaceGameLevelName!
override func didMove(to view: SKView) {
scaleMode = SKSceneScaleMode.aspectFill
backgroundColor = SKColor.white
view.showsDrawCount = true
view.showsFPS = true
//player.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5)
//addChild(player)
faceGameStageLevelGenerator = FaceGameStageLevelGenerator(size: size,num: pointNum)
prepareScene()
newStage()
self.addChild(scoreLabel)
}
func prepareScene()
{
//Question Area
let quesRect = SKShapeNode(rect: CGRect(x: 0, y: 0, width: size.width/2, height: size.height))
quesRect.position = CGPoint(x: 0,y: 0)
addChild(quesRect)
//Answer Area
let ansRect = SKShapeNode(rect: CGRect(x: 0, y: 0, width: size.width/2, height: size.height))
ansRect.fillColor = SKColor.white
ansRect.position = CGPoint(x: size.width/2,y: 0)
addChild(ansRect)
self.quesRect = quesRect
self.ansRect = ansRect
}
var scoreLabel:SKLabelNode = SKLabelNode(text:"");
func calScore()->Float
{
var score = 1 - ansComponents.compareSet(quesPositions) / Float(400 * quesPositions.count)
if score < 0
{
score = 0
}
score *= 100
let scorePercentString = NSString(format: "%.1f", score) as String
scoreLabel.text = scorePercentString+"%"
scoreLabel.isHidden = false
scoreLabel.fontSize = 100
scoreLabel.position = CGPoint(x: size.width/2, y: size.height/2)
scoreLabel.fontColor = UIColor(red: 80/255, green: 151/255, blue: 1, alpha: 1)
//scoreLabel.fontColor = uIntColor(80, green: 151, blue: 255, alpha: 255)
calposition()
return Float(score)
}
func calposition()
{
//ansComponents.sortComponents()
for component in ansComponents.components {
print("CGPoint(x:\(component.position.x),y:\(component.position.y)),", terminator: "")
}
}
func showImg()
{
ansRect.addChild(hintImg)
}
func hideImg(){
hintImg.removeFromParent()
}
func changeDifficulty(_ d:Int)
{
difficulty = d
}
func newStage()
{
if ansComponents != nil
{
ansComponents.removeFromParent()
}
//let levelName = "AngryBird"
//let levelName = "Tumbler"
//let levelName = "GreenMan"
faceGameStageLevelGenerator.genGameLevel(levelName)
// quesComponents = faceGameStageLevelGenerator.correctPosition()
quesPositions = faceGameStageLevelGenerator.correctPosition()
//quesComponents.addToNode(quesRect)
ansComponents = faceGameStageLevelGenerator.freeComponents()
ansComponents.setMovable(true)
ansComponents.addToNode(ansRect)
let quesImg = faceGameStageLevelGenerator.getMain()
quesImg.setScale(0.2)
quesImg.color = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
quesImg.colorBlendFactor = 1;
quesRect.addChild(quesImg)
hintImg = faceGameStageLevelGenerator.getMain()
hintImg.setScale(0.2)
hintImg.color = UIColor(red: 0, green: 0, blue: 0, alpha: 50/255)
//hintImg.color = uIntColor(0, green: 0, blue: 0, alpha: 50)
hintImg.colorBlendFactor = 1;
setFixPoint()
scoreLabel.isHidden = true
}
func restart()
{
if ansComponents != nil
{
ansComponents.removeFromParent()
}
ansComponents = faceGameStageLevelGenerator.freeComponents()
ansComponents.setMovable(true)
ansComponents.addToNode(ansRect)
setFixPoint()
scoreLabel.isHidden = true
}
func setFixPoint()
{
let index = faceGameStageLevelGenerator.gameLevelGened.fixPointIndex
ansComponents.components[index].position = quesPositions[index]
ansComponents.components[index].isUserInteractionEnabled = false
}
/*
var selectedNode:SKNode!
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
let touch = touches.first as! UITouch
let loc = touch.locationInNode(self)
selectedNode = selectNodeForTouch(loc)
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent)
{
let touch = touches.first as! UITouch
let loc = touch.locationInNode(self)
let prev_loc = touch.previousLocationInNode(self)
//let node = selectNodeForTouch(prev_loc)
let node = selectedNode
if node != nil
{
let p = node.position
node.position = CGPointMake(p.x+loc.x-prev_loc.x, p.y+loc.y-prev_loc.y)
}
}
func selectNodeForTouch(location:CGPoint)->SKNode!
{
let node = nodeAtPoint(location)// as? SKSpriteNode
println(node)
if node.name == "dot"
{
return node
}
else
{
return nil
}
//return nil
}
*/
}
| mit | 3e7029349e21b467090e10827b5c018c | 26.297778 | 120 | 0.601758 | 4.489766 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Controller/Scanner/CScannerOCR.swift | 1 | 11836 | import UIKit
import TesseractOCR
import MetalKit
class CScannerOCR:CController, G8TesseractDelegate
{
private enum CalculatorModifier
{
case add
case subtract
case multiply
case divide
}
let modelMenu:MScannerMenu
private weak var viewOCR:VScannerOCR!
private var recognized:Bool
private let image:UIImage
private let kLanguage:String = "eng"
private let kNumbersMin:UInt32 = 48
private let kNumbersMax:UInt32 = 57
private let kAlphaCapsMin:UInt32 = 65
private let kAlphaCapsMax:UInt32 = 90
private let kAlphaMin:UInt32 = 97
private let kAlphaMax:UInt32 = 122
private let kSignPoint:UInt32 = 46
private let kSignAdd:UInt32 = 43
private let kSignSubtract:UInt32 = 45
private let kSignDivide:UInt32 = 47
private let kSignMultiply:UInt32 = 42
private let kSignEquals:UInt32 = 61
private let kNewLine:UInt32 = 10
init(image:UIImage)
{
self.image = image
recognized = false
modelMenu = MScannerMenu()
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewOCR:VScannerOCR = VScannerOCR(controller:self)
self.viewOCR = viewOCR
view = viewOCR
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
if !recognized
{
recognized = true
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.preProcess()
}
}
}
//MARK: private
private func shareImage(image:UIImage)
{
DispatchQueue.main.async
{
let activity:UIActivityViewController = UIActivityViewController(
activityItems:[image],
applicationActivities:nil)
if let popover:UIPopoverPresentationController = activity.popoverPresentationController
{
popover.sourceView = self.viewOCR
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
self.present(activity, animated:true)
}
}
private func preProcess()
{
var image:UIImage = self.image
if let device:MTLDevice = MTLCreateSystemDefaultDevice()
{
let filter:MScannerFilter = MScannerFilter()
if let filteredImage:UIImage = filter.filter(
device:device,
image:image)
{
image = filteredImage
}
}
else
{
image = self.image.g8_blackAndWhite()
}
shareImage(image:image)
imageRecognition(image:image)
}
private func imageRecognition(image:UIImage)
{
let tesseract:G8Tesseract = G8Tesseract(
language:kLanguage,
engineMode:G8OCREngineMode.cubeOnly)
tesseract.pageSegmentationMode = G8PageSegmentationMode.singleBlock
tesseract.image = image
tesseract.recognize()
guard
let text:String = tesseract.recognizedText
else
{
return
}
textReady(text:text)
}
private func textReady(text:String)
{
DispatchQueue.main.async
{ [weak self] in
self?.viewOCR.textRecognized(text:text)
}
}
private func asyncClean(text:String)
{
var cleanText:String = ""
var prevSign:String?
var newLine:String?
for character:Character in text.characters
{
let characterString:String = "\(character)"
guard
let unicodeScalar:UnicodeScalar = UnicodeScalar(characterString)
else
{
continue
}
let unicodeInt:UInt32 = unicodeScalar.value
if (unicodeInt >= kNumbersMin && unicodeInt <= kNumbersMax) ||
(unicodeInt >= kAlphaMin && unicodeInt <= kAlphaMax) ||
(unicodeInt >= kAlphaCapsMin && unicodeInt <= kAlphaCapsMax)
{
if let newLine:String = newLine
{
cleanText.append(newLine)
}
if let prevSign:String = prevSign
{
cleanText.append(prevSign)
}
cleanText.append(characterString)
prevSign = nil
newLine = nil
}
else if unicodeInt == kNewLine
{
newLine = characterString
}
else
{
switch unicodeInt
{
case kSignAdd,
kSignSubtract,
kSignMultiply,
kSignDivide,
kSignEquals,
kSignPoint:
prevSign = characterString
break
default:
break
}
}
}
DispatchQueue.main.async
{ [weak self] in
self?.cleanFinished(newText:cleanText)
}
}
private func cleanFinished(newText:String)
{
viewOCR.viewText.text = newText
}
private func asyncCalculator(text:String)
{
var total:Double = 0
var coefficient:String?
var modifier:CalculatorModifier = CalculatorModifier.add
var equaled:Bool = false
for character:Character in text.characters
{
let characterString:String = "\(character)"
guard
let unicodeScalar:UnicodeScalar = UnicodeScalar(characterString)
else
{
continue
}
let unicodeInt:UInt32 = unicodeScalar.value
if (unicodeInt >= kNumbersMin && unicodeInt <= kNumbersMax) ||
(unicodeInt == kSignPoint)
{
if coefficient == nil
{
coefficient = ""
}
coefficient?.append(characterString)
}
else
{
switch unicodeInt
{
case kSignAdd,
kSignSubtract,
kSignMultiply,
kSignDivide,
kSignEquals:
if let coefficient:String = coefficient
{
var coefficientNumber:Double = MSession.sharedInstance.numberFrom(
string:coefficient)
if equaled
{
coefficientNumber = -coefficientNumber
}
switch modifier
{
case CalculatorModifier.add:
total += coefficientNumber
break
case CalculatorModifier.subtract:
total -= coefficientNumber
break
case CalculatorModifier.multiply:
total *= coefficientNumber
break
case CalculatorModifier.divide:
if coefficientNumber != 0
{
total /= coefficientNumber
}
break
}
}
break
default:
continue
}
coefficient = nil
switch unicodeInt
{
case kSignEquals:
equaled = true
modifier = CalculatorModifier.add
break
case kSignAdd:
modifier = CalculatorModifier.add
break
case kSignSubtract:
modifier = CalculatorModifier.subtract
break
case kSignMultiply:
modifier = CalculatorModifier.multiply
break
case kSignDivide:
modifier = CalculatorModifier.divide
break
default:
break
}
}
}
if let coefficient:String = coefficient
{
let coefficientNumber:Double = MSession.sharedInstance.numberFrom(
string:coefficient)
total += coefficientNumber
}
let calculatorString:String = MSession.sharedInstance.stringFrom(
number:total)
DispatchQueue.main.async
{ [weak self] in
self?.calculatorFinished(
newText:calculatorString)
}
}
private func calculatorFinished(newText:String)
{
let controllerCalculator:CCalculator = CCalculator(initial:newText)
parentController.push(
controller:controllerCalculator,
horizontal:CParent.TransitionHorizontal.fromRight)
}
//MARK: public
func back()
{
UIApplication.shared.keyWindow!.endEditing(true)
parentController.pop(horizontal:CParent.TransitionHorizontal.fromRight)
}
func help()
{
let modelHelp:MHelpScanner = MHelpScanner()
let controllerHelp:CHelp = CHelp(model:modelHelp)
parentController.push(
controller:controllerHelp,
vertical:CParent.TransitionVertical.fromTop,
background:false)
}
func clean()
{
let text:String = viewOCR.viewText.text
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncClean(text:text)
}
}
func calculator()
{
let text:String = viewOCR.viewText.text
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncCalculator(text:text)
}
}
//MARK: tesseract delegate
func shouldCancelImageRecognition(for tesseract:G8Tesseract!) -> Bool
{
return false
}
}
| mit | 5866d0d1bfac83145c526762a9ffdce6 | 26.849412 | 99 | 0.45125 | 6.751854 | false | false | false | false |
wei18810109052/CWWeChat | CWWeChat/ChatModule/CWChatClient/Model/CWEmoticonMessageBody.swift | 2 | 1766 | //
// CWEmoticonMessageBody.swift
// CWWeChat
//
// Created by chenwei on 2017/4/20.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import Foundation
import SwiftyJSON
class CWEmoticonMessageBody: NSObject, CWMessageBody {
weak var message: CWMessage?
/// 消息体类型
var type: CWMessageType = .emoticon
/// 本地路径
var originalLocalPath: String?
/// 服务器地址
var originalURL: URL?
var size: CGSize = CGSize.zero
init(localPath: String? = nil,
remoteURL: URL? = nil) {
self.originalLocalPath = localPath
self.originalURL = remoteURL
}
}
extension CWEmoticonMessageBody {
var info: [String: String] {
var info = ["size": NSStringFromCGSize(size)]
if let urlString = self.originalURL?.absoluteString {
info["url"] = urlString
}
if let path = self.originalLocalPath {
info["path"] = path
}
return info
}
var messageEncode: String {
do {
let data = try JSONSerialization.data(withJSONObject: self.info, options: .prettyPrinted)
return String(data: data, encoding: .utf8) ?? ""
} catch {
return ""
}
}
func messageDecode(string: String) {
let json: JSON = JSON(parseJSON: string)
if let size = json["size"].string {
self.size = CGSizeFromString(size)
}
if let path = json["path"].string {
self.originalLocalPath = path
}
if let urlstring = json["url"].string,
let url = URL(string: urlstring) {
self.originalURL = url
}
}
}
| mit | 7726d21fd6901587bdabceaddb3959bc | 22.767123 | 101 | 0.552161 | 4.577836 | false | false | false | false |
rolson/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Route & Navigation/Offline routing/OfflineRoutingViewController.swift | 1 | 12515 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class OfflineRoutingViewController: UIViewController, AGSGeoViewTouchDelegate {
@IBOutlet var mapView: AGSMapView!
@IBOutlet var segmentedControl:UISegmentedControl!
@IBOutlet var distanceLabel:UILabel!
@IBOutlet var timeLabel:UILabel!
@IBOutlet var detailsViewBottomContraint:NSLayoutConstraint!
var map:AGSMap!
var routeTask:AGSRouteTask!
var params:AGSRouteParameters!
private var stopGraphicsOverlay = AGSGraphicsOverlay()
private var routeGraphicsOverlay = AGSGraphicsOverlay()
private var longPressedGraphic:AGSGraphic!
private var longPressedRouteGraphic:AGSGraphic!
private var routeTaskOperation:AGSCancelable!
private var totalDistance:Double = 0 {
didSet {
let miles = String(format: "%.2f", totalDistance*0.000621371)
self.distanceLabel?.text = "(\(miles) mi)"
}
}
private var totalTime:Double = 0 {
didSet {
var minutes = Int(totalTime)
let hours = minutes/60
minutes = minutes%60
let hoursString = hours == 0 ? "" : "\(hours) hr "
let minutesString = minutes == 0 ? "0 min" : "\(minutes) min"
self.timeLabel?.text = "\(hoursString)\(minutesString)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["OfflineRoutingViewController"]
//using a tpk to create a local tiled layer
//which will be visible in case of no network connection
let path = NSBundle.mainBundle().pathForResource("streetmap_SD", ofType: "tpk")!
let localTiledLayer = AGSArcGISTiledLayer(tileCache: AGSTileCache(fileURL: NSURL(fileURLWithPath: path)))
//initialize the map using the local tiled layer as baselayer
self.map = AGSMap(basemap: AGSBasemap(baseLayer: localTiledLayer))
//assign the map to the map view
self.mapView.map = self.map
//register self as the touch delegate for the map view
//will be using the touch gestures to add the stops
self.mapView.touchDelegate = self
//add graphics overlay, one for the stop graphics
//and other for the route graphics
self.mapView.graphicsOverlays.addObjectsFromArray([self.routeGraphicsOverlay, self.stopGraphicsOverlay])
//get the path for the geodatabase in the bundle
let dbPath = NSBundle.mainBundle().pathForResource("sandiego", ofType: "geodatabase", inDirectory: "san-diego")!
//initialize the route task using the path and the network name
self.routeTask = AGSRouteTask(fileURLToDatabase: NSURL(fileURLWithPath: dbPath), networkName: "Streets_ND")
//get default route parameters
self.getDefaultParameters()
//zoom to San Diego
self.mapView.setViewpointCenter(AGSPoint(x: -13042254.715252, y: 3857970.236806, spatialReference: AGSSpatialReference(WKID: 3857)), scale: 2e4, completion: nil)
//enable magnifier for better experience while using tap n hold to add a stop
self.mapView.interactionOptions.magnifierEnabled = true
}
//method returns a graphic for the specified location
//also assigns the stop number
private func graphicForLocation(point:AGSPoint) -> AGSGraphic {
let symbol = self.symbolForStopGraphic(self.stopGraphicsOverlay.graphics.count + 1)
let graphic = AGSGraphic(geometry: point, symbol: symbol, attributes: nil)
return graphic
}
private func symbolForStopGraphic(index: Int) -> AGSSymbol {
let markerImage = UIImage(named: "BlueMarker")!
let markerSymbol = AGSPictureMarkerSymbol(image: markerImage)
markerSymbol.offsetY = markerImage.size.height/2
let textSymbol = AGSTextSymbol(text: "\(index)", color: UIColor.whiteColor(), size: 20, horizontalAlignment: AGSHorizontalAlignment.Center, verticalAlignment: AGSVerticalAlignment.Middle)
textSymbol.offsetY = markerSymbol.offsetY
let compositeSymbol = AGSCompositeSymbol(symbols: [markerSymbol, textSymbol])
return compositeSymbol
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - AGSGeoViewTouchDelegate
func geoView(geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
//on single tap, add stop graphic at the tapped location
//and route
let graphic = self.graphicForLocation(mapPoint)
self.stopGraphicsOverlay.graphics.addObject(graphic)
//clear the route graphic
self.longPressedRouteGraphic = nil
self.route(false)
}
func geoView(geoView: AGSGeoView, didLongPressAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
//add the graphic at that point
//keep a reference to that graphic to update the geometry if moved
self.longPressedGraphic = self.graphicForLocation(mapPoint)
self.stopGraphicsOverlay.graphics.addObject(self.longPressedGraphic)
//clear the route graphic
self.longPressedRouteGraphic = nil
//route
self.route(true)
}
func geoView(geoView: AGSGeoView, didMoveLongPressToScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
//update the graphic
//route
self.longPressedGraphic.geometry = mapPoint
self.route(true)
}
//MARK: - Route logic
private func getDefaultParameters() {
//get the default parameters
self.routeTask.defaultRouteParametersWithCompletion({ [weak self] (params: AGSRouteParameters?, error: NSError?) -> Void in
if let error = error {
print(error)
}
else {
self?.params = params
}
})
}
func route(isLongPressed:Bool) {
//if either default parameters failed to generate or
//the number of stops is less than two, return
if self.params == nil {
print("Failed to generate default parameters")
return
}
if self.stopGraphicsOverlay.graphics.count < 2 {
print("The stop count is less than 2")
return
}
//cancel previous requests
self.routeTaskOperation?.cancel()
self.routeTaskOperation = nil
//create stops using the last two graphics in the overlay
let count = self.stopGraphicsOverlay.graphics.count
let geometry1 = (self.stopGraphicsOverlay.graphics[count-2] as! AGSGraphic).geometry as! AGSPoint
let geometry2 = (self.stopGraphicsOverlay.graphics[count-1] as! AGSGraphic).geometry as! AGSPoint
let stop1 = AGSStop(point: (geometry1))
let stop2 = AGSStop(point: (geometry2))
let stops = [stop1, stop2]
//clear the previous stops
self.params.clearStops()
//add the new stops
self.params.setStops(stops)
//set the new travel mode
self.params.travelMode = self.routeTask.routeTaskInfo().travelModes[self.segmentedControl.selectedSegmentIndex]
self.route(self.params, isLongPressed: isLongPressed)
}
func route(params:AGSRouteParameters, isLongPressed:Bool) {
//solve for route
self.routeTaskOperation = self.routeTask.solveRouteWithParameters(params) { [weak self] (routeResult:AGSRouteResult?, error:NSError?) -> Void in
if let error = error where error.code != 3072 {
//3072 is `User canceled error`
print(error)
}
else {
//handle the route result
self?.displayRoutesOnMap(routeResult?.routes, isLongPressedResult: isLongPressed)
}
}
}
func displayRoutesOnMap(routes:[AGSRoute]?, isLongPressedResult:Bool) {
//if a route graphic for previous request (in case of long press)
//exists then remove it
if self.longPressedRouteGraphic != nil {
//update distance and time
self.totalTime = self.totalTime - Double(self.longPressedGraphic.attributes["routeTime"] as! NSNumber)
self.totalDistance = self.totalDistance - Double(self.longPressedGraphic.attributes["routeLength"] as! NSNumber)
self.routeGraphicsOverlay.graphics.removeObject(self.longPressedRouteGraphic)
self.longPressedRouteGraphic = nil
}
//if a route is returned, create a graphic for it
//and add to the route graphics overlay
if let route = routes?[0] {
let routeGraphic = AGSGraphic(geometry: route.routeGeometry, symbol: self.routeSymbol(), attributes: nil)
//keep reference to the graphic in case of long press
//to remove in case of cancel or move
if isLongPressedResult {
self.longPressedRouteGraphic = routeGraphic
//set attributes (to subtract in case the route is not used)
self.longPressedGraphic.attributes["routeTime"] = route.totalTime
self.longPressedGraphic.attributes["routeLength"] = route.totalLength
}
self.routeGraphicsOverlay.graphics.addObject(routeGraphic)
//update total distance and total time
self.totalTime = self.totalTime + route.totalTime
self.totalDistance = self.totalDistance + route.totalLength
self.toggleDetailsView(true)
}
}
//method returns the symbol for the route graphic
func routeSymbol() -> AGSSimpleLineSymbol {
let symbol = AGSSimpleLineSymbol(style: .Solid, color: UIColor.yellowColor(), width: 5)
return symbol
}
//MARK: - Actions
@IBAction func trashAction() {
//empty both graphic overlays
self.routeGraphicsOverlay.graphics.removeAllObjects()
self.stopGraphicsOverlay.graphics.removeAllObjects()
//reset distance and time
self.totalTime = 0
self.totalDistance = 0
//hide the details view
self.toggleDetailsView(false)
}
@IBAction func modeChanged(segmentedControl:UISegmentedControl) {
//re route for already added stops
if self.stopGraphicsOverlay.graphics.count > 1 {
var stops = [AGSStop]()
for graphic in self.stopGraphicsOverlay.graphics as AnyObject as! [AGSGraphic] {
let stop = AGSStop(point: graphic.geometry! as! AGSPoint)
stops.append(stop)
}
self.params.clearStops()
self.params.setStops(stops)
//set the new travel mode
self.params.travelMode = self.routeTask.routeTaskInfo().travelModes[self.segmentedControl.selectedSegmentIndex]
//clear all previous routes
self.routeGraphicsOverlay.graphics.removeAllObjects()
//reset distance and time
self.totalDistance = 0
self.totalTime = 0
//route
self.route(self.params, isLongPressed: false)
}
}
//MARK: toggle details view
private func toggleDetailsView(on: Bool) {
self.detailsViewBottomContraint.constant = on ? 0 : -36
UIView.animateWithDuration(0.3) { [weak self] in
self?.view.layoutIfNeeded()
}
}
}
| apache-2.0 | 97cb63210b4cf0e5b5e33705d050de51 | 39.501618 | 195 | 0.640831 | 5.18005 | false | false | false | false |
svenbacia/TraktKit | TraktKit/Sources/Response/Pagination.swift | 1 | 1039 | //
// Pagination.swift
// TraktKit
//
// Created by Sven Bacia on 07.09.17.
// Copyright © 2017 Sven Bacia. All rights reserved.
//
import Foundation
public struct Pagination {
public let page: Int
public let limit: Int
public let numberOfPages: Int
public let numberOfItems: Int
public init?(headers: [String: Any]) {
guard let pageString = headers["x-pagination-page"] as? String, let page = Int(pageString) else { return nil }
guard let limitString = headers["x-pagination-limit"] as? String, let limit = Int(limitString) else { return nil }
guard let numberOfPagesString = headers["x-pagination-page-count"] as? String, let numberOfPages = Int(numberOfPagesString) else { return nil }
guard let numberOfItemsString = headers["x-pagination-item-count"] as? String, let numberOfItems = Int(numberOfItemsString) else { return nil }
self.page = page
self.limit = limit
self.numberOfPages = numberOfPages
self.numberOfItems = numberOfItems
}
}
| mit | 87326c4eeccd75b7ccf67419a05f78f3 | 37.444444 | 151 | 0.686898 | 4.236735 | false | false | false | false |
SteveKueng/SplashBuddy | SplashBuddy/AppDelegate.swift | 1 | 2270 | //
// AppDelegate.swift
// SplashBuddy
//
// Created by ftiff on 02/08/16.
// Copyright © 2016 François Levaux-Tiffreau. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var softwareStatusValueTransformer: SoftwareStatusValueTransformer?
var mainWindowController: MainWindowController!
var backgroundController: BackgroundWindowController!
func applicationDidFinishLaunching(_ notification: Notification) {
// Value Transformer for Software Status
// We use it to map the software status (.pending…) with color images (orange…) in the Software TableView
softwareStatusValueTransformer = SoftwareStatusValueTransformer()
ValueTransformer.setValueTransformer(softwareStatusValueTransformer,
forName: NSValueTransformerName(rawValue: "SoftwareStatusValueTransformer"))
// Create Background Controller (the window behind) only displays for Release
// Change this in Edit Scheme -> Run -> Info
#if !DEBUG
let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "SplashBuddy"), bundle: nil)
backgroundController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "backgroundWindow")) as! BackgroundWindowController
backgroundController.showWindow(self)
NSApp.hideOtherApplications(self)
NSApp.presentationOptions = [ .disableProcessSwitching,
.hideDock,
.hideMenuBar,
.disableForceQuit,
.disableSessionTermination ]
#endif
// Get preferences from UserDefaults
Preferences.sharedInstance.getPreferencesApplications()
Parser.sharedInstance.readTimer()
}
@IBAction func quitAndSetSBDone(_ sender: Any) {
Preferences.sharedInstance.setupDone = true
NSApp.terminate(self)
}
}
| apache-2.0 | 20c3df50a14f01e984b5ad42285cf655 | 32.294118 | 174 | 0.611749 | 6.581395 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/WMFDatabaseHousekeeper.swift | 1 | 7474 | import Foundation
@objc class WMFDatabaseHousekeeper : NSObject {
// Returns deleted URLs
@discardableResult @objc func performHousekeepingOnManagedObjectContext(_ moc: NSManagedObjectContext, navigationStateController: NavigationStateController) throws -> [URL] {
let urls = try deleteStaleUnreferencedArticles(moc, navigationStateController: navigationStateController)
try deleteStaleTalkPages(moc)
try deleteStaleAnnouncements(moc)
return urls
}
private func deleteStaleAnnouncements(_ moc: NSManagedObjectContext) throws {
guard let announcementContentGroups = moc.orderedGroups(of: .announcement, with: nil) else {
return
}
let currentDate = Date()
for announcementGroup in announcementContentGroups {
guard let announcement = announcementGroup.contentPreview as? WMFAnnouncement,
let endDate = announcement.endTime,
currentDate > endDate else {
continue
}
moc.delete(announcementGroup)
}
if moc.hasChanges {
try moc.save()
}
}
/**
We only persist the last 50 most recently accessed talk pages, delete all others.
*/
private func deleteStaleTalkPages(_ moc: NSManagedObjectContext) throws {
let request: NSFetchRequest<NSFetchRequestResult> = TalkPage.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "dateAccessed", ascending: false)]
request.fetchOffset = 50
let batchRequest = NSBatchDeleteRequest(fetchRequest: request)
batchRequest.resultType = .resultTypeObjectIDs
let result = try moc.execute(batchRequest) as? NSBatchDeleteResult
let objectIDArray = result?.result as? [NSManagedObjectID]
let changes: [AnyHashable : Any] = [NSDeletedObjectsKey : objectIDArray as Any]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [moc])
try moc.removeUnlinkedTalkPageTopicContent()
}
private func deleteStaleUnreferencedArticles(_ moc: NSManagedObjectContext, navigationStateController: NavigationStateController) throws -> [URL] {
/**
Find `WMFContentGroup`s more than WMFExploreFeedMaximumNumberOfDays days old.
*/
let today = Date() as NSDate
guard let oldestFeedDateMidnightUTC = today.wmf_midnightUTCDateFromLocalDate(byAddingDays: 0 - WMFExploreFeedMaximumNumberOfDays) else {
assertionFailure("Calculating midnight UTC on the oldest feed date failed")
return []
}
let allContentGroupFetchRequest = WMFContentGroup.fetchRequest()
let allContentGroups = try moc.fetch(allContentGroupFetchRequest)
var referencedArticleKeys = Set<String>(minimumCapacity: allContentGroups.count * 5 + 1)
for group in allContentGroups {
if group.midnightUTCDate?.compare(oldestFeedDateMidnightUTC) == .orderedAscending {
moc.delete(group)
continue
}
if let articleURLDatabaseKey = group.articleURL?.wmf_databaseKey {
referencedArticleKeys.insert(articleURLDatabaseKey)
}
if let previewURL = group.contentPreview as? NSURL, let key = previewURL.wmf_databaseKey {
referencedArticleKeys.insert(key)
}
guard let fullContent = group.fullContent else {
continue
}
guard let content = fullContent.object as? [Any] else {
assertionFailure("Unknown Content Type")
continue
}
for obj in content {
switch (group.contentType, obj) {
case (.URL, let url as NSURL):
guard let key = url.wmf_databaseKey else {
continue
}
referencedArticleKeys.insert(key)
case (.topReadPreview, let preview as WMFFeedTopReadArticlePreview):
guard let key = (preview.articleURL as NSURL).wmf_databaseKey else {
continue
}
referencedArticleKeys.insert(key)
case (.story, let story as WMFFeedNewsStory):
guard let articlePreviews = story.articlePreviews else {
continue
}
for preview in articlePreviews {
guard let key = (preview.articleURL as NSURL).wmf_databaseKey else {
continue
}
referencedArticleKeys.insert(key)
}
case (.URL, _),
(.topReadPreview, _),
(.story, _),
(.image, _),
(.notification, _),
(.announcement, _),
(.onThisDayEvent, _),
(.theme, _):
break
default:
assertionFailure("Unknown Content Type")
}
}
}
/**
Find WMFArticles that are cached previews only, and have no user-defined state.
- A `viewedDate` of null indicates that the article was never viewed
- A `savedDate` of null indicates that the article is not saved
- A `placesSortOrder` of null indicates it is not currently visible on the Places map
- Items with `isExcludedFromFeed == YES` need to stay in the database so that they will continue to be excluded from the feed
*/
let articlesToDeleteFetchRequest = WMFArticle.fetchRequest()
// savedDate == NULL && isDownloaded == YES will be picked up by SavedArticlesFetcher for deletion
let articlesToDeletePredicate = NSPredicate(format: "viewedDate == NULL && savedDate == NULL && isDownloaded == NO && placesSortOrder == 0 && isExcludedFromFeed == NO")
if let preservedArticleKeys = navigationStateController.allPreservedArticleKeys(in: moc) {
referencedArticleKeys.formUnion(preservedArticleKeys)
}
articlesToDeleteFetchRequest.propertiesToFetch = ["key"]
articlesToDeleteFetchRequest.predicate = articlesToDeletePredicate
let articlesToDelete = try moc.fetch(articlesToDeleteFetchRequest)
var urls: [URL] = []
for obj in articlesToDelete {
guard obj.isFault else { // only delete articles that are faults. prevents deletion of articles that are being actively viewed. repro steps: open disambiguation pages view -> exit app -> re-enter app
continue
}
guard let key = obj.key, !referencedArticleKeys.contains(key) else {
continue
}
moc.delete(obj)
guard let url = obj.url else {
continue
}
urls.append(url)
}
if moc.hasChanges {
try moc.save()
}
return urls
}
}
| mit | b9d594b8abb9aa6c705e49a7e962e8de | 39.182796 | 211 | 0.574257 | 6.106209 | false | false | false | false |
jverkoey/swift-midi | LUMI/Message.swift | 1 | 4650 | import CoreMIDI
public struct Event {
let timeStamp: MIDITimeStamp
let status: UInt8
let data1: UInt8
let data2: UInt8
}
/// An individual message sent to or from a MIDI endpoint.
/// For the complete specification, visit http://www.midi.org/techspecs/Messages.php
enum Message {
// Channel voice messages
case NoteOff(channel: UInt8, key: UInt8, velocity: UInt8)
case NoteOn(channel: UInt8, key: UInt8, velocity: UInt8)
case Aftertouch(channel: UInt8, key: UInt8, pressure: UInt8)
case ControlChange(channel: UInt8, controller: UInt8, value: UInt8)
case ProgramChange(channel: UInt8, programNumber: UInt8)
case ChannelPressure(channel: UInt8, pressure: UInt8)
case PitchBend(channel: UInt8, pitch: UInt16)
// TODO: We need to store the data in raw form and convert it to the nicer enum on demand. This
// implementation is overly-complicated because it's trying to store the data in the nicer enum first.
init?(byteGenerator pop: () -> UInt8) {
let byte = pop()
if Message.isStatusByte(byte) {
let channel = Message.statusChannel(byte)
switch Message.statusMessage(byte) {
case .NoteOff: self = .NoteOff(channel: channel, key: pop(), velocity: pop())
case .NoteOn: self = .NoteOn(channel: channel, key: pop(), velocity: pop())
case .Aftertouch: self = .Aftertouch(channel: channel, key: pop(), pressure: pop())
case .ControlChange: self = .ControlChange(channel: channel, controller: pop(), value: pop())
case .ProgramChange: self = .ProgramChange(channel: channel, programNumber: pop())
case .ChannelPressure: self = .ChannelPressure(channel: channel, pressure: pop())
case .PitchBend:
// From http://midi.org/techspecs/midimessages.php
// The pitch bender is measured by a fourteen bit value. The first data byte contains the
// least significant 7 bits. The second data bytes contains the most significant 7 bits.
let low = UInt16(pop())
let high = UInt16(pop())
self = .PitchBend(channel: channel, pitch: (high << 7) | low)
}
return
}
return nil
}
func statusByte() -> UInt8 {
switch self {
case .NoteOff(let data): return (MessageValue.NoteOff.rawValue << UInt8(4)) | data.channel | Message.statusBit
case .NoteOn(let data): return (MessageValue.NoteOn.rawValue << UInt8(4)) | data.channel | Message.statusBit
case .Aftertouch(let data): return (MessageValue.Aftertouch.rawValue << UInt8(4)) | data.channel | Message.statusBit
case .ControlChange(let data): return (MessageValue.ControlChange.rawValue << UInt8(4)) | data.channel | Message.statusBit
case .ProgramChange(let data): return (MessageValue.ProgramChange.rawValue << UInt8(4)) | data.channel | Message.statusBit
case .ChannelPressure(let data): return (MessageValue.ChannelPressure.rawValue << UInt8(4)) | data.channel | Message.statusBit
case .PitchBend(let data): return (MessageValue.PitchBend.rawValue << UInt8(4)) | data.channel | Message.statusBit
}
}
func data1Byte() -> UInt8 {
switch self {
case .NoteOff(let data): return data.1
case .NoteOn(let data): return data.1
case .Aftertouch(let data): return data.1
case .ControlChange(let data): return data.1
case .ProgramChange(let data): return data.1
case .ChannelPressure(let data): return data.1
case .PitchBend(let data): return UInt8(data.pitch & 0x7F)
}
}
func data2Byte() -> UInt8 {
switch self {
case .NoteOff(let data): return data.2
case .NoteOn(let data): return data.2
case .Aftertouch(let data): return data.2
case .ControlChange(let data): return data.2
case .ProgramChange: return 0
case .ChannelPressure: return 0
case .PitchBend(let data): return UInt8((data.pitch >> 7) & 0x7F)
}
}
static private let statusBit: UInt8 = 0b10000000
static private let dataMask: UInt8 = 0b01111111
static private let messageMask: UInt8 = 0b01110000
static private let channelMask: UInt8 = 0b00001111
enum MessageValue : UInt8 {
case NoteOff = 0
case NoteOn
case Aftertouch
case ControlChange
case ProgramChange
case ChannelPressure
case PitchBend
}
static func isStatusByte(byte: UInt8) -> Bool {
return (byte & Message.statusBit) == Message.statusBit
}
static func isDataByte(byte: UInt8) -> Bool {
return (byte & Message.statusBit) == 0
}
static func statusMessage(byte: UInt8) -> MessageValue {
return MessageValue(rawValue: (byte & Message.messageMask) >> UInt8(4))!
}
static func statusChannel(byte: UInt8) -> UInt8 {
return byte & Message.channelMask
}
}
| apache-2.0 | 3ebb601045700d62ded0aca24284cf7a | 39.789474 | 130 | 0.695054 | 3.907563 | false | false | false | false |
redcirclegame/vz-pie-chart | Charts/Classes/Charts/PieRadarChartViewBase.swift | 1 | 21364 | //
// PieRadarChartViewBase.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.CGBase
import UIKit.UIGestureRecognizer
/// Base class of PieChartView and RadarChartView.
public class PieRadarChartViewBase: ChartViewBase
{
/// holds the normalized version of the current rotation angle of the chart
private var _rotationAngle = CGFloat(90.0)
/// holds the raw version of the current rotation angle of the chart
private var _rawRotationAngle = CGFloat(270.0)
/// flag that indicates if rotation is enabled or not
public var rotationEnabled = true
private var _rotationWithTwoFingers = false
private var _tapGestureRecognizer: UITapGestureRecognizer!
private var _rotationGestureRecognizer: UIRotationGestureRecognizer!
public override init(frame: CGRect)
{
super.init(frame: frame);
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
deinit
{
stopDeceleration();
}
internal override func initialize()
{
super.initialize();
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"));
_rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: Selector("rotationGestureRecognized:"));
self.addGestureRecognizer(_tapGestureRecognizer);
self.addGestureRecognizer(_rotationGestureRecognizer);
_rotationGestureRecognizer.enabled = rotationWithTwoFingers;
}
internal override func calcMinMax()
{
_deltaX = CGFloat(_data.xVals.count - 1);
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return;
}
calcMinMax();
calculateOffsets();
setNeedsDisplay();
}
internal override func calculateOffsets()
{
var legendLeft = CGFloat(0.0);
var legendRight = CGFloat(0.0);
var legendBottom = CGFloat(0.0);
var legendTop = CGFloat(0.0);
legendTop += self.extraTopOffset;
legendRight += self.extraRightOffset;
legendBottom += self.extraBottomOffset;
legendLeft += self.extraLeftOffset;
var minOffset = CGFloat(10.0);
var offsetLeft = max(minOffset, legendLeft);
var offsetTop = max(minOffset, legendTop);
var offsetRight = max(minOffset, legendRight);
var offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom));
_viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom);
}
/// returns the angle relative to the chart center for the given point on the chart in degrees.
/// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ...
public func angleForPoint(#x: CGFloat, y: CGFloat) -> CGFloat
{
var c = centerOffsets;
var tx = Double(x - c.x);
var ty = Double(y - c.y);
var length = sqrt(tx * tx + ty * ty);
var r = acos(ty / length);
var angle = r * ChartUtils.Math.RAD2DEG;
if (x > c.x)
{
angle = 360.0 - angle;
}
// add 90° because chart starts EAST
angle = angle + 90.0;
// neutralize overflow
if (angle > 360.0)
{
angle = angle - 360.0;
}
return CGFloat(angle);
}
/// Calculates the position around a center point, depending on the distance
/// from the center, and the angle of the position around the center.
internal func getPosition(#center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint
{
var a = cos(angle * ChartUtils.Math.FDEG2RAD);
return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD),
y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD));
}
/// Returns the distance of a certain point on the chart to the center of the chart.
public func distanceToCenter(#x: CGFloat, y: CGFloat) -> CGFloat
{
var c = self.centerOffsets;
var dist = CGFloat(0.0);
var xDist = CGFloat(0.0);
var yDist = CGFloat(0.0);
if (x > c.x)
{
xDist = x - c.x;
}
else
{
xDist = c.x - x;
}
if (y > c.y)
{
yDist = y - c.y;
}
else
{
yDist = c.y - y;
}
// pythagoras
dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0));
return dist;
}
/// Returns the xIndex for the given angle around the center of the chart.
/// Returns -1 if not found / outofbounds.
public func indexForAngle(angle: CGFloat) -> Int
{
fatalError("indexForAngle() cannot be called on PieRadarChartViewBase");
}
/// current rotation angle of the pie chart
/// :returns will always return a normalized value, which will be between 0.0 < 360.0
/// :default: 270 --> top (NORTH)
public var rotationAngle: CGFloat
{
get
{
return _rotationAngle;
}
set
{
_rawRotationAngle = newValue;
_rotationAngle = ChartUtils.normalizedAngleFromAngle(newValue);
setNeedsDisplay();
}
}
/// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees.
/// this is used when working with rotation direction, mainly by gestures and animations.
public var rawRotationAngle: CGFloat
{
return _rawRotationAngle;
}
/// returns the diameter of the pie- or radar-chart
public var diameter: CGFloat
{
var content = _viewPortHandler.contentRect;
return min(content.width, content.height);
}
/// Returns the radius of the chart in pixels.
public var radius: CGFloat
{
fatalError("radius cannot be called on PieRadarChartViewBase");
}
/// Returns the required bottom offset for the chart.
internal var requiredBottomOffset: CGFloat
{
fatalError("requiredBottomOffset cannot be called on PieRadarChartViewBase");
}
/// Returns the base offset needed for the chart without calculating the
/// legend size.
internal var requiredBaseOffset: CGFloat
{
fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase");
}
public override var chartXMax: Double
{
return 0.0;
}
public override var chartXMin: Double
{
return 0.0;
}
public var isRotationEnabled: Bool { return rotationEnabled; }
/// flag that indicates if rotation is done with two fingers or one.
/// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events.
/// :default: false
public var rotationWithTwoFingers: Bool
{
get
{
return _rotationWithTwoFingers;
}
set
{
_rotationWithTwoFingers = newValue;
_rotationGestureRecognizer.enabled = _rotationWithTwoFingers;
}
}
/// flag that indicates if rotation is done with two fingers or one.
/// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events.
/// :default: false
public var isRotationWithTwoFingers: Bool
{
return _rotationWithTwoFingers;
}
// MARK: - Animation
private var _spinAnimator: ChartAnimator!;
/// Applys a spin animation to the Chart.
public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?)
{
if (_spinAnimator != nil)
{
_spinAnimator.stop();
}
_spinAnimator = ChartAnimator();
_spinAnimator.updateBlock = {
self.rotationAngle = (toAngle - fromAngle) * self._spinAnimator.phaseX + fromAngle;
};
_spinAnimator.stopBlock = { self._spinAnimator = nil; };
_spinAnimator.animate(xAxisDuration: duration, easing: easing);
}
public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption)
{
spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption));
}
public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat)
{
spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil);
}
public func stopSpinAnimation()
{
if (_spinAnimator != nil)
{
_spinAnimator.stop();
}
}
// MARK: - Gestures
private var _touchStartPoint: CGPoint!
private var _isRotating = false
private var _defaultTouchEventsWereEnabled = false
private var _startAngle = CGFloat(0.0)
private struct AngularVelocitySample
{
var time: NSTimeInterval;
var angle: CGFloat;
}
private var _velocitySamples = [AngularVelocitySample]();
private var _decelerationLastTime: NSTimeInterval = 0.0
private var _decelerationDisplayLink: CADisplayLink!
private var _decelerationAngularVelocity: CGFloat = 0.0
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
// if rotation by touch is enabled
if (rotationEnabled)
{
stopDeceleration();
if (!rotationWithTwoFingers)
{
var touch = touches.first as! UITouch!;
var touchLocation = touch.locationInView(self);
self.resetVelocity();
if (rotationEnabled)
{
self.sampleVelocity(touchLocation: touchLocation);
}
self.setGestureStartAngle(x: touchLocation.x, y: touchLocation.y);
_touchStartPoint = touchLocation;
}
}
if (!_isRotating)
{
super.touchesBegan(touches, withEvent: event);
}
}
public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (rotationEnabled && !rotationWithTwoFingers)
{
var touch = touches.first as! UITouch!;
var touchLocation = touch.locationInView(self);
if (isDragDecelerationEnabled)
{
sampleVelocity(touchLocation: touchLocation);
}
if (!_isRotating && distance(eventX: touchLocation.x, startX: _touchStartPoint.x, eventY: touchLocation.y, startY: _touchStartPoint.y) > CGFloat(8.0))
{
_isRotating = true;
}
else
{
self.updateGestureRotation(x: touchLocation.x, y: touchLocation.y);
setNeedsDisplay();
}
}
if (!_isRotating)
{
super.touchesMoved(touches, withEvent: event);
}
}
public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (!_isRotating)
{
super.touchesEnded(touches, withEvent: event);
}
if (rotationEnabled && !rotationWithTwoFingers)
{
var touch = touches.first as! UITouch!;
var touchLocation = touch.locationInView(self);
if (isDragDecelerationEnabled)
{
stopDeceleration();
sampleVelocity(touchLocation: touchLocation);
_decelerationAngularVelocity = calculateVelocity();
if (_decelerationAngularVelocity != 0.0)
{
_decelerationLastTime = CACurrentMediaTime();
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"));
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
}
}
}
if (_isRotating)
{
_isRotating = false;
}
}
public override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent)
{
super.touchesCancelled(touches, withEvent: event);
if (_isRotating)
{
_isRotating = false;
}
}
private func resetVelocity()
{
_velocitySamples.removeAll(keepCapacity: false);
}
private func sampleVelocity(#touchLocation: CGPoint)
{
var currentTime = CACurrentMediaTime();
_velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y)));
// Remove samples older than our sample time - 1 seconds
for (var i = 0, count = _velocitySamples.count; i < count - 2; i++)
{
if (currentTime - _velocitySamples[i].time > 1.0)
{
_velocitySamples.removeAtIndex(0);
i--;
count--;
}
else
{
break;
}
}
}
private func calculateVelocity() -> CGFloat
{
if (_velocitySamples.isEmpty)
{
return 0.0;
}
var firstSample = _velocitySamples[0];
var lastSample = _velocitySamples[_velocitySamples.count - 1];
// Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction
var beforeLastSample = firstSample;
for (var i = _velocitySamples.count - 1; i >= 0; i--)
{
beforeLastSample = _velocitySamples[i];
if (beforeLastSample.angle != lastSample.angle)
{
break;
}
}
// Calculate the sampling time
var timeDelta = lastSample.time - firstSample.time;
if (timeDelta == 0.0)
{
timeDelta = 0.1;
}
// Calculate clockwise/ccw by choosing two values that should be closest to each other,
// so if the angles are two far from each other we know they are inverted "for sure"
var clockwise = lastSample.angle >= beforeLastSample.angle;
if (abs(lastSample.angle - beforeLastSample.angle) > 270.0)
{
clockwise = !clockwise;
}
// Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point
if (lastSample.angle - firstSample.angle > 180.0)
{
firstSample.angle += 360.0;
}
else if (firstSample.angle - lastSample.angle > 180.0)
{
lastSample.angle += 360.0;
}
// The velocity
var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta));
// Direction?
if (!clockwise)
{
velocity = -velocity;
}
return velocity;
}
/// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position
private func setGestureStartAngle(#x: CGFloat, y: CGFloat)
{
_startAngle = angleForPoint(x: x, y: y);
// take the current angle into consideration when starting a new drag
_startAngle -= _rotationAngle;
}
/// updates the view rotation depending on the given touch position, also takes the starting angle into consideration
private func updateGestureRotation(#x: CGFloat, y: CGFloat)
{
self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle;
}
public func stopDeceleration()
{
if (_decelerationDisplayLink !== nil)
{
_decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
_decelerationDisplayLink = nil;
}
}
@objc private func decelerationLoop()
{
var currentTime = CACurrentMediaTime();
_decelerationAngularVelocity *= self.dragDecelerationFrictionCoef;
var timeInterval = CGFloat(currentTime - _decelerationLastTime);
self.rotationAngle += _decelerationAngularVelocity * timeInterval;
_decelerationLastTime = currentTime;
if(abs(_decelerationAngularVelocity) < 0.001)
{
stopDeceleration();
}
}
/// returns the distance between two points
private func distance(#eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat
{
var dx = eventX - startX;
var dy = eventY - startY;
return sqrt(dx * dx + dy * dy);
}
/// returns the distance between two points
private func distance(#from: CGPoint, to: CGPoint) -> CGFloat
{
var dx = from.x - to.x;
var dy = from.y - to.y;
return sqrt(dx * dx + dy * dy);
}
/// reference to the last highlighted object
private var _lastHighlight: ChartHighlight!;
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Ended)
{
var location = recognizer.locationInView(self);
var distance = distanceToCenter(x: location.x, y: location.y);
// check if a slice was touched
if (distance > self.radius)
{
// if no slice was touched, highlight nothing
self.highlightValues(nil);
_lastHighlight = nil;
_lastHighlight = nil;
}
else
{
var angle = angleForPoint(x: location.x, y: location.y);
if (self.isKindOfClass(PieChartView))
{
angle /= _animator.phaseY;
}
var index = indexForAngle(angle);
// check if the index could be found
if (index < 0)
{
self.highlightValues(nil);
_lastHighlight = nil;
}
else
{
var dataSetIndex = 0;
var h = ChartHighlight(xIndex: index, dataSetIndex: dataSetIndex);
if (_lastHighlight !== nil && h == _lastHighlight)
{
self.highlightValue(highlight: nil, callDelegate: true);
_lastHighlight = nil;
}
else
{
self.highlightValue(highlight: h, callDelegate: true);
_lastHighlight = h;
}
}
}
}
}
@objc private func rotationGestureRecognized(recognizer: UIRotationGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration();
_startAngle = self.rawRotationAngle;
}
if (recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Changed)
{
var angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation;
self.rotationAngle = _startAngle + angle;
setNeedsDisplay();
}
else if (recognizer.state == UIGestureRecognizerState.Ended)
{
var angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation;
self.rotationAngle = _startAngle + angle;
setNeedsDisplay();
if (isDragDecelerationEnabled)
{
stopDeceleration();
_decelerationAngularVelocity = ChartUtils.Math.FRAD2DEG * recognizer.velocity;
if (_decelerationAngularVelocity != 0.0)
{
_decelerationLastTime = CACurrentMediaTime();
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"));
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
}
}
}
}
} | apache-2.0 | 6ea13c785f90fea8831b28060c3e2e9d | 30.73997 | 191 | 0.566245 | 5.451761 | false | false | false | false |
kimar/TheReservist | TheReservist/PartsViewController.swift | 2 | 2331 | //
// PartsViewController.swift
// TheReservist
//
// Created by Marcus Kida on 23/09/2014.
// Copyright (c) 2014 Marcus Kida. All rights reserved.
//
import UIKit
class PartsViewController: UITableViewController {
var parts: JSON?
let redColor = UIColor(red: 87/255, green: 194/255, blue: 87/255, alpha: 1.0)
let greenColor = UIColor(red: 194/255, green: 87/255, blue: 87/255, alpha: 1.0)
let products = Products()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
if let count = self.parts?.dictionaryValue?.count {
return count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
var partNumber = ""
var available = false
if let keys = self.parts?.dictionaryValue?.keys {
partNumber = keys.array[indexPath.row] as String
}
if let values = self.parts?.dictionaryValue?.values {
available = values.array[indexPath.row].boolValue
}
if let name = products.name(partNumber) {
var availableString = available ? "Reservation is available." : "Reservation is not available."
if let size = products.size(partNumber) {
if let color = products.color(partNumber) {
cell.textLabel?.text = "\(name) (\(color), \(size))"
cell.detailTextLabel?.textColor = available ? redColor : greenColor
cell.detailTextLabel?.text = availableString
}
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| mit | ea5e9a103906b906ebf05407dfd39354 | 32.782609 | 118 | 0.625483 | 5.067391 | false | false | false | false |
sarvex/SwiftRecepies | Data/Boosting Data Access in Table Views/Boosting Data Access in Table Views/PersonsListTableViewController.swift | 1 | 4700 | //
// PersonsListTableViewController.swift
// Boosting Data Access in Table Views
//
// Created by vandad on 167//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
import UIKit
import CoreData
class PersonsListTableViewController: UITableViewController,
NSFetchedResultsControllerDelegate {
struct TableViewConstants{
static let cellIdentifier = "Cell"
}
var barButtonAddPerson: UIBarButtonItem!
var frc: NSFetchedResultsController!
var managedObjectContext: NSManagedObjectContext?{
return (UIApplication.sharedApplication().delegate
as! AppDelegate).managedObjectContext
}
func addNewPerson(sender: AnyObject){
/* This is a custom segue identifier that we have defined in our
storyboard that simply does a "Show" segue from our view controller
to the "Add New Person" view controller */
performSegueWithIdentifier("addPerson", sender: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
barButtonAddPerson = UIBarButtonItem(barButtonSystemItem: .Add,
target: self,
action: "addNewPerson:")
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController,
didChangeObject anObject: AnyObject,
atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath?) {
if type == .Delete{
tableView.deleteRowsAtIndexPaths([indexPath!],
withRowAnimation: .Automatic)
}
else if type == .Insert{
tableView.insertRowsAtIndexPaths([newIndexPath!],
withRowAnimation: .Automatic)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
let sectionInfo = frc.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier(
TableViewConstants.cellIdentifier,
forIndexPath: indexPath) as! UITableViewCell
let person = frc.objectAtIndexPath(indexPath) as! Person
cell.textLabel!.text = person.firstName + " " + person.lastName
cell.detailTextLabel!.text = "Age: \(person.age)"
return cell
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if editing{
navigationItem.setRightBarButtonItem(nil, animated: true)
} else {
navigationItem.setRightBarButtonItem(barButtonAddPerson, animated: true)
}
}
override func tableView(tableView: UITableView,
commitEditingStyle editingStyle: UITableViewCellEditingStyle,
forRowAtIndexPath indexPath: NSIndexPath){
let personToDelete = self.frc.objectAtIndexPath(indexPath) as! Person
managedObjectContext!.deleteObject(personToDelete)
if personToDelete.deleted{
var savingError: NSError?
if managedObjectContext!.save(&savingError){
println("Successfully deleted the object")
} else {
if let error = savingError{
println("Failed to save the context with error = \(error)")
}
}
}
}
override func tableView(tableView: UITableView,
editingStyleForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCellEditingStyle {
return .Delete
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Persons"
navigationItem.leftBarButtonItem = editButtonItem()
navigationItem.rightBarButtonItem = barButtonAddPerson
/* Create the fetch request first */
let fetchRequest = NSFetchRequest(entityName: "Person")
let ageSort = NSSortDescriptor(key: "age", ascending: true)
let firstNameSort = NSSortDescriptor(key: "firstName", ascending: true)
fetchRequest.sortDescriptors = [ageSort, firstNameSort]
frc = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: managedObjectContext!,
sectionNameKeyPath: nil,
cacheName: nil)
frc.delegate = self
var fetchingError: NSError?
if frc.performFetch(&fetchingError){
println("Successfully fetched")
} else {
println("Failed to fetch")
}
}
}
| isc | 202afecf240d115be9df618ff0acbb58 | 27.484848 | 78 | 0.690213 | 5.703883 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDKTests/MXAuthenticationSessionUnitTests.swift | 1 | 3879 | //
// Copyright 2020 The Matrix.org Foundation C.I.C
//
// 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 XCTest
import MatrixSDK
class MXAuthenticationSessionUnitTests: XCTestCase {
func testParsing() throws {
let json: [String: Any] = [
"completed": [],
"session": "2134",
"flows": [
["type": "m.login.password",
"stages": [],
],
["type": "m.login.sso",
"stages": [],
MXLoginSSOFlowIdentityProvidersKey: [
["id": "gitlab",
"name": "GitLab"
],
["id": "github",
"name": "GitHub",
"icon": "https://github/icon.png"
]
]
],
["type": "m.login.cas",
"stages": [],
"identity_providers": []
]
],
"params": [
]
]
let authenticationSession = MXAuthenticationSession(fromJSON: json)
guard let flows = authenticationSession?.flows else {
XCTFail("flows shouldn not be nil")
return
}
XCTAssertEqual(flows.count, 3)
if let ssoFlow = flows.first(where: { $0.type == kMXLoginFlowTypeSSO }) {
if let loginSSOFlow = ssoFlow as? MXLoginSSOFlow {
XCTAssertEqual(loginSSOFlow.identityProviders.count, 2)
if let gitlabProvider = loginSSOFlow.identityProviders.first(where: { $0.identifier == "gitlab" }) {
XCTAssertEqual(gitlabProvider.name, "GitLab")
XCTAssertNil(gitlabProvider.icon)
} else {
XCTFail("Fail to find GitLab provider")
}
if let githubProvider = loginSSOFlow.identityProviders.first(where: { $0.identifier == "github" }) {
XCTAssertEqual(githubProvider.name, "GitHub")
XCTAssertEqual(githubProvider.icon, "https://github/icon.png")
} else {
XCTFail("Fail to find GitHub provider")
}
} else {
XCTFail("The SSO flow is not member of class MXLoginSSOFlow")
}
} else {
XCTFail("Fail to find SSO flow")
}
if let casFlow = flows.first(where: { $0.type == kMXLoginFlowTypeCAS }) {
if let loginSSOFlow = casFlow as? MXLoginSSOFlow {
XCTAssertTrue(loginSSOFlow.identityProviders.isEmpty)
} else {
XCTFail("The CAS flow is not member of class MXLoginSSOFlow")
}
} else {
XCTFail("Fail to find CAS flow")
}
if let passwordFlow = flows.first(where: { $0.type == kMXLoginFlowTypePassword }) {
XCTAssertFalse(passwordFlow is MXLoginSSOFlow)
} else {
XCTFail("Fail to find password flow")
}
}
}
| apache-2.0 | 10ce05974f483b408057f2c4d1babaa6 | 33.026316 | 116 | 0.484919 | 5.313699 | false | false | false | false |
ivygulch/IVGFoundation | IVGFoundation/source/extensions/UIColor+IVGFoundation.swift | 1 | 3721 | //
// UIColor+IVGFoundation
// IVGFoundation
//
// Created by Douglas Sjoquist on 5/20/16.
// Copyright © 2017 Ivy Gulch. All rights reserved.
//
import UIKit
private func doubleHexDigit(_ byte:Int) -> Int {
return byte*16 + byte
}
private func hexValue(_ hexString:String, _ start:Int, _ len:Int) -> Int? {
let startIndex = hexString.index(hexString.startIndex, offsetBy: start)
let endIndex = hexString.index(hexString.startIndex, offsetBy: start + len)
let hexSubstring = hexString[startIndex ..< endIndex]
return Int(hexSubstring, radix: 16)
}
public extension UIColor {
// note per rule 2 from here:
// https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID219
// we need to call an initializer even when we fail, since we are a convenience init
// the rule doesn't seem explicit, but adding the 'self.init(...)' before returning nil
// keeps swift 2.2 runtime from choking
//
// (found via this post)
// http://stackoverflow.com/questions/26854572/create-convenience-initializer-on-subclass-that-calls-failable-initializer
public convenience init?(hexString:String) {
var useString = hexString
if useString.isEmpty {
self.init(red:0, green:0, blue:0, alpha: 0)
return nil
}
if String(useString[useString.startIndex]) == "#" {
let index = useString.index(after: useString.startIndex)
useString = String(useString[index...])
}
let len = useString.lengthOfBytes(using: String.Encoding.utf8)
var red:CGFloat
var blue:CGFloat
var green:CGFloat
var alpha:CGFloat
switch (len) {
case 3:
guard let v0 = hexValue(useString,0,1), let v1 = hexValue(useString,1,1), let v2 = hexValue(useString,2,1) else {
self.init(red:0, green:0, blue:0, alpha: 0)
return nil
}
red = CGFloat(doubleHexDigit(v0)) / 255.0
green = CGFloat(doubleHexDigit(v1)) / 255.0
blue = CGFloat(doubleHexDigit(v2)) / 255.0
alpha = 1.0
case 4:
guard let v0 = hexValue(useString,0,1), let v1 = hexValue(useString,1,1), let v2 = hexValue(useString,2,1), let v3 = hexValue(useString,3,1) else {
self.init(red:0, green:0, blue:0, alpha: 0)
return nil
}
red = CGFloat(doubleHexDigit(v0)) / 255.0
green = CGFloat(doubleHexDigit(v1)) / 255.0
blue = CGFloat(doubleHexDigit(v2)) / 255.0
alpha = CGFloat(doubleHexDigit(v3)) / 255.0
case 6:
guard let v0 = hexValue(useString,0,2), let v1 = hexValue(useString,2,2), let v2 = hexValue(useString,4,2) else {
self.init(red:0, green:0, blue:0, alpha: 0)
return nil
}
red = CGFloat(v0) / 255.0
green = CGFloat(v1) / 255.0
blue = CGFloat(v2) / 255.0
alpha = 1.0
case 8:
guard let v0 = hexValue(useString,0,2), let v1 = hexValue(useString,2,2), let v2 = hexValue(useString,4,2), let v3 = hexValue(useString,6,2) else {
self.init(red:0, green:0, blue:0, alpha: 0)
return nil
}
red = CGFloat(v0) / 255.0
green = CGFloat(v1) / 255.0
blue = CGFloat(v2) / 255.0
alpha = CGFloat(v3) / 255.0
default:
self.init(red:0, green:0, blue:0, alpha: 0)
return nil
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
| mit | 04613635075099a98d7eca903ee850db | 38.157895 | 168 | 0.586559 | 3.75 | false | false | false | false |
benjaminthedev/swoosh-xcode-app | swoosh-xcode-app/swoosh-xcode-app/LeagueVC.swift | 1 | 1124 | //
// LeagueVC.swift
// swoosh-xcode-app
//
// Created by Benjamin on 19/08/2017.
// Copyright © 2017 Benjamin. All rights reserved.
//
import UIKit
class LeagueVC: UIViewController {
var player: Player!
@IBOutlet weak var nextBtn: BorderButton!
@IBAction func onNextTapped(_ sender: Any) {
performSegue(withIdentifier: "skillVCSegue", sender: self)
}
@IBAction func onMensTapped(_ sender: Any) {
selectLeague(leagueType: "mens")
}
@IBAction func onWomensTapped(_ sender: Any) {
selectLeague(leagueType: "womens")
}
@IBAction func onCoedTapped(_ sender: Any) {
selectLeague(leagueType: "coed")
}
func selectLeague(leagueType: String){
player.desiredLeague = leagueType
nextBtn.isEnabled = true
}
override func viewDidLoad() {
super.viewDidLoad()
player = Player()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let skillVC = segue.destination as? SkillVC {
skillVC.player = player
}
}
}
| gpl-3.0 | 2937d87e0fd24df906cdbd3817285352 | 21.019608 | 71 | 0.609083 | 4.128676 | false | false | false | false |
wireapp/wire-ios | WireCommonComponents/BackendEnvironment+Shared.swift | 1 | 1839 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireTransport
private let zmsLog = ZMSLog(tag: "backend-environment")
extension BackendEnvironment {
public static let backendSwitchNotification = Notification.Name("backendEnvironmentSwitchNotification")
public static var shared: BackendEnvironment = {
var environmentType: EnvironmentType?
if let typeOverride = AutomationHelper.sharedHelper.backendEnvironmentTypeOverride() {
environmentType = EnvironmentType(stringValue: typeOverride)
}
guard let environment = BackendEnvironment(userDefaults: .applicationGroupCombinedWithStandard, configurationBundle: .backendBundle, environmentType: environmentType) else {
fatalError("Malformed backend configuration data")
}
return environment
}() {
didSet {
AutomationHelper.sharedHelper.disableBackendTypeOverride()
shared.save(in: .applicationGroup)
NotificationCenter.default.post(name: backendSwitchNotification, object: shared)
zmsLog.debug("Shared backend environment did change to: \(shared.title)")
}
}
}
| gpl-3.0 | 81b35ca7f36f734d2fb0144f33284a3b | 41.767442 | 181 | 0.728657 | 4.904 | false | false | false | false |
spreedly/spreedly-ios | Spreedly/AdyenLifecycle.swift | 1 | 5934 | //
// AdyenLifecycle.swift
// Spreedly
//
// Created by David Santoso on 8/19/19.
// Copyright © 2019 Spreedly Inc. All rights reserved.
//
import Foundation
import Adyen3DS2
import SwiftyJSON
public class AdyenLifecycle: TransactionLifecycle {
var adyTransaction: ADYTransaction?
var adyService: ADYService?
override init(_ threeDsContext: JSON) {
super.init(threeDsContext)
}
override public func getDeviceFingerprintData(fingerprintDataCompletion: @escaping (String) -> Void) {
let params = ADYServiceParameters()
params.directoryServerIdentifier = initialThreeDsContext!["adyen"]["threeds2.threeDS2DirectoryServerInformation.directoryServerId"].stringValue
params.directoryServerPublicKey = initialThreeDsContext!["adyen"]["threeds2.threeDS2DirectoryServerInformation.publicKey"].stringValue
ADYService.service(with: params, appearanceConfiguration: nil, completionHandler: { service in
do {
self.adyService = service
self.adyTransaction = try self.adyService?.transaction(withMessageVersion: nil)
let authenticationRequestParameters = self.adyTransaction?.authenticationRequestParameters
let sdkEphemPubKeyParams = JSON(parseJSON: authenticationRequestParameters?.sdkEphemeralPublicKey ?? "{}")
let fingerprintData: [String: Any] = [
"threeDS2RequestData": [
"deviceChannel": "app",
"sdkEncData": authenticationRequestParameters?.deviceInformation ?? "",
"sdkAppID": authenticationRequestParameters?.sdkApplicationIdentifier ?? "",
"sdkTransID": authenticationRequestParameters?.sdkTransactionIdentifier ?? "",
"sdkReferenceNumber": authenticationRequestParameters?.sdkReferenceNumber ?? "",
"sdkEphemPubKey": [
"y": sdkEphemPubKeyParams["y"].stringValue,
"x": sdkEphemPubKeyParams["x"].stringValue,
"kty": sdkEphemPubKeyParams["kty"].stringValue,
"crv": sdkEphemPubKeyParams["crv"].stringValue,
],
"messageVersion": authenticationRequestParameters?.messageVersion ?? ""
]
]
let jsonDeviceData = try! JSONSerialization.data(withJSONObject: fingerprintData, options: [])
let decoded = String(data: jsonDeviceData, encoding: .utf8)!
let utf8str = decoded.data(using: String.Encoding.utf8)
let base64Encoded = utf8str!.base64EncodedString()
fingerprintDataCompletion(base64Encoded)
} catch let error as NSError {
print("Error: \(error)")
}
})
}
override public func doChallenge(rawThreeDsContext: String, challengeCompletion: @escaping (String) -> Void) {
let decodedData = Data(base64Encoded: rawThreeDsContext)!
let decodedString = String(data: decodedData, encoding: .utf8)!
challengeThreeDsContext = JSON(parseJSON: decodedString)
let serverTransId = challengeThreeDsContext?["adyen"]["threeds2.threeDS2ResponseData.threeDSServerTransID"].stringValue
let TransId = challengeThreeDsContext?["adyen"]["threeds2.threeDS2ResponseData.acsTransID"].stringValue
let referenceNumber = challengeThreeDsContext?["adyen"]["threeds2.threeDS2ResponseData.acsReferenceNumber"].stringValue
let signedContent = challengeThreeDsContext?["adyen"]["threeds2.threeDS2ResponseData.acsSignedContent"].stringValue
let challengeParameters = ADYChallengeParameters(
serverTransactionIdentifier: serverTransId!,
acsTransactionIdentifier: TransId!,
acsReferenceNumber: referenceNumber!,
acsSignedContent: signedContent!
)
adyTransaction?.performChallenge(with: challengeParameters, completionHandler: { (result, error) in
if (result != nil) {
let challengeResponseData = [
"threeDS2Result": [
"transStatus": result!.transactionStatus
]
]
let jsonDeviceData = try! JSONSerialization.data(withJSONObject: challengeResponseData, options: [])
let decoded = String(data: jsonDeviceData, encoding: .utf8)!
let utf8str = decoded.data(using: String.Encoding.utf8)
let base64Encoded = utf8str!.base64EncodedString()
challengeCompletion(base64Encoded)
} else {
print("Unable to complete challenge")
}
})
}
override public func doRedirect(window: UIWindow?, redirectUrl: String, checkoutForm: String, checkoutUrl: String, redirectCompletion: @escaping (String) -> Void) {
guard let _ = window else {
print("Aborting doRedirect window was nil")
return
}
let existingView = window!.rootViewController
let enhancedRedirectCompletion = { (token: String) -> Void in
window!.rootViewController = existingView
window!.makeKeyAndVisible()
redirectCompletion(token)
}
let viewController = RedirectViewController(redirectUrl: redirectUrl, checkoutForm: checkoutForm, checkoutUrl: checkoutUrl, completionHandler: enhancedRedirectCompletion)
window!.rootViewController = viewController
window!.makeKeyAndVisible()
}
override public func cleanup() {
self.adyService = nil
self.adyTransaction = nil
self.initialThreeDsContext = nil
self.challengeThreeDsContext = nil
}
}
| mit | eba37f70d408a929f11ea7f450c3369b | 46.464 | 178 | 0.631215 | 5.699328 | false | false | false | false |
cemolcay/ImageFreeCut | ImageFreeCut/ImageFreeCutView.swift | 1 | 4011 | //
// ImageFreeCutView.swift
// ImageFreeCut
//
// Created by Cem Olcay on 17/10/16.
// Copyright © 2016 Mojilala. All rights reserved.
//
import UIKit
import QuartzCore
public protocol ImageFreeCutViewDelegate: class {
func imageFreeCutView(_ imageFreeCutView: ImageFreeCutView, didCut image: UIImage?)
}
open class ImageFreeCutView: UIView {
open var imageView: UIImageView!
open var imageCutShapeLayer: CAShapeLayer!
open weak var delegate: ImageFreeCutViewDelegate?
open var imageToCut: UIImage? {
didSet {
imageView.image = imageToCut
}
}
private var drawPoints: [CGPoint] = [] {
didSet {
drawShape()
}
}
// MARK: Init
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
// Setup image view
imageView = UIImageView(frame: frame)
addSubview(imageView)
imageView.image = imageToCut
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
// Setup image cut shape layer
imageCutShapeLayer = CAShapeLayer()
imageCutShapeLayer.frame = imageView.bounds
imageCutShapeLayer.fillColor = UIColor.clear.cgColor
imageCutShapeLayer.lineWidth = 1
imageCutShapeLayer.strokeColor = UIColor.black.cgColor
imageCutShapeLayer.lineJoin = kCALineJoinRound
imageCutShapeLayer.lineDashPattern = [4, 4]
imageView.layer.addSublayer(imageCutShapeLayer)
}
// MARK: Lifecycle
override open func layoutSubviews() {
super.layoutSubviews()
imageCutShapeLayer.frame = imageView.bounds
}
// MARK: Touch Handling
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let touchPosition = touches.first?.location(in: imageView) else { return }
drawPoints.append(touchPosition)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let touchPosition = touches.first?.location(in: imageView) else { return }
drawPoints.append(touchPosition)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
guard let touchPosition = touches.first?.location(in: imageView) else { return }
drawPoints.append(touchPosition)
// Close path
guard let cgPath = imageCutShapeLayer.path else { return }
let path = UIBezierPath(cgPath: cgPath)
path.close()
imageCutShapeLayer.path = path.cgPath
// Notify delegate
delegate?.imageFreeCutView(self, didCut: cropImage())
resetShape()
}
// MARK: Cutting Crew
private func resetShape() {
drawPoints = []
imageView.layer.mask = nil
}
private func drawShape() {
if drawPoints.isEmpty {
imageCutShapeLayer.path = nil
return
}
let path = UIBezierPath()
for (index, point) in drawPoints.enumerated() {
if index == 0 {
path.move(to: point)
} else {
path.addLine(to: point)
}
}
imageCutShapeLayer.path = path.cgPath
}
private func cropImage() -> UIImage? {
guard let originalImage = imageToCut, let cgPath = imageCutShapeLayer.path else { return nil }
let path = UIBezierPath(cgPath: cgPath)
UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0)
path.addClip()
originalImage.draw(in: imageView.bounds)
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return croppedImage
}
}
| mit | 5f943ffc35c43d85e42907760fc893d4 | 28.057971 | 98 | 0.710474 | 4.684579 | false | false | false | false |
therealbnut/swift | test/SILGen/default_arguments_inherited.swift | 2 | 1727 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// When we synthesize an inherited designated initializer, the default
// arguments are still conceptually rooted on the base declaration.
// When we call such an initializer, we have to construct substitutions
// in terms of the base class generic signature, rather than the
// derived class generic signature.
class Puppy<T, U> {
init(t: T? = nil, u: U? = nil) {}
}
class Chipmunk : Puppy<Int, String> {}
class Kitten<V> : Puppy<Int, V> {}
class Goldfish<T> {
class Shark<U> : Puppy<T, U> {}
}
// CHECK-LABEL: sil hidden @_TF27default_arguments_inherited4doItFT_T_ : $@convention(thin) () -> () {
func doIt() {
// CHECK: [[ARG1:%.*]] = function_ref @_TIFC27default_arguments_inherited5PuppycFT1tGSqx_1uGSqq___GS0_xq__A_
// CHECK: apply [[ARG1]]<Int, String>({{.*}})
// CHECK: [[ARG2:%.*]] = function_ref @_TIFC27default_arguments_inherited5PuppycFT1tGSqx_1uGSqq___GS0_xq__A0_
// CHECK: apply [[ARG2]]<Int, String>({{.*}})
_ = Chipmunk()
// CHECK: [[ARG1:%.*]] = function_ref @_TIFC27default_arguments_inherited5PuppycFT1tGSqx_1uGSqq___GS0_xq__A_
// CHECK: apply [[ARG1]]<Int, String>(%{{.*}})
// CHECK: [[ARG2:%.*]] = function_ref @_TIFC27default_arguments_inherited5PuppycFT1tGSqx_1uGSqq___GS0_xq__A0_
// CHECK: apply [[ARG2]]<Int, String>(%{{.*}})
_ = Kitten<String>()
// CHECK: [[ARG1:%.*]] = function_ref @_TIFC27default_arguments_inherited5PuppycFT1tGSqx_1uGSqq___GS0_xq__A_
// CHECK: apply [[ARG1]]<String, Int>(%{{.*}})
// CHECK: [[ARG2:%.*]] = function_ref @_TIFC27default_arguments_inherited5PuppycFT1tGSqx_1uGSqq___GS0_xq__A0_
// CHECK: apply [[ARG2]]<String, Int>(%{{.*}})
_ = Goldfish<String>.Shark<Int>()
}
| apache-2.0 | d0c4b713318e2b9839c45c4ea873b66c | 42.175 | 111 | 0.651998 | 3.295802 | false | false | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/HomeKit/NORHKScannerViewController.swift | 1 | 3641 | //
// NORHKScannerViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 07/03/2017.
// Copyright © 2017 Nordic Semiconductor. All rights reserved.
//
import UIKit
import HomeKit
class NORHKScannerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, HMAccessoryBrowserDelegate {
//MARK: - Outlets and Actions
@IBOutlet weak var devicesTable: UITableView!
@IBOutlet weak var emptyView: UIView!
@IBAction func cancelButtonTapped(_ sender: Any) {
self.dismiss(animated: true)
}
//MARK: - Scanner implementation
public var delegate: NORHKScannerDelegate?
private var discoveredAccessories = [HMAccessory]()
private let accessoryBrowser = HMAccessoryBrowser()
private func startScanning() {
accessoryBrowser.delegate = self
accessoryBrowser.startSearchingForNewAccessories()
}
//MARK: - UIViewControllerw Flow
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: true)
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
activityIndicatorView.hidesWhenStopped = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: activityIndicatorView)
activityIndicatorView.startAnimating()
startScanning()
}
override func viewWillDisappear(_ animated: Bool) {
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
super.viewWillDisappear(animated)
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let selectedAccessory = discoveredAccessories[indexPath.row]
delegate?.browser(aBrowser: accessoryBrowser, didSelectAccessory: selectedAccessory)
self.dismiss(animated: true)
}
//MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "HKAccessoryCell", for: indexPath)
aCell.textLabel?.text = discoveredAccessories[indexPath.row].name
if #available(iOS 9.0, *) {
aCell.detailTextLabel?.text = discoveredAccessories[indexPath.row].category.localizedDescription
} else {
aCell.detailTextLabel?.text = ""
}
return aCell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return discoveredAccessories.count
}
//MARK: - HMAccessoryBrowserDelegate
func accessoryBrowser(_ browser: HMAccessoryBrowser, didFindNewAccessory accessory: HMAccessory) {
guard discoveredAccessories.contains(accessory) == false else {
return
}
if discoveredAccessories.count == 0 {
UIView.animate(withDuration: 0.5, animations: {
self.emptyView.alpha = 0
})
}
discoveredAccessories.append(accessory)
devicesTable.reloadData()
}
func accessoryBrowser(_ browser: HMAccessoryBrowser, didRemoveNewAccessory accessory: HMAccessory) {
guard discoveredAccessories.contains(accessory) == true else {
return
}
discoveredAccessories.remove(at: discoveredAccessories.index(of: accessory)!)
devicesTable.reloadData()
}
}
| bsd-3-clause | 0378a46a71b743e91e71f37c8babcb2c | 36.916667 | 131 | 0.696703 | 5.777778 | false | false | false | false |
voloshynslavik/MVx-Patterns-In-Swift | MVX Patterns In Swift/Utils/Picsum Photos/PicsumPhotosManager.swift | 1 | 1106 | //
// PicsumPhotosManager.swift
// MVX Patterns In Swift
//
// Created by Voloshyn Slavik on 5/22/19.
//
import Foundation
final class PicsumPhotosManager: BaseHttpManager {
private let decoder = JSONDecoder()
func getPhotos(_ pageIndex: Int = 1, photoLimits: Int = 50, callback: @escaping ((_ photos: [PicsumPhoto]?, _ error: Error?) -> Void)) {
let url = "https://picsum.photos/v2/list?page=\(pageIndex)&limit=\(photoLimits)"
self.get(url) { [weak self] (data, _, reguestError) in
var photos: [PicsumPhoto]?
var decodingError: Error?
defer {
DispatchQueue.main.async(execute: {
callback(photos, reguestError ?? decodingError)
})
}
if let data = data {
do {
photos = try self?.decoder.decode([PicsumPhoto].self, from: data)
} catch let error {
decodingError = error
}
}
}
}
}
| mit | f1c2b8187c652e9c16f26a7ffafec4a5 | 27.358974 | 140 | 0.499096 | 4.495935 | false | false | false | false |
jkolb/ModestProposal | ModestProposal/NSURL+HTTP.swift | 2 | 1654 | // Copyright (c) 2016 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public extension NSURL {
public func relativeToPath(path: String, parameters: [String:String] = [:]) -> NSURL {
let components = NSURLComponents()
components.percentEncodedPath = path
components.parameters = parameters
return components.URLRelativeToURL(self)!
}
public var parameters: [String:String] {
let components = NSURLComponents()
components.percentEncodedQuery = query
return components.parameters ?? [:]
}
}
| mit | c8beaf4bd85b6d62f742f61731cf9cd8 | 44.944444 | 90 | 0.734583 | 4.864706 | false | false | false | false |
odigeoteam/TableViewKit | TableViewKitTests/ArrayChangesUtils.swift | 1 | 1329 | import Foundation
@testable import TableViewKit
extension ArrayChanges: Equatable {
public static func == (lhs: ArrayChanges<Element>, rhs: ArrayChanges<Element>) -> Bool {
guard
let lhs = lhs as? ArrayChanges<Int>,
let rhs = rhs as? ArrayChanges<Int> else { return false }
switch (lhs, rhs) {
case (let .inserts(indexesLhs, elementsLhs),
let .inserts(indexesRhs, elementsRhs)),
(let .deletes(indexesLhs, elementsLhs),
let .deletes(indexesRhs, elementsRhs)):
return indexesLhs == indexesRhs && elementsLhs == elementsRhs
case (let .updates(indexesLhs),
let .updates(indexesRhs)):
return indexesLhs == indexesRhs
case (let .moves(indexesLhs),
let .moves(indexesRhs)):
return indexesLhs.elementsEqual(indexesRhs, by: { $0.0 == $1.0 && $0.1 == $1.1 })
case (let .beginUpdates(fromElementsLhs, toElementsLhs),
let .beginUpdates(fromElementsRhs, toElementsRhs)),
(let .endUpdates(fromElementsLhs, toElementsLhs),
let .endUpdates(fromElementsRhs, toElementsRhs)):
return fromElementsLhs == fromElementsRhs && toElementsLhs == toElementsRhs
default:
return false
}
}
}
| mit | 0a7fc241c6e68b52fa42d1370f4e8d32 | 43.3 | 93 | 0.607223 | 4.696113 | false | false | false | false |
ScottLegrove/HoneyDueIOS | Honey Due/UserHelper.swift | 1 | 3262 | //
// UserHelper.swift
// asdf
//
// Created by Tech on 2016-04-12.
// Copyright © 2016 GBC. All rights reserved.
//
import Foundation
class UserHelper{
static func Login(uName:String, uPass:String)->String?{
let data = APIConsumer.GetLoginJson(uName, password:uPass);
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []);
if let _ = json?["error"] as! String?{
return nil
}
if (json?.count > 0) {
return json!["token"] as? String;
}
return nil;
}
static func CreateUser(userName:String, password:String, email:String)->Bool{
let data = APIConsumer.GetRegisterJson(userName, password: password, email: email);
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []);
if json?.count > 0 {
if let result = json!["success"] as! Bool?
{
return result
}
return false
}
return false;
}
static func DeleteUser(listId: Int, userId: Int, token: String) -> Bool {
let data = APIConsumer.DeleteUserJson(listId, userId: userId, token: token);
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []);
if json?.count > 0 {
if let result = json!["success"] as! Bool?
{
return result
}
return false
}
return false;
}
static func AddUser(listId: Int, username: String, token: String) -> Bool {
let data = APIConsumer.AddUserJson(listId, username: username, token: token);
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []);
if json?.count > 0 {
if let result = json!["success"] as! Bool?
{
return result
}
return false
}
return false;
}
static func GetUser(listId: Int, userId: Int, token: String) -> OtherUser? {
let data = APIConsumer.GetUserJson(listId, userId: userId, token: token);
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []);
if json?.count == 2 {
if let _ = json?["error"] as! String?{
return nil
}
return OtherUser(name: json?["username"] as! String, id: Int(json?["id"] as! String)!);
}
return nil;
}
static func GetUsers(listId: Int, token: String) -> Array<OtherUser>? {
let data = APIConsumer.GetUsersJson(listId, token: token);
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []);
var users = Array<OtherUser>();
if json?.count > 0 {
if let user = json!["items"] as? [[String : AnyObject]]{
for i in user {
users.append(OtherUser(name: i["username"] as! String, id: Int(i["id"] as! String)!));
}
return users;
}
}
return nil;
}
func UpdateUser(){
}
} | mit | a16e6cf9cbcb5e857be1af3f9df33397 | 28.654545 | 106 | 0.518553 | 4.739826 | false | false | false | false |
banxi1988/Staff | Pods/PinAutoLayout/Pod/Classes/UIView+PinAutoLayout.swift | 2 | 17631 | //
// UIView+PinAutoLayout.swift
// banxi1988
// @LastModified 2015/09/30
// Created by banxi1988 on 15/5/28.
// Copyright (c) 2015年 banxi1988. All rights reserved.
//
import UIKit
public extension UIEdgeInsets{
public init (margin:CGFloat){
top = margin
left = margin
right = margin
bottom = margin
}
}
public class PAEdgeConstraints{
public var leading:NSLayoutConstraint?
public var trailing:NSLayoutConstraint?
public var top:NSLayoutConstraint?
public var bottom:NSLayoutConstraint?
public func updateBy(edge:UIEdgeInsets){
leading?.constant = edge.left
trailing?.constant = edge.right
top?.constant = edge.top
bottom?.constant = edge.bottom
}
}
public class PACenterConstraints{
public let centerX:NSLayoutConstraint
public let centerY:NSLayoutConstraint
public init(centerX:NSLayoutConstraint,centerY:NSLayoutConstraint){
self.centerX = centerX
self.centerY = centerY
}
}
public class PASizeConstraints{
public let width:NSLayoutConstraint
public let height:NSLayoutConstraint
public init(width:NSLayoutConstraint,height:NSLayoutConstraint){
self.width = width
self.height = height
}
public func updateBy(size:CGSize){
width.constant = size.width
height.constant = size.height
}
}
public let PA_DEFAULT_MARGIN : CGFloat = 15
public let PA_DEFAULT_SIBLING_MARGIN : CGFloat = 8
public extension UIView{
private func assertHasSuperview(){
assert(superview != nil, "NO SUPERVIEW")
}
public func pinTop(margin:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superview!, attribute: .Top, multiplier: 1.0, constant: margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinLeading(margin:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: superview!, attribute: .Leading, multiplier: 1.0, constant: margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinBottom(margin:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: superview!, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinTrailing(margin:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: superview!, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinVertical(margin:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> PAEdgeConstraints{
let edgeC = PAEdgeConstraints()
edgeC.top = pinTop(margin,priority: priority)
edgeC.bottom = pinBottom(margin,priority: priority)
return edgeC
}
public func pinHorizontal(margin:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> PAEdgeConstraints{
let edgeC = PAEdgeConstraints()
edgeC.leading = pinLeading(margin,priority: priority)
edgeC.trailing = pinTrailing(margin,priority: priority)
return edgeC
}
public func pinEdge(margin:UIEdgeInsets=UIEdgeInsetsZero,priority:UILayoutPriority=UILayoutPriorityRequired) -> PAEdgeConstraints{
let edgeC = PAEdgeConstraints()
edgeC.leading = pinLeading(margin.left,priority: priority)
edgeC.trailing = pinTrailing(margin.right,priority: priority)
edgeC.top = pinTop(margin.top,priority: priority)
edgeC.bottom = pinBottom(margin.bottom,priority: priority)
return edgeC
}
public func pinTopLeading(top:CGFloat = PA_DEFAULT_MARGIN, leading:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> PAEdgeConstraints{
let edgeC = PAEdgeConstraints()
edgeC.top = pinTop(top,priority: priority)
edgeC.leading = pinLeading(leading,priority: priority)
return edgeC
}
public func pinTopTrailing(top:CGFloat = PA_DEFAULT_MARGIN,trailing:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> PAEdgeConstraints{
let edgeC = PAEdgeConstraints()
edgeC.top = pinTop(top,priority: priority)
edgeC.trailing = pinTrailing(trailing,priority: priority)
return edgeC
}
public func pinBottomLeading(bottom:CGFloat = PA_DEFAULT_MARGIN,
leading:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> PAEdgeConstraints{
let edgeC = PAEdgeConstraints()
edgeC.bottom = pinTop(bottom,priority: priority)
edgeC.leading = pinLeading(leading,priority: priority)
return edgeC
}
public func pinBottomTrailing(bottom:CGFloat = PA_DEFAULT_MARGIN,
trailing:CGFloat = PA_DEFAULT_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> PAEdgeConstraints{
let edgeC = PAEdgeConstraints()
edgeC.bottom = pinTop(bottom,priority: priority)
edgeC.trailing = pinLeading(trailing,priority: priority)
return edgeC
}
private func assertIsSibling(sibling:UIView){
assert(superview != nil, "NO SUPERVIEW")
assert(superview == sibling.superview, "NOT SIBLING")
}
public func pinLeadingToSibling(sibling:UIView,margin:CGFloat = PA_DEFAULT_SIBLING_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: sibling, attribute: .Trailing, multiplier: 1.0, constant: margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinLeadingEqualWithSibling(sibling:UIView,offset:CGFloat = 0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: sibling, attribute: .Leading, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinTrailingEqualWithSibling(sibling:UIView,offset:CGFloat = 0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: sibling, attribute: .Trailing, multiplier: 1.0, constant: -offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinTrailingToSibing(sibling:UIView,margin:CGFloat = PA_DEFAULT_SIBLING_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute:.Trailing , relatedBy: .Equal, toItem: sibling, attribute: .Leading, multiplier: 1.0, constant: -margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinAboveSibling(sibling:UIView,margin:CGFloat = PA_DEFAULT_SIBLING_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute:.Bottom , relatedBy: .Equal, toItem: sibling, attribute: .Top, multiplier: 1.0, constant: -margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinBelowSibling(sibling:UIView,margin:CGFloat = PA_DEFAULT_SIBLING_MARGIN,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: sibling, attribute: .Bottom, multiplier: 1.0, constant: margin)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinTopWithSibling(sibling:UIView,offset:CGFloat = 0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: sibling, attribute: .Top, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinBottomWithSibling(sibling:UIView,offset:CGFloat = 0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: sibling, attribute: .Bottom, multiplier: 1.0, constant: -offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinCenterXToSibling(sibling:UIView,offset:CGFloat = 0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: sibling, attribute: .CenterX, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinCenterYToSibling(sibling:UIView,offset:CGFloat = 0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal, toItem: sibling, attribute: .CenterY, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinWidthToSibling(sibling:UIView,multiplier:CGFloat = 1.0,constant :CGFloat = 0.0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: sibling, attribute: .Width, multiplier: multiplier, constant: constant)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinHeightToSibling(sibling:UIView,multiplier:CGFloat = 1.0,constant :CGFloat = 0.0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertIsSibling(sibling)
let c = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: sibling, attribute: .Height, multiplier: multiplier, constant: constant)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinWidth(width:CGFloat,priority:UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint{
let c = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: width)
c.priority = priority
self.addConstraint(c)
return c
}
public func pinWidthGreaterThanOrEqual(width:CGFloat,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
let c = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: width)
c.priority = priority
self.addConstraint(c)
return c
}
func pinWidthLessThanOrEqual(width:CGFloat,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
let c = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .LessThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: width)
c.priority = priority
self.addConstraint(c)
return c
}
func pinHeight(height:CGFloat,priority:UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint{
let c = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: height)
c.priority = priority
self.addConstraint(c)
return c
}
public func pinHeightGreaterThanOrEqual(height:CGFloat,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
let c = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: height)
c.priority = priority
self.addConstraint(c)
return c
}
public func pinHeightLessThanOrEqual(height:CGFloat,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
let c = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .LessThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: height)
c.priority = priority
self.addConstraint(c)
return c
}
public func pinSize(size:CGSize,priority:UILayoutPriority=UILayoutPriorityRequired) -> PASizeConstraints{
let widthC = pinWidth(size.width,priority: priority)
let heightC = pinHeight(size.height,priority: priority)
return PASizeConstraints(width:widthC,height:heightC)
}
public func pinCenterY(offset:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal, toItem: superview!, attribute: .CenterY, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinCenterX(offset:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: superview!, attribute: .CenterX, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinInCenterX(offset:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: superview!, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinTrailingToCenterX(offset:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: superview!, attribute: .CenterX, multiplier: 1.0, constant: -offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinLeadingToCenterX(offset:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: superview!, attribute: .CenterX, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinAboveCenterY(offset:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: superview!, attribute: .CenterY, multiplier: 1.0, constant: -offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinBelowCenterY(offset:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
assertHasSuperview()
let c = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superview!, attribute: .CenterY, multiplier: 1.0, constant: offset)
c.priority = priority
superview?.addConstraint(c)
return c
}
public func pinCenter(xOffset :CGFloat = 0,yOffset:CGFloat = 0,priority:UILayoutPriority=UILayoutPriorityRequired) -> PACenterConstraints{
let centerX = pinCenterX(xOffset,priority: priority)
let centerY = pinCenterY(yOffset,priority: priority)
return PACenterConstraints(centerX: centerX, centerY: centerY)
}
public func pinAspectRatio(aspectRatio:CGFloat=0,priority:UILayoutPriority=UILayoutPriorityRequired) -> NSLayoutConstraint{
let c = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier:aspectRatio, constant: 0)
c.priority = priority
self.addConstraint(c)
return c
}
} | mit | a6d606faba3b625e2ff22f20a1f6099f | 46.013333 | 174 | 0.704975 | 4.914692 | false | false | false | false |
ben-ng/swift | validation-test/Reflection/reflect_multiple_types.swift | 4 | 13434 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_multiple_types
// RUN: %target-run %target-swift-reflection-test %t/reflect_multiple_types 2>&1 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
// FIXME: https://bugs.swift.org/browse/SR-2808
// XFAIL: resilient_stdlib
import SwiftReflectionTest
import Foundation
class TestClass {
var t00: Array<Int>
var t01: Bool
var t02: Character
var t03: Dictionary<Int, Int>
var t04: Double
var t05: Float
var t06: Int
var t07: Int16
var t08: Int32
var t09: Int64
var t10: Int8
var t11: NSArray
var t12: NSNumber
var t13: NSSet
var t14: NSString
var t15: Set<Int>
var t16: String
var t17: UInt
var t18: UInt16
var t19: UInt32
var t20: UInt64
var t21: UInt8
init(
t00: Array<Int>,
t01: Bool,
t02: Character,
t03: Dictionary<Int, Int>,
t04: Double,
t05: Float,
t06: Int,
t07: Int16,
t08: Int32,
t09: Int64,
t10: Int8,
t11: NSArray,
t12: NSNumber,
t13: NSSet,
t14: NSString,
t15: Set<Int>,
t16: String,
t17: UInt,
t18: UInt16,
t19: UInt32,
t20: UInt64,
t21: UInt8
) {
self.t00 = t00
self.t01 = t01
self.t02 = t02
self.t03 = t03
self.t04 = t04
self.t05 = t05
self.t06 = t06
self.t07 = t07
self.t08 = t08
self.t09 = t09
self.t10 = t10
self.t11 = t11
self.t12 = t12
self.t13 = t13
self.t14 = t14
self.t15 = t15
self.t16 = t16
self.t17 = t17
self.t18 = t18
self.t19 = t19
self.t20 = t20
self.t21 = t21
}
}
var obj = TestClass(
t00: [1, 2, 3],
t01: true,
t02: "A",
t03: [1: 3, 2: 2, 3: 1],
t04: 123.45,
t05: 123.45,
t06: 123,
t07: 123,
t08: 123,
t09: 123,
t10: 123,
t11: [1, 2, 3],
t12: 123,
t13: [1, 2, 3, 3, 2, 1],
t14: "Hello, NSString!",
t15: [1, 2, 3, 3, 2, 1],
t16: "Hello, Reflection!",
t17: 123,
t18: 123,
t19: 123,
t20: 123,
t21: 123
)
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_multiple_types.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=209 alignment=8 stride=216 num_extra_inhabitants=0
// CHECK-64: (field name=t00 offset=16
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=1
// (unstable implementation details omitted)
// CHECK-64: (field name=t01 offset=24
// CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254))))
// CHECK-64: (field name=t02 offset=32
// CHECK-64: (struct size=9 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64: (field name=_representation offset=0
// CHECK-64: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64: (field name=large offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646
// CHECK-64: (field name=_storage offset=0
// CHECK-64: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646
// CHECK-64: (field name=some offset=0
// CHECK-64: (reference kind=strong refcounting=native))))))
// CHECK-64: (field name=small offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))))))
// CHECK-64: (field name=t03 offset=48
// CHECK-64: (struct size=9 alignment=8 stride=16 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-64: (field name=t04 offset=64
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64: (field name=t05 offset=72
// CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-64: (field name=t06 offset=80
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64: (field name=t07 offset=88
// CHECK-64: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-64: (field name=t08 offset=92
// CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-64: (field name=t09 offset=96
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64: (field name=t10 offset=104
// CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-64: (field name=t11 offset=112
// CHECK-64: (reference kind=strong refcounting=unknown))
// CHECK-64: (field name=t12 offset=120
// CHECK-64: (reference kind=strong refcounting=unknown))
// CHECK-64: (field name=t13 offset=128
// CHECK-64: (reference kind=strong refcounting=unknown))
// CHECK-64: (field name=t14 offset=136
// CHECK-64: (reference kind=strong refcounting=unknown))
// CHECK-64: (field name=t15 offset=144
// CHECK-64: (struct size=9 alignment=8 stride=16 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-64: (field name=t16 offset=160
// CHECK-64: (struct size=24 alignment=8 stride=24 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-64: (field name=t17 offset=184
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64: (field name=t18 offset=192
// CHECK-64: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-64: (field name=t19 offset=196
// CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-64: (field name=t20 offset=200
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64: (field name=t21 offset=208
// CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_multiple_types.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=137 alignment=8 stride=144 num_extra_inhabitants=0
// CHECK-32: (field name=t00 offset=12
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=1
// (unstable implementation details omitted)
// CHECK-32: (field name=t01 offset=16
// CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254))))
// CHECK-32: (field name=t02 offset=24
// CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=_representation offset=0
// CHECK-32: (multi_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=large offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32: (field name=_storage offset=0
// CHECK-32: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32: (field name=some offset=0
// CHECK-32: (reference kind=strong refcounting=native))))))
// CHECK-32: (field name=small offset=0
// CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))))))
// CHECK-32: (field name=t03 offset=32
// CHECK-32: (struct size=5 alignment=4 stride=8 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-32: (field name=t04 offset=40
// CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-32: (field name=t05 offset=48
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32: (field name=t06 offset=52
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32: (field name=t07 offset=56
// CHECK-32: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-32: (field name=t08 offset=60
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32: (field name=t09 offset=64
// CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-32: (field name=t10 offset=72
// CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-32: (field name=t11 offset=76
// CHECK-32: (reference kind=strong refcounting=unknown))
// CHECK-32: (field name=t12 offset=80
// CHECK-32: (reference kind=strong refcounting=unknown))
// CHECK-32: (field name=t13 offset=84
// CHECK-32: (reference kind=strong refcounting=unknown))
// CHECK-32: (field name=t14 offset=88
// CHECK-32: (reference kind=strong refcounting=unknown))
// CHECK-32: (field name=t15 offset=92
// CHECK-32: (struct size=5 alignment=4 stride=8 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-32: (field name=t16 offset=100
// CHECK-32: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-32: (field name=t17 offset=112
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32: (field name=t18 offset=116
// CHECK-32: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-32: (field name=t19 offset=120
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32: (field name=t20 offset=128
// CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-32: (field name=t21 offset=136
// CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | db7083a88fbb58b724ca4b6f043688e2 | 43.78 | 133 | 0.6424 | 3.126367 | false | false | false | false |
julienbodet/wikipedia-ios | WMF Framework/SummaryExtensions.swift | 1 | 3138 | extension WMFArticle {
@objc public func update(withSummary summary: [String: Any]) {
if let originalImage = summary["originalimage"] as? [String: Any],
let source = originalImage["source"] as? String,
let width = originalImage["width"] as? Int,
let height = originalImage["height"] as? Int{
self.imageURLString = source
self.imageWidth = NSNumber(value: width)
self.imageHeight = NSNumber(value: height)
}
if let description = summary["description"] as? String {
self.wikidataDescription = description
}
if let displaytitle = summary["displaytitle"] as? String {
self.displayTitleHTML = displaytitle
}
if let extract = summary["extract"] as? String {
self.snippet = extract.wmf_summaryFromText()
}
if let coordinate = summary["coordinates"] as? [String: Any] ?? (summary["coordinates"] as? [[String: Any]])?.first,
let lat = coordinate["lat"] as? Double,
let lon = coordinate["lon"] as? Double {
self.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
}
}
}
extension NSManagedObjectContext {
public func wmf_createOrUpdateArticleSummmaries(withSummaryResponses summaryResponses: [String: [String: Any]]) throws -> [WMFArticle] {
let keys = summaryResponses.keys
guard keys.count > 0 else {
return []
}
var keysToCreate = Set(keys)
let articlesToUpdateFetchRequest = WMFArticle.fetchRequest()
articlesToUpdateFetchRequest.predicate = NSPredicate(format: "key IN %@", Array(keys))
var articles = try self.fetch(articlesToUpdateFetchRequest)
for articleToUpdate in articles {
guard let key = articleToUpdate.key,
let result = summaryResponses[key] else {
continue
}
articleToUpdate.update(withSummary: result)
keysToCreate.remove(key)
}
for key in keysToCreate {
guard let result = summaryResponses[key],
let article = self.createArticle(withKey: key) else {
continue
}
article.update(withSummary: result)
articles.append(article)
}
try self.save()
return articles
}
public func wmf_updateOrCreateArticleSummariesForArticles(withURLs articleURLs: [URL], completion: @escaping ([WMFArticle]) -> Void) {
Session.shared.fetchArticleSummaryResponsesForArticles(withURLs: articleURLs) { (summaryResponses) in
self.perform {
do {
let articles = try self.wmf_createOrUpdateArticleSummmaries(withSummaryResponses: summaryResponses)
completion(articles)
} catch let error {
DDLogError("Error fetching saved articles: \(error.localizedDescription)")
completion([])
}
}
}
}
}
| mit | 5a9f6555cac25b4e6dc1322c6e876cbe | 38.721519 | 140 | 0.586361 | 5.373288 | false | false | false | false |
fousa/trackkit | Example/Tests/Tests/TCX/TCXCourseSpecs.swift | 1 | 8938 | //
// TCXcourseSpec.swift
// TrackKit
//
// Created by Jelle Vandebeeck on 02/10/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import TrackKit
class TCXCourseSpec: QuickSpec {
override func spec() {
describe("courses") {
it("should not have courses") {
let content = "<TrainingCenterDatabase xmlns='http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'></TrainingCenterDatabase>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .tcx).parse()
expect(file.courses).to(beNil())
}
it("should not have courses without points") {
let content = "<TrainingCenterDatabase xmlns='http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'>"
+ "<Courses>"
+ "<Course>"
+ "<Track>"
+ "</Track>"
+ "</Course>"
+ "</Courses>"
+ "</TrainingCenterDatabase>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .tcx).parse()
expect(file.courses?.count).to(beNil())
}
describe("course data") {
var course: Course!
beforeEach {
let content = "<TrainingCenterDatabase xmlns='http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'>"
+ "<Courses>"
+ "<Course>"
+ "<Name>Jelle Vandebeeck</Name>"
+ "<Lap>"
+ "<TotalTimeSeconds>123</TotalTimeSeconds>"
+ "<DistanceMeters>456</DistanceMeters>"
+ "<BeginPosition>"
+ "<LatitudeDegrees>51.208845321089</LatitudeDegrees>"
+ "<LongitudeDegrees>4.394159177318</LongitudeDegrees>"
+ "</BeginPosition>"
+ "<EndPosition>"
+ "<LatitudeDegrees>51.208867281675</LatitudeDegrees>"
+ "<LongitudeDegrees>4.394087595865</LongitudeDegrees>"
+ "</EndPosition>"
+ "<Intensity>Active</Intensity>"
+ "</Lap>"
+ "<Track>"
+ "<Trackpoint>"
+ "<Position>"
+ "<LatitudeDegrees>51.208845321089</LatitudeDegrees>"
+ "<LongitudeDegrees>4.394159177318</LongitudeDegrees>"
+ "</Position>"
+ "</Trackpoint>"
+ "</Track>"
+ "</Course>"
+ "</Courses>"
+ "</TrainingCenterDatabase>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .tcx).parse()
course = file.courses?.first!
}
it("should have a name") {
expect(course.name) == "Jelle Vandebeeck"
}
it("should have a lap with total time in seconds") {
expect(course.totalTime) == 123
}
it("should have a lap with total distance in meters") {
expect(course.totalDistance) == 456
}
it("should have a lap with a begin position") {
expect(course.beginPosition?.latitude) == 51.208845321089
expect(course.beginPosition?.longitude) == 4.394159177318
}
it("should have a lap with an end position") {
expect(course.endPosition?.latitude) == 51.208867281675
expect(course.endPosition?.longitude) == 4.394087595865
}
it("should have a lap with an intensity") {
expect(course.intensity) == .active
}
}
describe("course track point data") {
var point: Point!
beforeEach {
let content = "<TrainingCenterDatabase xmlns='http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'>"
+ "<Courses>"
+ "<Course>"
+ "<Track>"
+ "<Trackpoint>"
+ "<Time>2016-03-10T10:05:12+02:00</Time>"
+ "<Position>"
+ "<LatitudeDegrees>51.208845321089</LatitudeDegrees>"
+ "<LongitudeDegrees>4.394159177318</LongitudeDegrees>"
+ "</Position>"
+ "<AltitudeMeters>100</AltitudeMeters>"
+ "<DistanceMeters>456</DistanceMeters>"
+ "</Trackpoint>"
+ "</Track>"
+ "</Course>"
+ "</Courses>"
+ "</TrainingCenterDatabase>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .tcx).parse()
point = file.courses?.first?.points?.first!
}
it("should have a track point time") {
expect(point.time?.description) == "2016-03-10 08:05:12 +0000"
}
it("should have a coordinate") {
expect(point.coordinate?.latitude) == 51.208845321089
expect(point.coordinate?.longitude) == 4.394159177318
}
it("should have a altitude in meters") {
expect(point.elevation) == 100
}
it("should have a distance in meters") {
expect(point.distance) == 456
}
}
describe("empty course point") {
var point: Point!
beforeEach {
let content = "<TrainingCenterDatabase xmlns='http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'>"
+ "<Courses>"
+ "<Course>"
+ "<Track>"
+ "<Trackpoint>"
+ "<Position>"
+ "<LatitudeDegrees>51.208845321089</LatitudeDegrees>"
+ "<LongitudeDegrees>4.394159177318</LongitudeDegrees>"
+ "</Position>"
+ "</Trackpoint>"
+ "</Track>"
+ "</Course>"
+ "</Courses>"
+ "</TrainingCenterDatabase>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .tcx).parse()
point = file.courses?.first?.points?.first!
}
it("should not have a track point time") {
expect(point.time?.description).to(beNil())
}
it("should not have a altitude in meters") {
expect(point.elevation).to(beNil())
}
it("should not have a distance in meters") {
expect(point.distance).to(beNil())
}
}
}
}
}
| mit | b37424dd9e05a67f1abfa6a92dc67d4d | 46.791444 | 148 | 0.371489 | 6.765329 | false | false | false | false |
khizkhiz/swift | benchmark/single-source/Walsh.swift | 2 | 2336 | //===--- Walsh.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Darwin
func IsPowerOfTwo(x: Int) -> Bool { return (x & (x - 1)) == 0 }
//Fast Walsh Hadamard Transform
func WalshTransform(data: inout [Double]) {
assert(IsPowerOfTwo(data.count), "Not a power of two")
var temp = [Double](repeating: 0, count: data.count)
var ret = WalshImpl(&data, &temp, 0, data.count)
for i in 0..<data.count {
data[i] = ret[i]
}
}
func Scale(data: inout [Double], _ scalar : Double) {
for i in 0..<data.count {
data[i] = data[i] * scalar
}
}
func InverseWalshTransform(data: inout [Double]) {
WalshTransform(&data)
Scale(&data, Double(1)/Double(data.count))
}
func WalshImpl(data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] {
if (size == 1) { return data }
let stride = size/2
for i in 0..<stride {
temp[start + i] = data[start + i + stride] + data[start + i]
temp[start + i + stride] = data[start + i] - data[start + i + stride]
}
WalshImpl(&temp, &data, start, stride)
return WalshImpl(&temp, &data, start + stride, stride)
}
func checkCorrectness() {
var In : [Double] = [1,0,1,0,0,1,1,0]
var Out : [Double] = [4,2,0,-2,0,2,0,2]
var data : [Double] = In
WalshTransform(&data)
var mid = data
InverseWalshTransform(&data)
for i in 0..<In.count {
// Check encode.
CheckResults(abs(data[i] - In[i]) < 0.0001, "Incorrect results in Walsh.")
// Check decode.
CheckResults(abs(mid[i] - Out[i]) < 0.0001, "Incorrect results in Walsh.")
}
}
@inline(never)
public func run_Walsh(N : Int) {
checkCorrectness()
// Generate data.
var data2 : [Double] = []
for i in 0..<1024 {
data2.append(Double(sin(Float(i))))
}
// Transform back and forth.
for _ in 1...10*N {
WalshTransform(&data2)
InverseWalshTransform(&data2)
}
}
| apache-2.0 | 97f46b5b4f6f6a1619e54948f324a373 | 27.144578 | 101 | 0.596747 | 3.322902 | false | false | false | false |
hackersatcambridge/hac-website | Sources/HaCWebsiteLib/Views/LandingPage/EventFeature.swift | 1 | 2234 | import Foundation
import HaCTML
/// A landing page feature for events
struct EventFeature: LandingFeature {
/// The span of time when the event is happening
let eventPeriod: DateInterval
/// The link to use in the lead up to the event (e.g. Facebook event link)
let eventLink: String
/// The link to use whilst the event is happening
let liveLink: String?
let hero: Nodeable
var dateBlock: Nodeable {
if currentlyHappening {
return El.Div[Attr.className => "EventFeature__date EventFeature__date--highlight"].containing(
"On now"
)
} else if isToday {
return El.Div[Attr.className => "EventFeature__date EventFeature__date--highlight"].containing(
"Today at " + DateUtils.individualTimeFormatter.string(from: eventPeriod.start)
)
} else {
return El.Div[Attr.className => "EventFeature__date"].containing(
DateUtils.individualDayFormatter.string(from: eventPeriod.start)
)
}
}
var expiryDate: Date {
/// Expire 2 hours after event finish
return eventPeriod.end + 2 * 60 * 60
}
/// Whether the event is currently in progress
var currentlyHappening: Bool {
let currentDate = Date()
let startPadding: TimeInterval = 15 * 60 // 15 mins
let endPadding: TimeInterval = 60 * 60 // 60 mins to allow for overrunning event
let paddedEventPeriod = DateInterval(
start: eventPeriod.start - startPadding,
end: eventPeriod.end + endPadding
)
return paddedEventPeriod.contains(currentDate)
}
/// Whether the event is on the same day
var isToday: Bool {
var calendar = NSCalendar.current
if let timeZone = TimeZone(identifier: "Europe/London") {
calendar.timeZone = timeZone
}
return calendar.isDateInToday(eventPeriod.start)
}
/// Returns a link to the most currently relevant information about this event
var currentLink: String {
guard let liveLink = liveLink else { return eventLink }
if currentlyHappening {
return liveLink
} else {
return eventLink
}
}
var node: Node {
return El.A[Attr.href => currentLink, Attr.className => "EventFeature EventFeature--text-light"].containing(
hero,
dateBlock
)
}
}
| mit | 00f4b322777fe7bf9aa88b20bb5b584a | 28.786667 | 112 | 0.681289 | 4.485944 | false | false | false | false |
dche/FlatCG | Tests/FlatCGTests/QuaternionTests.swift | 1 | 3244 |
import XCTest
import simd
import FlatUtil
import GLMath
@testable import FlatCG
class QuaternionTests: XCTestCase {
func testConstruction() {
let q = Quaternion(1, 2, 3, 4)
let v4 = vec4(1, 2, 3, 4).normalize
XCTAssert(q.imaginary ~== v4.xyz)
XCTAssert(q.real ~== v4.w)
}
// func testFromMatrix() {}
func testFromAxisAngle() {
let q = Quaternion(axis: Normal3D(vec3.y), angle: .half_pi)
let (axis, angle) = q.axisAngle
XCTAssert(axis ~== vec3(0, 1, 0))
XCTAssert(angle.isClose(to: .half_pi, tolerance: .epsilon * 10))
let v = q.apply(vec3(1, 0, 0))
XCTAssert(v ~== vec3(0, 0, -1))
XCTAssert(quickCheck(Gen<vec3>(), Gen<Float>(), size: 100) { axis, angle in
let q = Quaternion(axis: Normal3D(vector: axis), angle: angle * .tau)
let (ax, ag) = q.axisAngle
return ax.isClose(to: axis.normalize, tolerance: .epsilon * 1000) && ag.isClose(to: angle * .tau, tolerance: .epsilon * 1000)
})
}
func testFromVectors() {
XCTAssert(quickCheck(Gen<vec3>(), Gen<vec3>(), size: 100) { a, b in
let na = Normal<Point3D>(vector: a)
let nb = Normal<Point3D>(vector: b)
let q = Quaternion(fromDirection: na, to: nb)
return q.apply(na.vector).isClose(to: nb.vector, tolerance: .epsilon * 1000)
})
}
func testIendity() {
let i = Quaternion.identity
XCTAssert(quickCheck(Gen<vec3>(), size: 100) { v in
return i.apply(v) == v
})
}
func testInverse() {
XCTAssert(quickCheck(Gen<vec3>(), Gen<Float>(), size: 100) { i, r in
let q = Quaternion(imaginary: i, real: r)
return q.compose(q.inverse).isClose(to: .identity, tolerance: .epsilon * 100)
})
XCTAssert(quickCheck(Gen<vec3>(), Gen<Float>(), Gen<vec3>(), size: 100) { i, r, v in
let q = Quaternion(imaginary: i, real: r)
let iq = q.inverse
return iq.apply(q.apply(v)).isClose(to: v, tolerance: .epsilon * 1000)
})
}
func testCompose() {
XCTAssert(quickCheck(Gen<vec4>(), Gen<vec4>(), Gen<vec3>(), size: 100) { a, b, v in
let p = Quaternion(imaginary: a.xyz, real: a.w)
let q = Quaternion(imaginary: b.xyz, real: b.w)
return q.apply(p.apply(v)).isClose(to: (p.compose(q).apply(v)), tolerance: .epsilon * 1000)
})
}
func testToMatrix() {
XCTAssert(quickCheck(Gen<vec3>(), Gen<Float>(), Gen<vec3>(), size: 100) { i, r, v in
let q = Quaternion(imaginary: i, real: r)
let m = q.matrix
return q.apply(v).isClose(to: (m * vec4(v, 0)).xyz, tolerance: .epsilon * 1000)
})
}
func testApply() {
XCTAssert(quickCheck(Gen<vec4>(), Gen<vec3>(), size: 100) { qv, v in
let n = v.normalize
let q = Quaternion(imaginary: qv.xyz, real: qv.w)
let p = Quaternion(imaginary: n, real: 0)
let a = q.apply(n)
// q * p * q-1
let b = q.inverse.compose(p).compose(q)
return a.isClose(to: b.imaginary, tolerance: .epsilon * 1000)
})
}
}
| mit | e19beb0d60367e01b1b70ed8518debe1 | 34.648352 | 137 | 0.546856 | 3.465812 | false | true | false | false |
Estimote/iOS-SDK | LegacyExamples/Nearables/MonitoringExample-Swift/MonitoringExample-Swift/MonitoringDetailsViewController.swift | 1 | 2241 | //
// MonitoringDetailsViewController.swift
// MonitoringExample-Swift
//
// Created by Marcin Klimek on 09/01/15.
// Copyright (c) 2015 Estimote. All rights reserved.
//
import UIKit
class MonitoringDetailsViewController: UIViewController, ESTNearableManagerDelegate
{
var nearableManager:ESTNearableManager
var nearable:ESTNearable
@IBOutlet weak var enterSwitch: UISwitch!
@IBOutlet weak var exitSwitch: UISwitch!
required init?(coder aDecoder: NSCoder)
{
self.nearable = ESTNearable()
self.nearableManager = ESTNearableManager()
super.init(coder: aDecoder)
self.nearableManager.delegate = self;
}
override func viewDidLoad()
{
/**
* Setup title of the screen based on nearable type.
*/
self.title = NSString(format: "Nearable: %@", ESTNearableDefinitions.nameForType(nearable.type)) as String
/**
* Create Estimote Nearable Manager and start looking for
* the nearable device selected on previous screen and keept
* as self.nearable property.
*/
self.nearableManager.startMonitoringForIdentifier(self.nearable.identifier)
}
func nearableManager(manager: ESTNearableManager!, didEnterIdentifierRegion identifier: String!)
{
/**
* Verify if Enter switch is on, show local notification if ON.
*/
if (self.enterSwitch.on)
{
let notification:UILocalNotification = UILocalNotification();
notification.alertBody = "Enter region notification";
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
}
func nearableManager(manager: ESTNearableManager!, didExitIdentifierRegion identifier: String!)
{
/**
* Verify if Exit switch is on, show local notification if ON.
*/
if (self.exitSwitch.on)
{
let notification:UILocalNotification = UILocalNotification();
notification.alertBody = "Exit region notification";
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
}
}
| mit | 917be7cfdb979089ff137c3d96306d54 | 30.125 | 114 | 0.646586 | 5.387019 | false | false | false | false |
at-internet/atinternet-ios-objc-sdk | Tracker/TrackerTests/ParameterTests.swift | 1 | 6502 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// ParameterTests.swift
//
import UIKit
import XCTest
class ParameterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// On vérifie que qu'il est possible d'instancier plusieurs fois un Paramètre
func testMultiInstance() {
let page = ATParam("p", value: {"home"}, type: .String)
let xtCustom = ATParam("stc", value: {"{\"crash\":1}"}, type: .JSON)
XCTAssert(page !== xtCustom, "page et xtCustom ne doivent pas pointer vers la même référence")
}
// On vérifie les différents paramètres après une initialisation par défaut
func testParameterValuesAfterInit() {
let param = ATParam()
XCTAssertEqual(param.key, "", "le paramètre key doit être une chaine vide")
XCTAssert(param.value() == "", "le paramètre value doit être égal à ''")
XCTAssert(param.options == nil, "le paramètre options doit être nil")
}
// On vérifie que les paramètres key et value ont bien été affectés
func testParameterValuesAfterInitWithKeyAndValue() {
let param = ATParam("p", value: {"Home"}, type: .String)
XCTAssertEqual(param.key, "p", "le paramètre key doit être égal à p")
XCTAssert(param.value() == "Home", "le paramètre value doit être égal à Home")
}
// On vérifie que les paramètres key, value et relativeParameter ont bien été affectés
func testParameterValuesAfterInitWithKeyAndValueAtFirstPosition() {
let paramOptions = ATParamOption()
paramOptions.relativePosition = .First
let param = ATParam("p", value: {"Home"}, type: .String, options: paramOptions)
XCTAssertEqual(param.key, "p", "le paramètre key doit être égal à p")
XCTAssert(param.value() == "Home", "le paramètre value doit être égale à Home")
XCTAssert(param.options?.relativePosition == .First, "l'option relativePosition doit être égale à first")
XCTAssert(param.options?.relativeParameterKey == "", "l'option relativeParameter doit être égale à ''")
}
// On vérifie que les paramètres key, value et relativeParameter ont bien été affectés
// On vérifie que si le paramètre a une position last, le relativeParameter est nil
func testParameterValuesAfterInitWithKeyAndValueAtLastPosition() {
let paramOptions = ATParamOption()
paramOptions.relativePosition = .Last
let param = ATParam("p", value: {"Home"}, type: .String, options: paramOptions)
XCTAssertEqual(param.key, "p", "le paramètre key doit être égal à p")
XCTAssert(param.value() == "Home", "le paramètre value doit être égale à Home")
XCTAssert(param.options?.relativePosition == .Last, "l'option relativePosition doit être égale à last")
XCTAssert(param.options?.relativeParameterKey == "", "l'option relativeParameter doit être égale à ''")
}
// On vérifie que les paramètres key, value et relativeParameter ont bien été affectés
func testParameterValuesAfterInitWithKeyAndValueBeforeReferrerParameter() {
let paramOptions = ATParamOption()
paramOptions.relativePosition = .Before
paramOptions.relativeParameterKey = "ref"
let param = ATParam("p", value: {"Home"}, type: .String, options: paramOptions)
XCTAssertEqual(param.key, "p", "le paramètre key doit être égal à p")
XCTAssert(param.value() == "Home", "le paramètre value doit être égale à Home")
XCTAssert(param.options?.relativePosition == .Before, "l'option relativePosition doit être égale à before")
XCTAssert(param.options?.relativeParameterKey == "ref", "l'option relativeParameter doit être égale à 'ref'")
}
// On vérifie que les paramètres key, value et relativeParameter ont bien été affectés
func testParameterValuesAfterInitWithKeyAndValueAfterXTCustomParameter() {
let paramOptions = ATParamOption()
paramOptions.relativePosition = .After
paramOptions.relativeParameterKey = "stc"
let param = ATParam("p", value: {"Home"}, type: .String, options: paramOptions)
XCTAssertEqual(param.key, "p", "le paramètre key doit être égal à p")
XCTAssert(param.value() == "Home", "le paramètre value doit être égale à Home")
XCTAssert(param.options?.relativePosition == .After, "l'option relativePosition doit être égale à after")
XCTAssert(param.options?.relativeParameterKey == "stc", "l'option relativeParameter doit être égale à 'stc'")
}
// On vérifie que la liste des paramètres en lecture seule contient les 10 clés à ne pas surcharger (sujet à modification)
func testReadOnlyParametersKeys() {
XCTAssertEqual(11, ATReadOnlyParam.list().count, "Il doit y avoir 10 clés de paramètres en lecture seule")
}
}
| mit | 6780bfe324c1eaa0a2193a7114e3ccc0 | 47.363636 | 141 | 0.697525 | 4.746468 | false | true | false | false |
dnseitz/YAPI | YAPI/YAPI/V2/V2_YelpRegionDataModels.swift | 1 | 1296 | //
// YelpRegionDataModels.swift
// YAPI
//
// Created by Daniel Seitz on 9/11/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import Foundation
import CoreLocation
public struct YelpRegion {
/// Span of suggested map bounds
let span: YelpRegionSpan?
/// Center position of map bounds
let center: YelpRegionCenter
init(withDict dict: [String: AnyObject]) {
if let span = dict["span"] as? [String: AnyObject] {
self.span = YelpRegionSpan(withDict: span)
}
else {
self.span = nil
}
self.center = YelpRegionCenter(withDict: dict["center"] as! [String: AnyObject])
}
}
struct YelpRegionSpan {
/// Latitude width of map bounds
let latitudeDelta: Double
/// Longitude height of map bounds
let longitudeDelta: Double
init(withDict dict: [String: AnyObject]) {
self.latitudeDelta = dict["latitude_delta"] as! Double
self.longitudeDelta = dict["longitude_delta"] as! Double
}
}
struct YelpRegionCenter {
/// Latitude position of map bounds center
let latitude: Double
/// Longitude position of map bounds center
let longitude: Double
init(withDict dict: [String: AnyObject]) {
self.latitude = dict["latitude"] as! Double
self.longitude = dict["longitude"] as! Double
}
}
| mit | 8449c47aa6ad10c9463633c368053d26 | 21.719298 | 84 | 0.676448 | 4.13738 | false | false | false | false |
SwiftArchitect/SO-32342486 | SO-32342486/ViewController.swift | 1 | 4779 | //
// ViewController.swift
// SO-32342486
//
// Copyright © 2017, 2018 Xavier Schott
// 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 AVFoundation
class ViewController: UIViewController {
var audioRecorder:AVAudioRecorder!
var audioPlayer:AVAudioPlayer!
var progressLink : CADisplayLink? = nil
@IBOutlet weak var recordingActivity: UIActivityIndicatorView!
@IBOutlet weak var playProgress: UIProgressView!
let recordSettings = [AVSampleRateKey : NSNumber(value: Float(44100.0)),
AVFormatIDKey : NSNumber(value: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey : NSNumber(value: Int32(1)),
AVEncoderAudioQualityKey : NSNumber(value: Int32(AVAudioQuality.medium.rawValue))]
override func viewDidLoad() {
super.viewDidLoad()
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioRecorder = AVAudioRecorder(url: directoryURL()!, settings: recordSettings)
audioRecorder.prepareToRecord()
} catch {}
}
@IBAction func doRecordAction(_ sender: AnyObject) {
playProgress.setProgress(0, animated: false)
recordingActivity.startAnimating()
recordingActivity.isHidden = false
if !audioRecorder.isRecording {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true)
audioRecorder.record()
} catch {}
}
}
@IBAction func doPlayAction(_ sender: AnyObject) {
if !audioRecorder.isRecording {
do {
playProgress.setProgress(0, animated: false)
try audioPlayer = AVAudioPlayer(contentsOf: audioRecorder.url)
progressLink = CADisplayLink(target: self,
selector: #selector(ViewController.playerProgress))
if let progressLink = progressLink {
progressLink.preferredFramesPerSecond = 2
progressLink.add(to: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
}
audioPlayer.delegate = self
audioPlayer.play()
} catch {}
}
}
@IBAction func doStopAction(_ sender: AnyObject) {
audioRecorder.stop()
recordingActivity.stopAnimating()
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false)
} catch {}
}
@objc func playerProgress() {
var progress = Float(0)
if let audioPlayer = audioPlayer {
progress = ((audioPlayer.duration > 0)
? Float(audioPlayer.currentTime/audioPlayer.duration)
: 0)
}
playProgress.setProgress(progress, animated: true)
}
func directoryURL() -> URL? {
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = urls[0] as URL
let soundURL = documentDirectory.appendingPathComponent("SO-32342486.m4a")
return soundURL
}
}
extension ViewController : AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if let progressLink = progressLink {
progressLink.invalidate()
}
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
if let progressLink = progressLink {
progressLink.invalidate()
}
}
}
| mit | 94ff3c85e429d9f84bd31ee037e94535 | 36.622047 | 108 | 0.651737 | 5.374578 | false | false | false | false |
csnu17/My-Blognone-apps | myblognone/Common/Extensions/MyDateExtension.swift | 1 | 1087 | //
// MyDateExtension.swift
// myblognone
//
// Created by Kittisak Phetrungnapha on 12/22/2559 BE.
// Copyright © 2559 Kittisak Phetrungnapha. All rights reserved.
//
import Foundation
extension Date {
func getStringWith(format: String) -> String {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 25200)
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: self)
}
static func getNewDateTimeString(inputStr: String, inputFormat: String, outputFormat: String) -> String? {
// input
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 25200)
formatter.dateFormat = inputFormat
formatter.locale = Locale(identifier: "en_US_POSIX")
guard let inputDate = formatter.date(from: inputStr) else {
return nil
}
// output
formatter.dateFormat = outputFormat
return formatter.string(from: inputDate)
}
}
| mit | 51d1e3ea956d81b962dfccda2d4399f6 | 30.028571 | 110 | 0.649171 | 4.721739 | false | false | false | false |
BugMomon/weibo | NiceWB/NiceWB/Classes/Main(主要)/AccessToken/UserAccount.swift | 1 | 2007 | //
// UserAccount.swift
// NiceWB
//
// Created by HongWei on 2017/3/31.
// Copyright © 2017年 HongWei. All rights reserved.
//
import UIKit
class UserAccount: NSObject ,NSCoding{
//授权
var access_token :String?
//用户ID
var uid : String?
//过期剩余秒数
var expires_in : TimeInterval = 0.0{
didSet{
expires_date = NSDate.init(timeIntervalSinceNow: expires_in + (8 * 60 * 60))//在后面加上东八区的时间
}
}
//过期时间
var expires_date : NSDate?
//用户昵称
var screen_name : String?
//用户头像地址
var avatar_large : String?
// override init() {
// super.init()
// }
init(dict : [String : AnyObject]){
super.init()
setValuesForKeys(dict)
}
//重写这个方法是为了防止模型转换时缺少的key
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
//重写discripsion属性
override var description: String{
return dictionaryWithValues(forKeys: ["access_token","uid","expires_date","screen_name","avatar_large"]).description
}
// MARK:- 归档解档
//解档方法
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObject(forKey: "access_token") as? String
expires_date = aDecoder.decodeObject(forKey: "expires_date") as? NSDate
screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
uid = aDecoder.decodeObject(forKey: "uid") as? String
}
//归档方法
func encode(with aCoder: NSCoder) {
aCoder.encode(access_token, forKey: "access_token")
aCoder.encode(uid, forKey: "uid")
aCoder.encode(expires_date, forKey: "expires_date")
aCoder.encode(screen_name, forKey: "screen_name")
aCoder.encode(avatar_large, forKey: "avatar_large")
}
}
| apache-2.0 | aec297886b47f7673564f72f55646839 | 25.253521 | 124 | 0.612661 | 3.835391 | false | false | false | false |
multinerd/Mia | Mia/Extensions/UITableViewCell/UITableViewCell+.swift | 1 | 865 | import UIKit
public extension UITableViewCell {
/// Sets the cells `backgroundColor` and `contentView.backgroundColor` properties
public var cBackgroundColor: UIColor {
get {
return backgroundColor!
}
set {
backgroundColor = newValue
contentView.backgroundColor = newValue
}
}
public func resetSeparatorInset() {
if self.responds(to: #selector(setter:UITableViewCell.separatorInset)) {
self.separatorInset = .zero
}
if self.responds(to: #selector(setter:UIView.preservesSuperviewLayoutMargins)) {
self.preservesSuperviewLayoutMargins = false
}
if self.responds(to: #selector(setter:UIView.layoutMargins)) {
self.layoutMargins = .zero
}
}
}
| mit | 4db641e523c2ee69a5d35fa2cbd55f04 | 22.378378 | 88 | 0.589595 | 5.805369 | false | false | false | false |
x331275955/- | xiong-练习微博(视频)/xiong-练习微博(视频)/Models/NewUserCollectionViewController.swift | 1 | 6143 | //
// NewUserCollectionViewController.swift
// xiong-练习微博(视频)
//
// Created by 王晨阳 on 15/9/20.
// Copyright © 2015年 IOS. All rights reserved.
//
import UIKit
private let imageCount = 4
private let reuseIdentifier = "Cell"
class NewUserCollectionViewController: UICollectionViewController {
// 手动弄一个layout
private let layout = XCollectionFlowLayout()
init() {
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
// 调用super是为了 用sb开发
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// 使用自定义Cell
self.collectionView!.registerClass(NewUserCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
// MARK:- 数据源方法
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageCount
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewUserCell
cell.imageIndex = indexPath.item
return cell
}
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
// 获取当前显示的 indexPath
let path = collectionView.indexPathsForVisibleItems().last!
// 判断是否是末尾的 indexPath
if path.item == imageCount - 1 {
// 播放动画
let cell = collectionView.cellForItemAtIndexPath(path) as! NewUserCell
cell.startButtonAnim()
}
}
}
// 新特性的cell
class NewUserCell: UICollectionViewCell {
// 点击StartButton事件
func clickStartButton(){
// 发送通知
NSNotificationCenter.defaultCenter().postNotificationName(XRootViewControllerSwitchNotification, object: true)
}
// 图像索引 -- 私有属性在同一个文件里是可以访问的.
private var imageIndex: Int = 0{
didSet{
iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
startButton.hidden = true
}
}
// 设置startButton的动画
private func startButtonAnim(){
startButton.hidden = false
startButton.transform = CGAffineTransformMakeScale(0, 0)
UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
// 恢复默认形变
self.startButton.transform = CGAffineTransformIdentity
}) { (_) -> Void in
}
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareUI()
}
private func prepareUI(){
// 添加控件 -- 建议都加载到 contentView 上
contentView.addSubview(iconView)
contentView.addSubview(startButton)
// 自动布局
iconView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subView": iconView]))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subView": iconView]))
startButton.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
}
// MARK: - 懒加载控件
private lazy var iconView = UIImageView()
private lazy var startButton: UIButton = {
let button = UIButton()
button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
button.setTitle("开始体验", forState: UIControlState.Normal)
button.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
// 根据背景图片自动调整大小
button.sizeToFit()
return button
}()
}
// 顺序:1.数据源获取cell数量. 2.获取layout 3. 数据源方法 去布局cell
// 自定义流水布局
private class XCollectionFlowLayout: UICollectionViewFlowLayout{
// 设置各种属性!!!!
private override func prepareLayout() {
// 设置图片大小
itemSize = collectionView!.bounds.size
// 设置间距
minimumInteritemSpacing = 0
minimumLineSpacing = 0
// 设置滚动方向
scrollDirection = UICollectionViewScrollDirection.Horizontal
// 设置分页
collectionView?.pagingEnabled = true
// 设置滚动条
collectionView?.showsHorizontalScrollIndicator = false
// 设置弹性
collectionView?.bounces = false
}
}
| mit | b2b3b37014a3dcb10776d6a5923d64ee | 31.704545 | 235 | 0.648019 | 5.502868 | false | false | false | false |
sclark01/Swifty3Mesh | Meshy/Meshy/AppDelegate.swift | 1 | 4448 | import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Meshy")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 5ac815a4958fb111653aea0a8673b26a | 51.329412 | 285 | 0.686601 | 6.018945 | false | false | false | false |
xivol/MCS-V3-Mobile | assignments/task1/BattleShip.playground/Contents.swift | 1 | 1591 | //: __Battleship__ — (also Battleships or Sea Battle) is a guessing game for two players. It is played on ruled grids (paper or board) on which the players' fleets of ships (including battleships) are marked. The locations of the fleet are concealed from the other player. Players alternate turns calling "shots" at the other player's ships, and the objective of the game is to destroy the opposing player's fleet. Battleship is known worldwide as a pencil and paper game which dates from World War I. It was published by various companies as a pad-and-pencil game in the 1930s, and was released as a plastic board game by Milton Bradley in 1967. The game has spawned electronic versions, video games, smart device apps and a film. __NOTE__ : This version of BattleShip is implemented based on X and Y axis coordinates in range 0-9.
//:
//: 
var ship11: CombatShip = CombatShip([(0,0), (0,1), (0,2)])
var ship12: CombatShip = CombatShip([(5,5), (4,5), (3,5), (2,5), (1,5)])
var ship13: CombatShip = CombatShip([(7,3), (7,4), (7,5)])
var jackSparrow: BattleShipPlayer =
BattleShipPlayer(name: "Jack Sparrow", [ship11, ship12, ship13])
var ship21: CombatShip = CombatShip([(9, 9), (9,8), (9,7)])
var ship22: CombatShip = CombatShip([(5,5), (4,5), (3,5)])
var ship23: CombatShip = CombatShip([(7,5), (7,6), (7,7), (7,8)])
var davyJones: BattleShipPlayer =
BattleShipPlayer(name: "Davy Jones", [ship21, ship22, ship23])
var game = BattleShip()
game.delegate = BattleShipTracker()
game.join(player: jackSparrow)
game.join(player: davyJones)
game.play()
| mit | eb9fe2f01cb9f8035c8d1c902dcaa458 | 62.56 | 833 | 0.721208 | 3.395299 | false | false | false | false |
cuzv/TinyCoordinator | Sample/Model.swift | 1 | 2656 | //
// Model.swift
// Copyright (c) 2016 Red Rain (https://github.com/cuzv).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import TinyCoordinator
class CellDataItem: NSObject {
var name: String = ""
var pic: String = ""
init(name: String, pic: String) {
self.name = name
self.pic = pic
super.init()
}
override var description: String {
return debugDescription
}
override var debugDescription: String {
var output: [String] = []
output.append("-------------------------------------------------")
output.append("name: \(name)")
output.append("-------------------------------------------------")
return output.joined(separator: "\n")
}
}
func ==(lhs: CellDataItem, rhs: CellDataItem) -> Bool {
return lhs.name == rhs.name && lhs.pic == rhs.pic
}
class CellDataItem2: NSObject {
var name: String = ""
var pic: String = ""
init(name: String, pic: String) {
self.name = name
self.pic = pic
super.init()
}
override var description: String {
return debugDescription
}
override var debugDescription: String {
var output: [String] = []
output.append("-------------------------------------------------")
output.append("name: \(name)")
output.append("-------------------------------------------------")
return output.joined(separator: "\n")
}
}
func ==(lhs: CellDataItem2, rhs: CellDataItem2) -> Bool {
return lhs.name == rhs.name && lhs.pic == rhs.pic
}
| mit | 61c5a1abdec4e375121a47ec5d1e949f | 32.2 | 81 | 0.601657 | 4.494078 | false | false | false | false |
morbrian/udacity-nano-onthemap | OnTheMap/StudentLocationsCollectionViewController.swift | 1 | 3082 | //
// StudentLocationsCollectionViewController.swift
// OnTheMap
//
// Created by Brian Moriarty on 5/31/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import UIKit
// StudentLocationsCollectionViewController
// Displays all student locations in a collection view
class StudentLocationsCollectionViewController: OnTheMapBaseViewController {
@IBOutlet weak var collectionView: UICollectionView!
var pinImage: UIImage!
// MARK: ViewController Lifecycle
override func viewDidLoad() {
pinImage = UIImage(named: "Pin")
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
collectionView.reloadData()
}
// MARK: Overrides from super class
override func updateDisplayFromModel() {
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
}
}
// MARK: - UICollectionViewDelegate
extension StudentLocationsCollectionViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let item = dataManager?.studentLocationAtIndex(indexPath.item),
urlString = item.mediaUrl {
self.sendToUrlString(urlString)
}
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let currentCount = dataManager?.studentLocationCount
where indexPath.item == currentCount - PreFetchTrigger {
if preFetchEnabled {
fetchNextPage()
}
}
}
}
// MARK: - UICollectionViewDataSource
extension StudentLocationsCollectionViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataManager?.studentLocationCount ?? 0
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let studentLocationData = dataManager?.studentLocationAtIndex(indexPath.item)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.StudentLocationCollectionItem, forIndexPath: indexPath) as! StudentLocationCollectionViewCell
cell.firstNameLabel?.text = studentLocationData?.firstname
cell.lastNameLabel?.text = studentLocationData?.lastname
cell.imageView?.image = pinImage
return cell
}
}
// MARK: - StudentLocationCollectionViewCell
// StudentLocationCollectionViewCell
// represents cell of a collection view containing a single student location item.
class StudentLocationCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var firstNameLabel: UILabel?
@IBOutlet weak var lastNameLabel: UILabel?
}
| mit | f5643808557f31eebe9714aaffe80e4b | 32.5 | 180 | 0.711226 | 6.019531 | false | false | false | false |
lemberg/connfa-ios | Connfa/Common/Extensions/UIApplication+topViewController.swift | 1 | 839 | //
// UIApplication+topViewController.swift
// Connfa
//
// Created by Marian Fedyk on 9/6/18.
// Copyright © 2018 Lemberg Solution. All rights reserved.
//
import UIKit
extension UIApplication {
static func topViewController(controller: UIViewController? = shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
| apache-2.0 | 0e8253fec2b58f60b38c1beb180ab6f3 | 31.230769 | 124 | 0.742243 | 5.303797 | false | false | false | false |
stephentyrone/swift | test/IRGen/objc_bridge.swift | 3 | 11038 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = private constant { i32, i32, [17 x { i8*, i8*, i8* }] } {
// CHECK: i32 24,
// CHECK: i32 17,
// CHECK: [17 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strRealPropSSvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strRealPropSSvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strFakePropSSvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strFakePropSSvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC9strResultSSyFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC6strArg1sySS_tFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCACycfcTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfDTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0),
// CHECK: i8* bitcast (void (%3*, i8*, %4*)* @"$s11objc_bridge3BasC9acceptSetyyShyACGFTo" to i8*)
// CHECK: }
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @{{.*}}, i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfETo" to i8*)
// CHECK: }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = private constant { i32, i32, [5 x { i8*, i8* }] } {
// CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [8 x i8] c"T@?,N,C\00"
// CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = private constant {{.*}} [[OBJC_BLOCK_PROPERTY]]
func getDescription(_ o: NSObject) -> String {
return o.description
}
func getUppercaseString(_ s: NSString) -> String {
return s.uppercase()
}
// @interface Foo -(void) setFoo: (NSString*)s; @end
func setFoo(_ f: Foo, s: String) {
f.setFoo(s)
}
// NSString *bar(int);
func callBar() -> String {
return bar(0)
}
// void setBar(NSString *s);
func callSetBar(_ s: String) {
setBar(s)
}
var NSS : NSString = NSString()
// -- NSString methods don't convert 'self'
extension NSString {
// CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE11nsstrResultAByFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
@objc func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE8nsstrArg1syAB_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc func nsstrArg(s s: NSString) { }
}
class Bas : NSObject {
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strRealPropSSvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC11strRealPropSSvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var strRealProp : String
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strFakePropSSvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC11strFakePropSSvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var strFakeProp : String {
get {
return ""
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var nsstrRealProp : NSString
// CHECK: define hidden swiftcc %TSo8NSStringC* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvg"(%T11objc_bridge3BasC* swiftself %0) {{.*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC9strResultSSyFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
@objc func strResult() -> String { return "" }
// CHECK: define internal void @"$s11objc_bridge3BasC6strArg1sySS_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc func strArg(s s: String) { }
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
@objc func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc func nsstrArg(s s: NSString) { }
override init() {
strRealProp = String()
nsstrRealProp = NSString()
super.init()
}
deinit { var x = 10 }
override var hash: Int { return 0 }
@objc func acceptSet(_ set: Set<Bas>) { }
}
func ==(lhs: Bas, rhs: Bas) -> Bool { return true }
class OptionalBlockProperty: NSObject {
@objc var x: (([AnyObject]) -> [AnyObject])?
}
| apache-2.0 | 27461a7dbe5e835d46a11db4089fa64d | 53.374384 | 147 | 0.580902 | 3.030752 | false | false | false | false |
stephentyrone/swift | test/IRGen/prespecialized-metadata/class-inmodule-2argument-1super-2argument-run.swift | 1 | 3513 | // RUN: %target-run-simple-swift(%S/Inputs/main.swift %S/Inputs/consume-logging-metadata-value.swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// Executing on the simulator within __abort_with_payload with "No ABI plugin located for triple x86_64h-apple-ios -- shared libraries will not be registered!"
// UNSUPPORTED: CPU=x86_64 && OS=ios
// UNSUPPORTED: CPU=x86_64 && OS=tvos
// UNSUPPORTED: CPU=x86_64 && OS=watchos
// UNSUPPORTED: CPU=i386 && OS=watchos
// UNSUPPORTED: use_os_stdlib
class WeakMutableInstanceMethodBox<Input, Output> {
let line: UInt
init(line: UInt = #line) {
self.line = line
}
private var work: ((Input) -> Output?)?
func bind<T: AnyObject>(to object: T, method: @escaping (T) -> (Input) -> Output?) {
self.work = { [weak object] input in
guard let object = object else { return nil }
return method(object)(input)
}
}
func call(_ input: Input) -> Output? {
return work?(input)
}
}
extension WeakMutableInstanceMethodBox : CustomStringConvertible {
var description: String {
"\(type(of: self)) @ \(line)"
}
}
class MyWeakMutableInstanceMethodBox<Input, Output> : WeakMutableInstanceMethodBox<Input, Output> {
override init(line: UInt = #line) {
super.init(line: line)
}
}
@inline(never)
func consume<Input, Output>(base: WeakMutableInstanceMethodBox<Input, Output>) {
consume(base)
}
func consume<Input, Output>(derived: MyWeakMutableInstanceMethodBox<Input, Output>) {
consume(derived)
}
func doit() {
// CHECK: [[SUPERCLASS_METADATA_INT_BOOL_ADDRESS:[0-9a-f]+]] WeakMutableInstanceMethodBox<Int, Bool> @ 63
consume(WeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUPERCLASS_METADATA_INT_BOOL_ADDRESS]] WeakMutableInstanceMethodBox<Int, Bool> @ 65
consume(base: WeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUPERCLASS_METADATA_DOUBLE_FLOAT_ADDRESS:[0-9a-f]+]] WeakMutableInstanceMethodBox<Double, Float> @ 67
consume(WeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUPERCLASS_METADATA_DOUBLE_FLOAT_ADDRESS]] WeakMutableInstanceMethodBox<Double, Float> @ 69
consume(base: WeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUBCLASS_METADATA_INT_BOOL_ADDRESS:[0-9a-f]+]] MyWeakMutableInstanceMethodBox<Int, Bool> @ 72
consume(MyWeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUPERCLASS_METADATA_INT_BOOL_ADDRESS]] MyWeakMutableInstanceMethodBox<Int, Bool> @ 74
consume(base: MyWeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUBCLASS_METADATA_INT_BOOL_ADDRESS]] MyWeakMutableInstanceMethodBox<Int, Bool> @ 76
consume(derived: MyWeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUBCLASS_METADATA_DOUBLE_FLOAT_ADDRESS:[0-9a-f]+]] MyWeakMutableInstanceMethodBox<Double, Float>
consume(MyWeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUPERCLASS_METADATA_DOUBLE_FLOAT_ADDRESS]] MyWeakMutableInstanceMethodBox<Double, Float>
consume(base: MyWeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUBCLASS_METADATA_DOUBLE_FLOAT_ADDRESS]] MyWeakMutableInstanceMethodBox<Double, Float>
consume(derived: MyWeakMutableInstanceMethodBox<Double, Float>())
}
| apache-2.0 | c0693093112c21819801c162a827ac36 | 40.329412 | 190 | 0.710219 | 4.128085 | false | false | false | false |
glorybird/KeepReading2 | kr/Pods/EasyAnimation/EasyAnimation/RBBSpringAnimation/RBBBlockBasedArray.swift | 20 | 1079 | //
// RBBSpringAnimation.h
// RBBAnimation
//
// Created by Robert Böhnke on 10/14/13.
// Copyright (c) 2013 Robert Böhnke. All rights reserved.
//
//
// RBBBlockBasedArray.swift
//
// Swift intepretation of the Objective-C original by Marin Todorov
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import Foundation
typealias RBBBlockBasedArrayBlock = (Int) -> AnyObject
class RBBBlockBasedArray: NSArray {
private var countBlockBased: Int = 0
private var block: RBBBlockBasedArrayBlock? = nil
//can't do custom init because it's declared in an NSArray extension originally
//and can't override it from here in Swift 1.2; need to do initialization from an ordinary method
func setCount(count: Int, block: RBBBlockBasedArrayBlock) {
self.countBlockBased = count;
self.block = block
}
override var count: Int {
return countBlockBased
}
//will crash if block is not set
override func objectAtIndex(index: Int) -> AnyObject {
return block!(index)
}
}
| apache-2.0 | 9834694fb85f21750ba87cf805424012 | 24.642857 | 101 | 0.679666 | 4.207031 | false | false | false | false |
superk589/CGSSGuide | DereGuide/Common/CGSSGlobal.swift | 2 | 4119 | //
// CGSSGlobal.swift
// DereGuide
//
// Created by zzk on 16/6/28.
// Copyright © 2016 zzk. All rights reserved.
//
import UIKit
import Reachability
struct Config {
static let iAPRemoveADProductIDs: Set<String> = ["dereguide_small_tips", "dereguide_medium_tips"]
static let bundleID = "com.zzk.cgssguide"
static let unityVersion = "2018.2.20f1"
static let cloudKitDebug = true
static let maxNumberOfStoredUnits = 100
static let maxCharactersOfMessage = 200
#if DEBUG
static let cloudKitFetchLimits = 5
#else
static let cloudKitFetchLimits = 20
#endif
static let appName = NSLocalizedString("DereGuide", comment: "")
static let maximumSinglePotential = 10
static let maximumTotalPotential = 35
// max = 15928 + 500 + 500 + 500
// ceil(0.5 × max × 1.3) * 10
static let maximumSupportAppeal = 113290
}
struct NotificationCategory {
static let birthday = "Birthday"
}
struct Path {
static let cache = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
static let document = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
static let library = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
static let home = NSHomeDirectory()
// include the last "/"
static let temporary = NSTemporaryDirectory()
}
struct Screen {
static var width: CGFloat {
return UIScreen.main.bounds.width
}
static var height: CGFloat {
return UIScreen.main.bounds.height
}
// 当前屏幕1坐标的像素点数量
static var scale: CGFloat {
return UIScreen.main.scale
}
// FIXME: do not use these two, because in multi-task mode shortSide or longSide does not make sense.
static let shortSide = min(width, height)
static let longSide = max(width, height)
}
public class CGSSGlobal {
// 当前屏幕的宽度和高度常量
public static let width = UIScreen.main.bounds.width
public static let height = UIScreen.main.bounds.height
// 当前屏幕1坐标的像素点数量
public static let scale = UIScreen.main.scale
// 用于GridView的字体
public static let numberFont = UIFont.init(name: "menlo", size: 14)
public static let alphabetFont = UIFont.systemFont(ofSize: 14)
public static let spreadImageWidth: CGFloat = 1280
public static let spreadImageHeight: CGFloat = 824
static let rarityToStirng: [String] = ["", "N", "N+", "R", "R+", "SR", "SR+", "SSR", "SSR+"]
static let appid = "1131934691"
// 时区转换
static func getDateFrom(oldDate: NSDate, timeZone: NSTimeZone) -> NSDate {
let inv = timeZone.secondsFromGMT(for: oldDate as Date)
let timeInv = TimeInterval(inv)
let newDate = oldDate.addingTimeInterval(timeInv)
return newDate
}
static func isWifi() -> Bool {
if let reachability = Reachability() {
if reachability.connection == .wifi {
return true
}
}
return false
}
static func isMobileNet() -> Bool {
if let reachability = Reachability() {
if reachability.connection == .cellular {
return true
}
}
return false
}
static var languageType: LanguageType {
if let code = Locale.preferredLanguages.first {
return LanguageType(identifier: code)
} else {
return .en
}
}
}
enum LanguageType {
case en
case cn
case tw
case ja
case other
init(identifier: String) {
switch identifier {
case let x where x.hasPrefix("en"):
self = .en
case let x where x.hasPrefix("zh-Hans"):
self = .cn
case let x where x.hasPrefix("zh-Hant"):
self = .tw
case let x where x.hasPrefix("ja"):
self = .ja
default:
self = .other
}
}
}
| mit | 7693913eb7dd6f0447990e93d29c400d | 26.387755 | 111 | 0.620964 | 4.419319 | false | false | false | false |
iOS-Swift-Developers/Swift | 基础语法/类/main.swift | 1 | 1054 | //
// main.swift
// 类
//
// Created by 韩俊强 on 2017/6/12.
// Copyright © 2017年 HaRi. All rights reserved.
//
import Foundation
/*
类的基本定义
Swift中的结构体和类非常相似, 但是又有不同之处
类是具有相同属性和方法的抽象
格式:
class 类名称 {
类的属性和方法
}
*/
class Rect {
var width:Double = 0.0
var height:Double = 0.0
func show() -> Void {
print("width = \(width) height = \(height)")
}
}
// 类没有逐一构造器
//var r1 = Rect(width: 10.0, height: 10.0)
var r1 = Rect()
r1.show()
var r2 = r1
r2.show()
// 类是引用类型, 结构体之间的赋值其实是将r2指向了r1的内存存储空间, 所以他们是两个指向相同的一块存储空间, 修改其中一个会影响到另外一个
r1.width = 100.0
r1.show()
r2.show()
/*
恒等运算符, 用于判断是否是同一个实例, 也就是是否指向同一块存储空间
有: === !== 两种类型
*/
var r3 = Rect()
if r1 === r3
{
print("指向同一块存储空间")
}
| mit | 98cf19e6fc53750af535633a572185f4 | 13.019608 | 73 | 0.612587 | 2.241379 | false | false | false | false |
ManWithBear/CodeInput | Sources/CodeInputWrapper.swift | 1 | 1236 | //
// CodeInputWrapper.swift
// CodeInput
//
// Created by Denis Bogomolov on 04/03/2017.
//
import UIKit
open class CodeInputWrapper: UIView {
open private(set) var textView: CodeInputView!
@IBInspectable var symbolsCount: Int = 4
@IBInspectable var symbolSpacing: CGFloat = 8
@available(*, unavailable) init() {
fatalError("This class designed to be used only in xib/storyboard, please use CodeInputView")
}
@available(*, unavailable) override init(frame: CGRect) {
fatalError("This class designed to be used only in xib/storyboard, please use CodeInputView")
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = .clear
textView = createCodeInputView()
addSubview(textView)
}
open func createCodeInputView() -> CodeInputView {
return CodeInputView(symbolsCount, spacing: symbolSpacing)
}
override open var intrinsicContentSize: CGSize {
return textView.intrinsicContentSize
}
override open func layoutSubviews() {
super.layoutSubviews()
textView.frame = bounds
}
}
| mit | 1307391e9d3ce7d928196b7fdc3fd011 | 27.090909 | 101 | 0.675566 | 4.753846 | false | false | false | false |
blg-andreasbraun/ProcedureKit | Sources/Network/Network.swift | 2 | 8122 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
#if !os(watchOS)
import SystemConfiguration
public protocol NetworkResilience {
/**
The number of attempts to make for the
network request. It represents the total number
of attempts which should be made.
- returns: a Int
*/
var maximumNumberOfAttempts: Int { get }
/**
The timeout backoff wait strategy defines the time between
retry attempts in the event of a network timout.
Use `.Immediate` to indicate no time between retry attempts.
- returns: a WaitStrategy
*/
var backoffStrategy: WaitStrategy { get }
/**
A request timeout, which if specified indicates the maximum
amount of time to wait for a response.
- returns: a TimeInterval
*/
var requestTimeout: TimeInterval? { get }
/**
Some HTTP status codes should be treated as errors, and
retried
- parameter statusCode: an Int
- returns: a Bool, to indicate that the
*/
func shouldRetry(forResponseWithHTTPStatusCode statusCode: HTTPStatusCode) -> Bool
}
public struct DefaultNetworkResilience: NetworkResilience {
public let maximumNumberOfAttempts: Int
public let backoffStrategy: WaitStrategy
public let requestTimeout: TimeInterval?
public init(maximumNumberOfAttempts: Int = 3, backoffStrategy: WaitStrategy = .incrementing(initial: 2, increment: 2), requestTimeout: TimeInterval? = 8.0) {
self.maximumNumberOfAttempts = maximumNumberOfAttempts
self.backoffStrategy = backoffStrategy
self.requestTimeout = requestTimeout
}
public func shouldRetry(forResponseWithHTTPStatusCode statusCode: HTTPStatusCode) -> Bool {
switch statusCode {
case let code where code.isServerError:
return true
case .requestTimeout, .tooManyRequests:
return true
default:
return false
}
}
}
public enum ProcedureKitNetworkResiliencyError: Error {
case receivedErrorStatusCode(HTTPStatusCode)
}
class NetworkReachabilityWaitProcedure: Procedure {
let reachability: SystemReachability
let connectivity: Reachability.Connectivity
init(reachability: SystemReachability, via connectivity: Reachability.Connectivity = .any) {
self.reachability = reachability
self.connectivity = connectivity
super.init()
}
override func execute() {
reachability.whenReachable(via: connectivity) { [weak self] in self?.finish() }
}
}
class NetworkRecovery<T: Operation> where T: NetworkOperation {
let resilience: NetworkResilience
let connectivity: Reachability.Connectivity
var reachability: SystemReachability = Reachability.Manager.shared
var max: Int { return resilience.maximumNumberOfAttempts }
var wait: WaitStrategy { return resilience.backoffStrategy }
init(resilience: NetworkResilience, connectivity: Reachability.Connectivity) {
self.resilience = resilience
self.connectivity = connectivity
}
func recover(withInfo info: RetryFailureInfo<T>, payload: RepeatProcedurePayload<T>) -> RepeatProcedurePayload<T>? {
let networkResponse = info.operation.makeNetworkResponse()
// Check to see if we should wait for a network reachability change before retrying
if shouldWaitForReachabilityChange(givenNetworkResponse: networkResponse) {
let waiter = NetworkReachabilityWaitProcedure(reachability: reachability, via: connectivity)
payload.operation.add(dependency: waiter)
info.addOperations(waiter)
return RepeatProcedurePayload(operation: payload.operation, delay: nil, configure: payload.configure)
}
// Check if the resiliency behavior indicates a retry
guard shouldRetry(givenNetworkResponse: networkResponse) else { return nil }
return payload
}
func shouldWaitForReachabilityChange(givenNetworkResponse networkResponse: ProcedureKitNetworkResponse) -> Bool {
guard let networkError = networkResponse.error else { return false }
return networkError.waitForReachabilityChangeBeforeRetrying
}
func shouldRetry(givenNetworkResponse networkResponse: ProcedureKitNetworkResponse) -> Bool {
// Check that we've actually got a network error & suggested delay
if let networkError = networkResponse.error {
// Check to see if we have a transient or timeout network error - retry with suggested delay
if networkError.isTransientError || networkError.isTimeoutError {
return true
}
}
// Check to see if we have an http error code
guard let statusCode = networkResponse.httpStatusCode, statusCode.isClientError || statusCode.isServerError else {
return false
}
// Query the network resilience type to determine the behavior.
return resilience.shouldRetry(forResponseWithHTTPStatusCode: statusCode)
}
}
open class NetworkProcedure<T: Procedure>: RetryProcedure<T>, OutputProcedure where T: NetworkOperation, T: OutputProcedure, T.Output: HTTPPayloadResponseProtocol {
public typealias Output = T.Output
let recovery: NetworkRecovery<T>
internal var reachability: SystemReachability {
get { return recovery.reachability }
set { recovery.reachability = newValue }
}
public init<OperationIterator>(dispatchQueue: DispatchQueue? = nil, resilience: NetworkResilience = DefaultNetworkResilience(), connectivity: Reachability.Connectivity = .any, iterator base: OperationIterator) where OperationIterator: IteratorProtocol, OperationIterator.Element == T {
recovery = NetworkRecovery<T>(resilience: resilience, connectivity: connectivity)
super.init(dispatchQueue: dispatchQueue, max: recovery.max, wait: recovery.wait, iterator: base, retry: recovery.recover(withInfo:payload:))
if let timeout = resilience.requestTimeout {
appendConfigureBlock { $0.add(observer: TimeoutObserver(by: timeout)) }
}
}
public convenience init(dispatchQueue: DispatchQueue = DispatchQueue.default, resilience: NetworkResilience = DefaultNetworkResilience(), connectivity: Reachability.Connectivity = .any, body: @escaping () -> T?) {
self.init(dispatchQueue: dispatchQueue, resilience: resilience, connectivity: connectivity, iterator: AnyIterator(body))
}
open override func procedureQueue(_ queue: ProcedureQueue, willFinishOperation operation: Operation, withErrors errors: [Error]) {
var networkErrors = errors
// Ultimately, always call super to correctly manage the operation lifecycle.
defer { super.procedureQueue(queue, willFinishOperation: operation, withErrors: networkErrors) }
// Check that the operation is the current one.
guard operation == current else { return }
// If we have any errors let RetryProcedure (super) deal with it by returning here
guard errors.isEmpty else { return }
// Create a network response from the network operation
let networkResponse = current.makeNetworkResponse()
// Check to see if this network response should be retried
guard recovery.shouldRetry(givenNetworkResponse: networkResponse), let statusCode = networkResponse.httpStatusCode else { return }
// Create resiliency error
let error: ProcedureKitNetworkResiliencyError = .receivedErrorStatusCode(statusCode)
// Set the network errors
networkErrors = [error]
}
}
#endif
public extension InputProcedure where Input: Equatable {
@discardableResult func injectPayload<Dependency: OutputProcedure>(fromNetwork dependency: Dependency) -> Self where Dependency.Output: HTTPPayloadResponseProtocol, Dependency.Output.Payload == Input {
return injectResult(from: dependency) { http in
guard let payload = http.payload else { throw ProcedureKitError.requirementNotSatisfied() }
return payload
}
}
}
| mit | 283c8ff41e261fc5b61f35d18d90caa0 | 37.126761 | 289 | 0.715799 | 5.465007 | false | false | false | false |
kumabook/StickyNotesiOS | StickyNotes/MBProgressHUDExtension.swift | 1 | 1305 | //
// MBProgressHUDExtension.swift
// StickyNotes
//
// Created by Hiroki Kumamoto on 2017/05/04.
// Copyright © 2017 kumabook. All rights reserved.
//
import Foundation
import MBProgressHUD
extension MBProgressHUD {
fileprivate class func createCompletedHUD(_ view: UIView) -> MBProgressHUD {
let hud = MBProgressHUD(view: view)
hud.customView = UIImageView(image:UIImage(named:"checkmark"))
hud.mode = MBProgressHUDMode.customView
hud.label.text = "Completed".localize()
return hud
}
class func showCompletedHUDForView(_ view: UIView, animated: Bool, duration: TimeInterval, after: @escaping () -> Void) -> MBProgressHUD {
let hud = MBProgressHUD.createCompletedHUD(view)
view.addSubview(hud)
hud.show(true, duration: duration, after: {
hud.removeFromSuperview()
after()
})
return hud
}
func show(_ animated:Bool, duration:TimeInterval, after:@escaping () -> Void) {
show(animated: true)
let startTime = DispatchTime.now() + Double(Int64(duration * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: startTime) { () -> Void in
self.hide(animated: true)
after()
}
}
}
| mit | 95a65f9079c8b6617bd002547606464a | 32.435897 | 142 | 0.638037 | 4.405405 | false | false | false | false |
domenicosolazzo/practice-swift | playgrounds/Enumerations.playground/section-1.swift | 1 | 1598 | // Enumerations
/**
An enumeration defines a common type for a a group of related values
and enables you to work with those values in a type-safe way within
your code
Enumerations in Swift are first-class types in their own right.
They adopt many features traditionally supported only by classes,
such as computed properties to provide additional information about
the enumeration's value.
*/
import Cocoa
/**
========================================
======== Enumeration Syntax ============
========================================
**/
/**
Enumerations are created using the enum keyword and
place their entire definition within a pair of braces.
The values are called 'members values'.
Unline C, Swift enumerations members are not assigned a default integer value when
they are created. They are fully-fledged values on their own.
The case keyword indicates that a new line of member values is
about to be defined.
**/
enum Planet{
case Mercury, Venus, Earth, Mars, // Multiple member values can appear separated by comma
Jupiter, Saturn, Uranus, Neptune
}
var earth = Planet.Earth
/**
You can drop the Type in the following assignment because it is already known by Swift
**/
earth = .Mercury
enum Barcode{
case UPCA(Int, Int, Int)
case QRCode(String)
}
var productBarCode = Barcode.UPCA(20, 20, 100)
/**
======= RAW Values =======
*/
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
var char = ASCIIControlCharacter.Tab.rawValue
// FromRaw
var val = ASCIIControlCharacter(rawValue: "\t")
| mit | c5a4fa7cb50bff398f2596cd598633a3 | 24.365079 | 93 | 0.689612 | 4.318919 | false | false | false | false |
ifLab/WeCenterMobile-iOS | WeCenterMobile/Controller/HotTopicListViewController.swift | 3 | 6859 | //
// HotTopicListViewController.swift
// WeCenterMobile
//
// Created by Bill Hu on 15/12/9.
// Copyright © 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import MJRefresh
import UIKit
class HotTopicListViewController: UITableViewController {
var type: TopicObjectListType
var firstSelected = true
var page = 1
var topics = [Topic]()
var shouldReloadAfterLoadingMore = true
let count = 20
let objectTypes: [FeaturedObject.Type] = [FeaturedQuestionAnswer.self, FeaturedQuestionAnswer.self, FeaturedArticle.self]
let cellReuseIdentifier = "TopicCell"
let cellNibName = "TopicCell"
init(type: TopicObjectListType) {
self.type = type
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
let theme = SettingsManager.defaultManager.currentTheme
view.backgroundColor = UIColor.clearColor()
tableView.indicatorStyle = theme.scrollViewIndicatorStyle
tableView.delaysContentTouches = false
tableView.msr_wrapperView?.delaysContentTouches = false
tableView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self)
tableView.separatorStyle = .None
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension
tableView.wc_addRefreshingHeaderWithTarget(self, action: "refresh")
tableView.registerNib(UINib(nibName: cellNibName, bundle: NSBundle.mainBundle()), forCellReuseIdentifier: cellReuseIdentifier)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.mj_header.beginRefreshing()
}
func segmentedViewControllerDidSelectSelf(segmentedViewController: MSRSegmentedViewController) {
if firstSelected {
firstSelected = false
tableView.mj_header.beginRefreshing()
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return topics.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! TopicCell
cell.update(topic: topics[indexPath.row])
cell.topicButtonA.addTarget(self, action: "didPressTopicButton:", forControlEvents: .TouchUpInside)
cell.topicButtonB.addTarget(self, action: "didPressTopicButton:", forControlEvents: .TouchUpInside)
return cell
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func didPressTopicButton(sender: UIButton) {
if let topic = sender.msr_userInfo as? Topic {
msr_navigationController!.pushViewController(TopicViewController(topic: topic), animated: true)
}
}
func refresh() {
shouldReloadAfterLoadingMore = false
tableView.mj_footer?.endRefreshing()
if type == .Focus {
let user = User.currentUser!
user.fetchTopics(
page: 1,
count: count,
success: {
[weak self] topics in
if let self_ = self {
self_.page = 1
self_.topics = topics
self_.tableView.reloadData()
self_.tableView.mj_header.endRefreshing()
if self_.tableView.mj_footer == nil {
self_.tableView.wc_addRefreshingFooterWithTarget(self_, action: "loadMore")
}
}
return
},
failure: {
[weak self] error in
self?.tableView.mj_header.endRefreshing()
return
})
} else {
Topic.fetchHotTopic(page: 1, count: count, type: type,
success: {
[weak self] topics in
if let self_ = self {
self_.page = 1
self_.topics = topics
self_.tableView.reloadData()
self_.tableView.mj_header.endRefreshing()
if self_.tableView.mj_footer == nil {
self_.tableView.wc_addRefreshingFooterWithTarget(self_, action: "loadMore")
}
}
return
},
failure: {
[weak self] error in
self?.tableView.mj_header.endRefreshing()
return
})
}
}
func loadMore() {
if tableView.mj_header.isRefreshing() {
tableView.mj_footer.endRefreshing()
return
}
shouldReloadAfterLoadingMore = true
if type == .Focus {
let user = User.currentUser!
user.fetchTopics(
page: page + 1,
count: count,
success: {
[weak self] topics in
if let self_ = self {
if self_.shouldReloadAfterLoadingMore {
++self_.page
self_.topics.appendContentsOf(topics)
self_.tableView.reloadData()
}
self_.tableView.mj_footer.endRefreshing()
}
return
},
failure: {
[weak self] error in
self?.tableView.mj_footer.endRefreshing()
return
})
} else {
Topic.fetchHotTopic(page: page + 1, count: count, type: type,
success: {
[weak self] topics in
if let self_ = self {
if self_.shouldReloadAfterLoadingMore {
++self_.page
self_.topics.appendContentsOf(topics)
self_.tableView.reloadData()
self_.tableView.mj_footer.endRefreshing()
}
}
return
},
failure: {
[weak self] error in
self?.tableView.mj_header.endRefreshing()
return
})
}
}
}
| gpl-2.0 | 3d0bc99c78f93cb1f140ef4ddc57402d | 39.093567 | 134 | 0.541278 | 5.742044 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Basics.playground/Pages/Parameter Ramp Time.xcplaygroundpage/Contents.swift | 1 | 1365 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Parameter Ramp Time
//: Most AudioKit nodes have parameters that you can change.
//: Its very common need to change these parameters in a smooth way
//: to avoid pops and clicks, so you can set a ramp time to slow the
//: variation of a property from its current value to its next.
import XCPlayground
import AudioKit
var noise = AKWhiteNoise(amplitude: 1)
var filter = AKMoogLadder(noise)
filter.resonance = 0.94
AudioKit.output = filter
AudioKit.start()
noise.start()
var counter = 0
AKPlaygroundLoop(frequency: 2.66) {
let frequencyToggle = counter % 2
if frequencyToggle > 0 {
filter.cutoffFrequency = 111
} else {
filter.cutoffFrequency = 666
}
counter += 1
}
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Parameter Ramp Time")
addSubview(AKPropertySlider(
property: "Ramp Time",
format: "%0.3f s",
value: filter.rampTime
) { sliderValue in
filter.rampTime = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | bf53156490f86c2d82d0430292aee928 | 23.818182 | 72 | 0.663004 | 4.226006 | false | false | false | false |
Journey321/xiaorizi | xiaorizi/Classes/Extension/NSString+Util.swift | 1 | 2028 | //
// NSString+Util.swift
//
//
// Created by zhike on 16/9/5.
//
//
import Foundation
import CoreLocation
extension String {
/// 判断是否是邮箱
func validateEmail() -> Bool {
let emailRegex: String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest: NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluateWithObject(self)
}
/// 判断是否是手机号
func validateMobile() -> Bool {
let phoneRegex: String = "^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0,0-9]))\\d{8}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluateWithObject(self)
}
/// 将字符串转换成经纬度
func stringToCLLocationCoordinate2D(separator: String) -> CLLocationCoordinate2D? {
let arr = self.componentsSeparatedByString(separator)
if arr.count != 2 {
return nil
}
let latitude: Double = NSString(string: arr[1]).doubleValue
let longitude: Double = NSString(string: arr[0]).doubleValue
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
func textSizeWithFont(font: UIFont, constrainedToSize size:CGSize) -> CGSize {
var textSize:CGSize!
if CGSizeEqualToSize(size, CGSizeZero) {
let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
textSize = self.sizeWithAttributes(attributes as? [String : AnyObject])
} else {
let option = NSStringDrawingOptions.UsesLineFragmentOrigin
let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
let stringRect = self.boundingRectWithSize(size, options: option, attributes: attributes as? [String : AnyObject], context: nil)
textSize = stringRect.size
}
return textSize
}
}
| mit | 88fb0cc42f9ffd22528bc0cea8f930a7 | 28.522388 | 144 | 0.602123 | 4.698337 | false | true | false | false |
gservera/ScheduleKit | SCKExample-Swift/EventLoadingView.swift | 1 | 1937 | //
// EventLoadingView.swift
// ScheduleKit
//
// Created by Guillem Servera Negre on 2/11/16.
// Copyright © 2016 Guillem Servera. All rights reserved.
//
import Cocoa
final class EventLoadingView: NSView {
let label = NSTextField(frame: .zero)
let spinner = NSProgressIndicator(frame: .zero)
override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
if label.superview == nil {
label.translatesAutoresizingMaskIntoConstraints = false
label.isBordered = false
label.isEditable = false
label.isBezeled = false
label.drawsBackground = false
label.stringValue = "Loading events asynchronously…"
label.font = NSFont.systemFont(ofSize: 30.0, weight: .thin)
addSubview(label)
label.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 10.0).isActive = true
label.sizeToFit()
label.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 1000), for: .horizontal)
label.setContentHuggingPriority(NSLayoutConstraint.Priority(rawValue: 1000), for: .horizontal)
label.textColor = NSColor.labelColor
spinner.style = .spinning
spinner.translatesAutoresizingMaskIntoConstraints = false
spinner.isIndeterminate = true
addSubview(spinner)
spinner.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
spinner.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -30.0).isActive = true
spinner.startAnimation(nil)
} else if superview == nil {
spinner.stopAnimation(nil)
}
}
override func draw(_ dirtyRect: NSRect) {
NSColor.controlBackgroundColor.set()
dirtyRect.fill()
}
}
| mit | 92a19d16823f9375742eb12919e2603a | 37.68 | 120 | 0.662358 | 5.284153 | false | false | false | false |
practicalswift/swift | stdlib/public/core/UnicodeEncoding.swift | 6 | 4568 | //===--- UnicodeEncoding.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public protocol _UnicodeEncoding {
/// The basic unit of encoding
associatedtype CodeUnit : UnsignedInteger, FixedWidthInteger
/// A valid scalar value as represented in this encoding
associatedtype EncodedScalar : BidirectionalCollection
where EncodedScalar.Iterator.Element == CodeUnit
/// A unicode scalar value to be used when repairing
/// encoding/decoding errors, as represented in this encoding.
///
/// If the Unicode replacement character U+FFFD is representable in this
/// encoding, `encodedReplacementCharacter` encodes that scalar value.
static var encodedReplacementCharacter : EncodedScalar { get }
/// Converts from encoded to encoding-independent representation
static func decode(_ content: EncodedScalar) -> Unicode.Scalar
/// Converts from encoding-independent to encoded representation, returning
/// `nil` if the scalar can't be represented in this encoding.
static func encode(_ content: Unicode.Scalar) -> EncodedScalar?
/// Converts a scalar from another encoding's representation, returning
/// `nil` if the scalar can't be represented in this encoding.
///
/// A default implementation of this method will be provided
/// automatically for any conforming type that does not implement one.
static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar?
/// A type that can be used to parse `CodeUnits` into
/// `EncodedScalar`s.
associatedtype ForwardParser : Unicode.Parser
where ForwardParser.Encoding == Self
/// A type that can be used to parse a reversed sequence of
/// `CodeUnits` into `EncodedScalar`s.
associatedtype ReverseParser : Unicode.Parser
where ReverseParser.Encoding == Self
//===--------------------------------------------------------------------===//
// FIXME: this requirement shouldn't be here and is mitigated by the default
// implementation below. Compiler bugs prevent it from being expressed in an
// intermediate, underscored protocol.
/// Returns true if `x` only appears in this encoding as the representation of
/// a complete scalar value.
static func _isScalar(_ x: CodeUnit) -> Bool
}
extension _UnicodeEncoding {
// See note on declaration of requirement, above
@inlinable
public static func _isScalar(_ x: CodeUnit) -> Bool { return false }
@inlinable
public static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar? {
return encode(FromEncoding.decode(content))
}
/// Converts from encoding-independent to encoded representation, returning
/// `encodedReplacementCharacter` if the scalar can't be represented in this
/// encoding.
@inlinable
internal static func _encode(_ content: Unicode.Scalar) -> EncodedScalar {
return encode(content) ?? encodedReplacementCharacter
}
/// Converts a scalar from another encoding's representation, returning
/// `encodedReplacementCharacter` if the scalar can't be represented in this
/// encoding.
@inlinable
internal static func _transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar {
return transcode(content, from: FromEncoding.self)
?? encodedReplacementCharacter
}
@inlinable
internal static func _transcode<
Source: Sequence, SourceEncoding: Unicode.Encoding>(
_ source: Source,
from sourceEncoding: SourceEncoding.Type,
into processScalar: (EncodedScalar)->Void)
where Source.Element == SourceEncoding.CodeUnit {
var p = SourceEncoding.ForwardParser()
var i = source.makeIterator()
while true {
switch p.parseScalar(from: &i) {
case .valid(let e): processScalar(_transcode(e, from: sourceEncoding))
case .error(_): processScalar(encodedReplacementCharacter)
case .emptyInput: return
}
}
}
}
extension Unicode {
public typealias Encoding = _UnicodeEncoding
}
| apache-2.0 | 2e10446b8578cb76ab3a20bebf5d58db | 38.37931 | 80 | 0.700525 | 5.232532 | false | false | false | false |
NoManTeam/Hole | CryptoFramework/Crypto/Algorithm/AES_256_ECB/AES_API.swift | 1 | 1289 | //
// AES.swift
// 密语输入法
//
// Created by macsjh on 15/9/24.
// Copyright © 2015年 macsjh. All rights reserved.
//
import Foundation
/**
AES_256_ECB加密API
- Parameter plainText: 要加密的明文
- Parameter key: 密码(长度任意,会转换为MD5值)
- Returns: 加密后的密文(base64编码字符串)
*/
func aesEncrypt(plainText:NSString, var key:String) -> NSString?
{
key = MessageDigest.md5(key)
let base64PlainText = LowLevelEncryption.base64Encode(plainText)
if(base64PlainText != nil)
{
let cipherText = NSAESString.aes256_encrypt(base64PlainText!, Key: key)
if(cipherText != nil)
{
return LowLevelEncryption.base64Encode(cipherText!)
}
}
return nil
}
/**
AES_256_ECB解密API
- Parameter plainText: 要解密的密文
- Parameter key: 密码(长度任意,会转换为MD5值)
- Returns: 明文(base64编码字符串)
*/
func aesDecrypt(cipherText:NSString, var key:String) -> NSString?
{
key = MessageDigest.md5(key)
let originCipherText = LowLevelEncryption.base64Decode(cipherText)
if(originCipherText != nil)
{
let base64CipherText = NSAESString.aes256_decrypt(originCipherText!, key: key)
if (base64CipherText != nil)
{
return LowLevelEncryption.base64Decode(base64CipherText!)
}
}
return nil
} | unlicense | c6f0566bf9a64141546301f1ed5c935c | 20.203704 | 80 | 0.733392 | 2.896203 | false | false | false | false |
adamnemecek/AudioKit | Sources/AudioKit/Taps/NodeRecorder.swift | 1 | 8005 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
/// Simple audio recorder class, requires a minimum buffer length of 128 samples (.short)
open class NodeRecorder: NSObject {
// MARK: - Properties
/// The node we record from
public private(set) var node: Node
/// True if we are recording.
public private(set) var isRecording = false
/// An optional duration for the recording to auto-stop when reached
open var durationToRecord: Double = 0
/// Duration of recording
open var recordedDuration: Double {
return internalAudioFile?.duration ?? 0
}
/// If non-nil, attempts to apply this as the format of the specified output bus. This should
/// only be done when attaching to an output bus which is not connected to another node; an
/// error will result otherwise.
/// The tap and connection formats (if non-nil) on the specified bus should be identical.
/// Otherwise, the latter operation will override any previously set format.
///
/// Default is nil.
open var recordFormat: AVAudioFormat?
// The file to record to
private var internalAudioFile: AVAudioFile?
/// The bus to install the recording tap on. Default is 0.
private var bus: Int = 0
/// Used for fixing recordings being truncated
private var recordBufferDuration: Double = 16_384 / Settings.sampleRate
/// return the AVAudioFile for reading
open var audioFile: AVAudioFile? {
do {
guard let url = internalAudioFile?.url else { return nil }
return try AVAudioFile(forReading: url)
} catch let error as NSError {
Log("Error, Cannot create internal audio file for reading: \(error.localizedDescription)")
return nil
}
}
private static var tmpFiles = [URL]()
// MARK: - Initialization
/// Initialize the node recorder
///
/// Recording buffer size is Settings.recordingBufferLength
///
/// - Parameters:
/// - node: Node to record from
/// - file: Audio file to record to
/// - bus: Integer index of the bus to use
///
public init(node: Node,
file: AVAudioFile? = NodeRecorder.createTempFile(),
bus: Int = 0) throws {
self.node = node
super.init()
guard let file = file else {
Log("Error, no file to write to")
return
}
do {
// We initialize AVAudioFile for writing (and check that we can write to)
internalAudioFile = try AVAudioFile(forWriting: file.url,
settings: file.fileFormat.settings)
} catch let error as NSError {
Log("Error: cannot write to", file.url)
throw error
}
self.bus = bus
}
// MARK: - Methods
/// Returns a CAF file in the NSTemporaryDirectory suitable for writing to via Settings.audioFormat
public static func createTempFile() -> AVAudioFile? {
let filename = UUID().uuidString + ".caf"
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
var settings = Settings.audioFormat.settings
settings[AVLinearPCMIsNonInterleaved] = NSNumber(value: false)
Log("Creating temp file at", url)
guard let tmpFile = try? AVAudioFile(forWriting: url,
settings: settings,
commonFormat: Settings.audioFormat.commonFormat,
interleaved: true) else { return nil }
tmpFiles.append(url)
return tmpFile
}
/// When done with this class, remove any temp files that were created with createTempFile()
public static func removeTempFiles() {
for url in NodeRecorder.tmpFiles {
try? FileManager.default.removeItem(at: url)
Log("𝗫 Deleted tmp file at", url)
}
NodeRecorder.tmpFiles.removeAll()
}
/// Start recording
public func record() throws {
if isRecording == true {
Log("Warning: already recording")
return
}
if let path = internalAudioFile?.url.path, !FileManager.default.fileExists(atPath: path) {
// record to new tmp file
if let tmpFile = NodeRecorder.createTempFile() {
internalAudioFile = try AVAudioFile(forWriting: tmpFile.url,
settings: tmpFile.fileFormat.settings)
}
}
let bufferLength: AVAudioFrameCount = Settings.recordingBufferLength.samplesCount
isRecording = true
// Note: if you install a tap on a bus that already has a tap it will crash your application.
Log("⏺ Recording using format", internalAudioFile?.processingFormat.debugDescription)
// note, format should be nil as per the documentation for installTap:
// "If non-nil, attempts to apply this as the format of the specified output bus. This should
// only be done when attaching to an output bus which is not connected to another node"
// In most cases AudioKit nodes will be attached to something else.
// Make sure the input node has an engine
// before recording
if node.avAudioNode.engine == nil {
Log("🛑 Error: Error recording. Input node '\(node)' has no engine.")
isRecording = false
return
}
node.avAudioNode.installTap(onBus: bus,
bufferSize: bufferLength,
format: recordFormat,
block: process(buffer:time:))
}
private func process(buffer: AVAudioPCMBuffer, time: AVAudioTime) {
guard let internalAudioFile = internalAudioFile else { return }
do {
recordBufferDuration = Double(buffer.frameLength) / Settings.sampleRate
try internalAudioFile.write(from: buffer)
// allow an optional timed stop
if durationToRecord != 0 && internalAudioFile.duration >= durationToRecord {
stop()
}
} catch let error as NSError {
Log("Write failed: error -> \(error.localizedDescription)")
}
}
/// Stop recording
public func stop() {
if isRecording == false {
Log("Warning: Cannot stop recording, already stopped")
return
}
isRecording = false
if Settings.fixTruncatedRecordings {
// delay before stopping so the recording is not truncated.
let delay = UInt32(recordBufferDuration * 1_000_000)
usleep(delay)
}
node.avAudioNode.removeTap(onBus: bus)
}
/// Reset the AVAudioFile to clear previous recordings
public func reset() throws {
// Stop recording
if isRecording == true {
stop()
}
guard let internalAudioFile = internalAudioFile else { return }
// Delete the physical recording file
let fileManager = FileManager.default
let settings = internalAudioFile.fileFormat.settings
let url = internalAudioFile.url
do {
if let path = audioFile?.url.path {
try fileManager.removeItem(atPath: path)
}
} catch let error as NSError {
Log("Error: Can't delete" + (audioFile?.url.lastPathComponent ?? "nil") + error.localizedDescription)
}
// Creates a blank new file
do {
self.internalAudioFile = try AVAudioFile(forWriting: url, settings: settings)
Log("File has been cleared")
} catch let error as NSError {
Log("Error: Can't record to" + url.lastPathComponent)
throw error
}
}
}
| mit | e8cb85491c20293b20773298f4096f46 | 35.022523 | 113 | 0.6006 | 5.327781 | false | false | false | false |
balazsnemeth/Swift-YouTube-Player | YouTubePlayerExample/YouTubePlayerExample/ViewController.swift | 2 | 2493 | //
// ViewController.swift
// YouTubePlayerExample
//
// Created by Giles Van Gruisen on 1/31/15.
// Copyright (c) 2015 Giles Van Gruisen. All rights reserved.
//
import UIKit
import YouTubePlayer
class ViewController: UIViewController {
@IBOutlet var playerView: YouTubePlayerView!
@IBOutlet var playButton: UIButton!
@IBOutlet var currentTimeButton: UIButton!
@IBOutlet var durationButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func play(sender: UIButton) {
if playerView.ready {
if playerView.playerState != YouTubePlayerState.Playing {
playerView.play()
playButton.setTitle("Pause", forState: .Normal)
} else {
playerView.pause()
playButton.setTitle("Play", forState: .Normal)
}
}
}
@IBAction func prev(sender: UIButton) {
playerView.previousVideo()
}
@IBAction func next(sender: UIButton) {
playerView.nextVideo()
}
@IBAction func loadVideo(sender: UIButton) {
playerView.playerVars = [
"playsinline": "1",
"controls": "0",
"showinfo": "0"
]
playerView.loadVideoID("wQg3bXrVLtg")
}
@IBAction func loadPlaylist(sender: UIButton) {
playerView.loadPlaylistID("RDe-ORhEE9VVg")
}
@IBAction func currentTime(sender: UIButton) {
let title = String(format: "Current Time %@", playerView.getCurrentTime() ?? "0")
currentTimeButton.setTitle(title, forState: .Normal)
}
@IBAction func duration(sender: UIButton) {
let title = String(format: "Duration %@", playerView.getDuration() ?? "0")
durationButton.setTitle(title, forState: .Normal)
}
func showAlert(message: String) {
self.presentViewController(alertWithMessage(message), animated: true, completion: nil)
}
func alertWithMessage(message: String) -> UIAlertController {
let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
return alertController
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | a282e6b657431ef5beac4cb5cc52789f | 28.329412 | 101 | 0.632972 | 4.677298 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/KeyVerification/Common/Verify/Scanning/KeyVerificationVerifyByScanningViewModel.swift | 1 | 10529 | // File created from ScreenTemplate
// $ createScreen.sh Verify KeyVerificationVerifyByScanning
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
enum KeyVerificationVerifyByScanningViewModelError: Error {
case unknown
}
final class KeyVerificationVerifyByScanningViewModel: KeyVerificationVerifyByScanningViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let verificationKind: KeyVerificationKind
private let keyVerificationRequest: MXKeyVerificationRequest
private let qrCodeDataCoder: MXQRCodeDataCoder
private let keyVerificationManager: MXKeyVerificationManager
private var qrCodeTransaction: MXQRCodeTransaction?
private var scannedQRCodeData: MXQRCodeData?
// MARK: Public
weak var viewDelegate: KeyVerificationVerifyByScanningViewModelViewDelegate?
weak var coordinatorDelegate: KeyVerificationVerifyByScanningViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, verificationKind: KeyVerificationKind, keyVerificationRequest: MXKeyVerificationRequest) {
self.session = session
self.verificationKind = verificationKind
self.keyVerificationManager = self.session.crypto.keyVerificationManager
self.keyVerificationRequest = keyVerificationRequest
self.qrCodeDataCoder = MXQRCodeDataCoder()
}
deinit {
self.removePendingQRCodeTransaction()
}
// MARK: - Public
func process(viewAction: KeyVerificationVerifyByScanningViewAction) {
switch viewAction {
case .loadData:
self.loadData()
case .scannedCode(payloadData: let payloadData):
self.scannedQRCode(payloadData: payloadData)
case .cannotScan:
self.startSASVerification()
case .cancel:
self.cancel()
case .acknowledgeMyUserScannedOtherCode:
self.acknowledgeScanOtherCode()
}
}
// MARK: - Private
private func loadData() {
let qrCodePlayloadData: Data?
let canShowScanAction: Bool
self.qrCodeTransaction = self.keyVerificationManager.qrCodeTransaction(withTransactionId: self.keyVerificationRequest.requestId)
if let supportedVerificationMethods = self.keyVerificationRequest.myMethods {
if let qrCodeData = self.qrCodeTransaction?.qrCodeData {
qrCodePlayloadData = self.qrCodeDataCoder.encode(qrCodeData)
} else {
qrCodePlayloadData = nil
}
canShowScanAction = self.canShowScanAction(from: supportedVerificationMethods)
} else {
qrCodePlayloadData = nil
canShowScanAction = false
}
let viewData = KeyVerificationVerifyByScanningViewData(verificationKind: self.verificationKind,
qrCodeData: qrCodePlayloadData,
showScanAction: canShowScanAction)
self.update(viewState: .loaded(viewData: viewData))
self.registerTransactionDidStateChangeNotification()
}
private func canShowScanAction(from verificationMethods: [String]) -> Bool {
return verificationMethods.contains(MXKeyVerificationMethodQRCodeScan)
}
private func cancel() {
self.cancelQRCodeTransaction()
self.keyVerificationRequest.cancel(with: MXTransactionCancelCode.user(), success: nil, failure: nil)
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModelDidCancel(self)
}
private func cancelQRCodeTransaction() {
guard let transaction = self.qrCodeTransaction else {
return
}
transaction.cancel(with: MXTransactionCancelCode.user())
self.removePendingQRCodeTransaction()
}
private func update(viewState: KeyVerificationVerifyByScanningViewState) {
self.viewDelegate?.keyVerificationVerifyByScanningViewModel(self, didUpdateViewState: viewState)
}
// MARK: QR code
private func scannedQRCode(payloadData: Data) {
self.scannedQRCodeData = self.qrCodeDataCoder.decode(payloadData)
let isQRCodeValid = self.scannedQRCodeData != nil
self.update(viewState: .scannedCodeValidated(isValid: isQRCodeValid))
}
private func acknowledgeScanOtherCode() {
guard let scannedQRCodeData = self.scannedQRCodeData else {
return
}
guard let qrCodeTransaction = self.qrCodeTransaction else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModel(self, didScanOtherQRCodeData: scannedQRCodeData, withTransaction: qrCodeTransaction)
}
private func removePendingQRCodeTransaction() {
guard let qrCodeTransaction = self.qrCodeTransaction else {
return
}
self.keyVerificationManager.removeQRCodeTransaction(withTransactionId: qrCodeTransaction.transactionId)
}
// MARK: SAS
private func startSASVerification() {
self.update(viewState: .loading)
self.session.crypto.keyVerificationManager.beginKeyVerification(from: self.keyVerificationRequest, method: MXKeyVerificationMethodSAS, success: { [weak self] (keyVerificationTransaction) in
guard let self = self else {
return
}
// Remove pending QR code transaction, as we are going to use SAS verification
self.removePendingQRCodeTransaction()
if keyVerificationTransaction is MXOutgoingSASTransaction == false {
NSLog("[KeyVerificationVerifyByScanningViewModel] SAS transaction should be outgoing")
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .error(KeyVerificationVerifyByScanningViewModelError.unknown))
}
}, failure: { [weak self] (error) in
guard let self = self else {
return
}
self.update(viewState: .error(error))
}
)
}
// MARK: - MXKeyVerificationTransactionDidChange
private func registerTransactionDidStateChangeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(transactionDidStateChange(notification:)), name: .MXKeyVerificationTransactionDidChange, object: nil)
}
private func unregisterTransactionDidStateChangeNotification() {
NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationTransactionDidChange, object: nil)
}
@objc private func transactionDidStateChange(notification: Notification) {
guard let transaction = notification.object as? MXKeyVerificationTransaction else {
return
}
guard self.keyVerificationRequest.requestId == transaction.transactionId else {
NSLog("[KeyVerificationVerifyByScanningViewModel] transactionDidStateChange: Not for our transaction (\(self.keyVerificationRequest.requestId)): \(transaction.transactionId)")
return
}
if let sasTransaction = transaction as? MXSASTransaction {
self.sasTransactionDidStateChange(sasTransaction)
} else if let qrCodeTransaction = transaction as? MXQRCodeTransaction {
self.qrCodeTransactionDidStateChange(qrCodeTransaction)
}
}
private func sasTransactionDidStateChange(_ transaction: MXSASTransaction) {
switch transaction.state {
case MXSASTransactionStateShowSAS:
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModel(self, didStartSASVerificationWithTransaction: transaction)
case MXSASTransactionStateCancelled:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelled(reason))
case MXSASTransactionStateCancelledByMe:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelledByMe(reason))
default:
break
}
}
private func qrCodeTransactionDidStateChange(_ transaction: MXQRCodeTransaction) {
switch transaction.state {
case .verified:
// Should not happen
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModelDidCancel(self)
case .qrScannedByOther:
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModel(self, qrCodeDidScannedByOtherWithTransaction: transaction)
case .cancelled:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelled(reason))
case .cancelledByMe:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelledByMe(reason))
default:
break
}
}
}
| apache-2.0 | 9b5b935bcd427850733bbc5e752ead2a | 38.732075 | 197 | 0.672808 | 6.685079 | false | false | false | false |
benbahrenburg/BucketList | BucketList/Classes/EncryptedDiskCache.swift | 1 | 5017 | //
// BucketList - Just another cache provider with security built in
// EncryptedDiskCache.swift
//
// Created by Ben Bahrenburg on 3/23/16.
// Copyright © 2016 bencoding.com. All rights reserved.
//
import Foundation
import RNCryptor
/**
Encrypted File Based Cache Provider
*/
public final class EncryptedDiskCache: SecureBucket {
private let _cacheName: String
private let _directoryURL: URL
var emptyOnUnload: Bool = true
var imageConverterOption: CacheOptions.imageConverter = CacheOptions.imageConverter.jpegRepresentation
public init(_ cacheName: String = UUID().uuidString) {
_cacheName = cacheName
let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
_directoryURL = dir.appendingPathComponent(_cacheName)
if !FileHelpers.exists(_directoryURL) {
do {
try FileManager.default.createDirectory(atPath: _directoryURL.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Cannot create cache director: \(error)")
}
}
}
deinit {
if emptyOnUnload {
empty()
}
}
@discardableResult public func add(_ secret: String, forKey: String, object: AnyObject) throws -> Bool {
return try autoreleasepool { () -> Bool in
let fileURL = getPathForKey(forKey)
let data = NSKeyedArchiver.archivedData(withRootObject: object)
try writeEncrypted(secret, path: fileURL, data: data)
return true
}
}
@discardableResult public func add(_ secret: String, forKey: String, image: UIImage) throws -> Bool {
return try autoreleasepool { () -> Bool in
let fileURL = getPathForKey(forKey)
if let data = Converters.convertImage(image, option: imageConverterOption) {
try writeEncrypted(secret, path: fileURL, data: data)
return true
}
return false
}
}
@discardableResult public func add(_ secret: String, forKey: String, data: Data) throws -> Bool {
return try autoreleasepool { () -> Bool in
let fileURL = getPathForKey(forKey)
try writeEncrypted(secret, path: fileURL, data: data)
return true
}
}
public func getObject(_ secret: String, forKey: String) throws -> AnyObject? {
if exists(forKey) {
let fileURL = getPathForKey(forKey)
let data = try readEncrypted(secret, path: fileURL)
return NSKeyedUnarchiver.unarchiveObject(with: data) as AnyObject?
}
return nil
}
public func getData(_ secret: String, forKey: String) throws -> Data? {
if exists(forKey) {
let fileURL = getPathForKey(forKey)
return try readEncrypted(secret, path: fileURL)
}
return nil
}
public func getImage(_ secret: String, forKey: String) throws -> UIImage? {
if exists(forKey) {
let fileURL = getPathForKey(forKey)
let data = try readEncrypted(secret, path: fileURL)
return UIImage(data: data)
}
return nil
}
@discardableResult public func remove(_ forKey: String) throws -> Bool {
let fileURL = getPathForKey(forKey)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: fileURL.path) {
try fileManager.removeItem(atPath: fileURL.path)
}
return true
}
@discardableResult public func empty() -> Bool {
do {
try FileHelpers.removeAll(_directoryURL)
return true
} catch {
print("Could not remove all cache: \(error)")
return false
}
}
public func exists(_ forKey: String) -> Bool {
return FileHelpers.exists(getPathForKey(forKey))
}
private func getPathForKey(_ forKey: String) -> URL {
return _directoryURL.appendingPathComponent(forKey)
}
private func readEncrypted(_ secret: String, path: URL) throws -> Data {
return try autoreleasepool { () -> Data in
let output = NSMutableData()
let data = try Data(contentsOf: path)
let decryptor = RNCryptor.Decryptor(password: secret)
try output.append(decryptor.update(withData: data))
try output.append(decryptor.finalData())
return output as Data
}
}
private func writeEncrypted(_ secret: String, path: URL, data: Data) throws {
try autoreleasepool {
let encryptor = RNCryptor.Encryptor(password: secret)
let encrypt = NSMutableData()
encrypt.append(encryptor.update(withData: data))
encrypt.append(encryptor.finalData())
try encrypt.write(to: path, options: [.atomicWrite, .completeFileProtection])
}
}
}
| mit | a4380d466f3ad85663e3aaba3fa2f780 | 33.122449 | 135 | 0.605064 | 4.996016 | false | false | false | false |
Brightify/Cuckoo | Generator/Source/CuckooGeneratorFramework/Utils.swift | 2 | 1926 | //
// String+Utility.swift
// CuckooGenerator
//
// Created by Tadeas Kriz on 12/01/16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Foundation
import SourceKittenFramework
extension String {
var trimmed: String {
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
func takeUntil(occurence: String) -> String? {
return components(separatedBy: occurence).first
}
subscript(range: Range<Int>) -> String {
let stringRange = index(startIndex, offsetBy: range.lowerBound)..<index(startIndex, offsetBy: range.upperBound)
return String(self[stringRange])
}
}
extension String.UTF8View {
subscript(range: Range<Int>) -> String {
let stringRange = index(startIndex, offsetBy: range.lowerBound)..<index(startIndex, offsetBy: range.upperBound)
let subsequence: String.UTF8View.SubSequence = self[stringRange]
return String(subsequence) ?? ""
}
}
extension String {
func regexMatches(_ source: String) -> Bool {
let regex = try! NSRegularExpression(pattern: self)
return regex.firstMatch(in: source, range: NSRange(location: 0, length: source.count)) != nil
}
}
extension Sequence {
#if !swift(>=4.1)
public func compactMap<O>(_ transform: (Element) -> O?) -> [O] {
return self.flatMap(transform)
}
#endif
func only<T>(_ type: T.Type) -> [T] {
return compactMap { $0 as? T }
}
func noneOf<T>(_ type: T.Type) -> [Iterator.Element] {
return filter { !($0 is T) }
}
}
internal func extractRange(from dictionary: [String: SourceKitRepresentable], offset: Key, length: Key) -> CountableRange<Int>? {
guard let offset = (dictionary[offset.rawValue] as? Int64).map(Int.init),
let length = (dictionary[length.rawValue] as? Int64).map(Int.init) else { return nil }
return offset..<offset.advanced(by: length)
}
| mit | 750fe8d28aa391dd515cdcb23be16b6e | 29.078125 | 129 | 0.658701 | 3.985507 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/AudioAnalyzerExample/Controller/AudioAnalyzerExampleViewController.swift | 1 | 5289 | //
// AudioAnalyzerExampleViewController.swift
// SciChartShowcaseDemo
//
// Created by Yaroslav Pelyukh on 2/26/17.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import Foundation
import UIKit
import SciChart
//typealias updateDataSeriesDelegate = (_ dataSeries: SCIXyDataSeries ) -> Void
class AudioAnalyzerExampleViewController: BaseViewController {
var audioWaveformController: AudioWaveformSurfaceController!
var fftFormController: FFTFormSurfaceController!
var spectrogramFormController: SpectogramSurfaceController!
var displaylink : CADisplayLink!
@IBOutlet weak var audioWaveFormChartView: SCIChartSurface!
@IBOutlet weak var fftChartView: SCIChartSurface!
@IBOutlet weak var spectrogramChartView: SCIChartSurface!
var imageAudioWave: UIImage?
let audioRecorderDataManager:AudioRecorder = AudioRecorder()
override func viewDidLoad() {
super.viewDidLoad()
createSurfaceControllers()
subscribeSurfaceDelegates()
audioRecorderDataManager.startRecording()
displaylink = CADisplayLink(target: self, selector: #selector(updateData))
displaylink.add(to: .current, forMode: .defaultRunLoopMode)
let barButton = UIBarButtonItem(title: "FFT Settings", style: .plain, target: self, action: #selector(changeMaxHzFft))
navigationItem.setRightBarButton(barButton, animated: true)
}
@IBAction func changeMaxHzFft(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "Select Max Hz For", message: "", preferredStyle: .actionSheet)
let varies = ["22 kHz", "10 kHz", "5 kHz", "1 kHz"]
for i in 0..<4 {
let title = varies[i]
let actionTheme = UIAlertAction(title: title, style: .default, handler: { (action: UIAlertAction) -> Void in
if i == 0 {
self.fftFormController.setMaxHz(maxValue: 22000)
}
if i == 1 {
self.fftFormController.setMaxHz(maxValue: 10000)
}
if i == 2 {
self.fftFormController.setMaxHz(maxValue: 5000)
}
if i == 3 {
self.fftFormController.setMaxHz(maxValue: 1000)
}
})
alertController.addAction(actionTheme)
}
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
if let controller = alertController.popoverPresentationController {
controller.sourceView = view
controller.barButtonItem = sender
}
navigationController?.present(alertController, animated: true, completion: nil)
}
@objc func updateData(displayLink: CADisplayLink) {
audioWaveformController.updateData(displayLink: displayLink)
fftFormController.updateData(displayLink: displayLink)
spectrogramFormController.updateData(displayLink: displayLink)
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = false
}
func makeScreenshot() {
UIImageWriteToSavedPhotosAlbum(audioWaveformController.chartSurface.exportToUIImage(), self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
UIImageWriteToSavedPhotosAlbum(fftFormController.chartSurface.exportToUIImage(), self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
UIImageWriteToSavedPhotosAlbum(spectrogramFormController.chartSurface.exportToUIImage(), self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
audioRecorderDataManager.stopRecording()
displaylink.invalidate()
displaylink = nil
}
private func createSurfaceControllers() {
audioWaveformController = AudioWaveformSurfaceController(audioWaveFormChartView)
fftFormController = FFTFormSurfaceController(fftChartView)
spectrogramFormController = SpectogramSurfaceController(spectrogramChartView)
}
private func subscribeSurfaceDelegates(){
audioRecorderDataManager.sampleToEngineDelegate = audioWaveformController.updateDataSeries
audioRecorderDataManager.fftSamplesDelegate = fftFormController.updateDataSeries
audioRecorderDataManager.spectrogramSamplesDelegate = spectrogramFormController.updateDataSeries
}
}
| mit | fe47e4c324516238f3639a043ef9b9b1 | 40.3125 | 166 | 0.680787 | 5.537173 | false | false | false | false |
teaxus/TSAppEninge | Source/Basic/View/Extension/UITablevViewCell+Extension.swift | 1 | 1682 | //
// UITablevViewCell+Extension.swift
// TSAppEngine
//
// Created by teaxus on 16/1/30.
// Copyright © 2016年 teaxus. All rights reserved.
//
import Foundation
extension UITableViewCell{
public var ts_line_indentation:CGFloat{
set(newValue){
let edge = UIEdgeInsetsMake(0, newValue, 0, 0)
#if swift(>=2.2)
if self.responds(to: #selector(setter: UITableViewCell.separatorInset)){
self.separatorInset = edge
}
if self.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)){
self.preservesSuperviewLayoutMargins = false
}
if self.responds(to: Selector(("setLayoutMargins"))){
self.layoutMargins = edge
}
#else
if self.respondsToSelector("setSeparatorInset:"){
self.separatorInset = edge
}
if self.respondsToSelector("setPreservesSuperviewLayoutMargins:"){
self.preservesSuperviewLayoutMargins = false
}
if self.respondsToSelector("setLayoutMargins:"){
self.layoutMargins = edge
}
#endif
}
get{
return self.separatorInset.left
}
}
public var tableview:UITableView?{
var superview = self.superview
while superview != nil {
if superview is UITableView{
return superview as? UITableView
}
superview = superview?.superview
}
return nil
}
}
| mit | b740f450b0cad0204805864d61a2f220 | 30.092593 | 96 | 0.534247 | 5.809689 | false | false | false | false |
eridbardhaj/Weather | Weather/Classes/Controllers/MainTabBarViewController.swift | 1 | 1578 | //
// MainTabBarViewController.swift
// Weather
//
// Created by Erid Bardhaj on 5/3/15.
// Copyright (c) 2015 STRV. All rights reserved.
//
import UIKit
class MainTabBarViewController: UITabBarController
{
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.changeTabBarItems()
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
//Keep original image, not gray default mode
changeTabBarItems()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Configuration
func changeTabBarItems()
{
var imageNames = ["fc-today", "tod-forecast", "tod-settings"]
var count = 0
for imageName in imageNames
{
var m_tabBarItem: UITabBarItem = self.tabBar.items![count] as! UITabBarItem
var image = UIImage(named: imageName)
m_tabBarItem.image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
count++
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 014a84066221214e88c15d109d055bc4 | 26.206897 | 106 | 0.638783 | 4.900621 | false | false | false | false |
stripe/stripe-ios | StripeCameraCore/StripeCameraCore/Source/Coordinators/Torch.swift | 1 | 1213 | //
// Torch.swift
// StripeCameraCore
//
// Created by Mel Ludowise on 12/1/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import AVFoundation
import Foundation
struct Torch {
enum State {
case off
case on
}
let device: AVCaptureDevice?
var state: State
var lastStateChange: Date
var level: Float
init(
device: AVCaptureDevice
) {
self.state = .off
self.lastStateChange = Date()
if device.hasTorch {
self.device = device
if device.isTorchActive {
self.state = .on
}
} else {
self.device = nil
}
self.level = 1.0
}
mutating func toggle() {
self.state = self.state == .on ? .off : .on
do {
try self.device?.lockForConfiguration()
if self.state == .on {
try self.device?.setTorchModeOn(level: self.level)
} else {
self.device?.torchMode = .off
}
} catch {
// no-op
}
// Always unlock when we're done even if `setTorchModeOn` threw
self.device?.unlockForConfiguration()
}
}
| mit | 4ee2570871422f9df0c5f82e1384710c | 21.867925 | 71 | 0.520627 | 4.375451 | false | false | false | false |
yacir/YBSlantedCollectionViewLayout | Sources/Internal/CollectionViewSlantedLayoutAttributes.swift | 1 | 2002 | /**
This file is part of the CollectionViewSlantedLayout package.
Copyright © 2016-present Yassir Barchi <[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
/// :nodoc:
open class CollectionViewSlantedLayoutAttributes: UICollectionViewLayoutAttributes {
/// :nodoc:
open var slantedLayerMask: CAShapeLayer?
/// :nodoc:
override open func copy(with zone: NSZone?) -> Any {
let attributesCopy = super.copy(with: zone)
if let attributesCopy = attributesCopy as? CollectionViewSlantedLayoutAttributes {
attributesCopy.slantedLayerMask = slantedLayerMask
}
return attributesCopy
}
/// :nodoc:
override open func isEqual(_ object: Any?) -> Bool {
if let obj = object as? CollectionViewSlantedLayoutAttributes {
if slantedLayerMask != obj.slantedLayerMask {
return false
}
return super.isEqual(object)
}
return false
}
}
| mit | fca498da71adf1174308e263b65aac6f | 34.732143 | 90 | 0.724638 | 4.916462 | false | false | false | false |
DikeyKing/WeCenterMobile-iOS | WeCenterMobile/View/Comment/CommentCell.swift | 1 | 2425 | //
// CommentCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/2/3.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class CommentCell: UITableViewCell {
@IBOutlet weak var userAvatarView: MSRRoundedImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var bodyLabel: UILabel!
@IBOutlet weak var userButton: UIButton!
@IBOutlet weak var commentButton: UIButton!
@IBOutlet weak var separator: UIView!
@IBOutlet weak var userContainerView: UIView!
@IBOutlet weak var commentContainerView: UIView!
@IBOutlet weak var containerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
let theme = SettingsManager.defaultManager.currentTheme
msr_scrollView?.delaysContentTouches = false
containerView.msr_borderColor = theme.borderColorA
separator.backgroundColor = theme.borderColorA
for v in [userContainerView, commentContainerView] {
v.backgroundColor = theme.backgroundColorB
}
for v in [userButton, commentButton] {
v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted)
}
userNameLabel.textColor = theme.titleTextColor
}
func update(#comment: Comment) {
msr_userInfo = comment
userAvatarView.wc_updateWithUser(comment.user)
userNameLabel.text = comment.user?.name
var attributedString = NSMutableAttributedString()
let theme = SettingsManager.defaultManager.currentTheme
if comment.atUser?.name != nil {
attributedString.appendAttributedString(NSAttributedString(
string: "@\(comment.atUser!.name!) ",
attributes: [
NSForegroundColorAttributeName: theme.footnoteTextColor,
NSFontAttributeName: bodyLabel.font]))
}
attributedString.appendAttributedString(NSAttributedString(
string: (comment.body ?? ""),
attributes: [
NSForegroundColorAttributeName: theme.bodyTextColor,
NSFontAttributeName: bodyLabel.font]))
bodyLabel.attributedText = attributedString
userButton.msr_userInfo = comment.user
commentButton.msr_userInfo = comment
setNeedsLayout()
layoutIfNeeded()
}
}
| gpl-2.0 | 6ef5d3202c93e5b70d696bcbd6081d0c | 37.460317 | 99 | 0.67272 | 5.796651 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/WMFAppViewController+Extensions.swift | 1 | 11293 | import UIKit
import WMF
import SwiftUI
extension WMFAppViewController {
// MARK: - Language Variant Migration Alerts
@objc internal func presentLanguageVariantAlerts(completion: @escaping () -> Void) {
guard shouldPresentLanguageVariantAlerts else {
completion()
return
}
let savedLibraryVersion = UserDefaults.standard.integer(forKey: WMFLanguageVariantAlertsLibraryVersion)
guard savedLibraryVersion < MWKDataStore.currentLibraryVersion else {
completion()
return
}
let languageCodesNeedingAlerts = self.dataStore.languageCodesNeedingVariantAlerts(since: savedLibraryVersion)
guard let firstCode = languageCodesNeedingAlerts.first else {
completion()
return
}
self.presentVariantAlert(for: firstCode, remainingCodes: Array(languageCodesNeedingAlerts.dropFirst()), completion: completion)
UserDefaults.standard.set(MWKDataStore.currentLibraryVersion, forKey: WMFLanguageVariantAlertsLibraryVersion)
}
private func presentVariantAlert(for languageCode: String, remainingCodes: [String], completion: @escaping () -> Void) {
let primaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler
let secondaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler?
// If there are remaining codes
if let nextCode = remainingCodes.first {
// If more to show, primary button shows next variant alert
primaryButtonTapHandler = { _ in
self.dismiss(animated: true) {
self.presentVariantAlert(for: nextCode, remainingCodes: Array(remainingCodes.dropFirst()), completion: completion)
}
}
// And no secondary button
secondaryButtonTapHandler = nil
} else {
// If no more to show, primary button navigates to languge settings
primaryButtonTapHandler = { _ in
self.displayPreferredLanguageSettings(completion: completion)
}
// And secondary button dismisses
secondaryButtonTapHandler = { _ in
self.dismiss(animated: true, completion: completion)
}
}
let alert = LanguageVariantEducationalPanelViewController(primaryButtonTapHandler: primaryButtonTapHandler, secondaryButtonTapHandler: secondaryButtonTapHandler, dismissHandler: nil, theme: self.theme, languageCode: languageCode)
self.present(alert, animated: true, completion: nil)
}
// Don't present over modals or navigation stacks
// The user is deep linking in these states and we don't want to interrupt them
private var shouldPresentLanguageVariantAlerts: Bool {
guard presentedViewController == nil,
let navigationController = navigationController,
navigationController.viewControllers.count == 1 &&
navigationController.viewControllers[0] is WMFAppViewController else {
return false
}
return true
}
private func displayPreferredLanguageSettings(completion: @escaping () -> Void) {
self.dismissPresentedViewControllers()
let languagesVC = WMFPreferredLanguagesViewController.preferredLanguagesViewController()
languagesVC.showExploreFeedCustomizationSettings = true
languagesVC.userDismissalCompletionBlock = completion
languagesVC.apply(self.theme)
let navVC = WMFThemeableNavigationController(rootViewController: languagesVC, theme: theme)
present(navVC, animated: true, completion: nil)
}
}
// MARK: Notifications
extension WMFAppViewController: SettingsPresentationDelegate {
public func userDidTapSettings(from viewController: UIViewController?) {
if viewController is ExploreViewController {
logTappedSettingsFromExplore()
}
showSettings(animated: true)
}
}
extension WMFAppViewController: NotificationsCenterPresentationDelegate {
/// Perform conditional presentation logic depending on origin `UIViewController`
public func userDidTapNotificationsCenter(from viewController: UIViewController? = nil) {
let viewModel = NotificationsCenterViewModel(notificationsController: dataStore.notificationsController, remoteNotificationsController: dataStore.remoteNotificationsController, languageLinkController: self.dataStore.languageLinkController)
let notificationsCenterViewController = NotificationsCenterViewController(theme: theme, viewModel: viewModel)
navigationController?.pushViewController(notificationsCenterViewController, animated: true)
}
}
extension WMFAppViewController {
@objc func userDidTapPushNotification() {
guard let topMostViewController = self.topMostViewController else {
return
}
// If already displaying Notifications Center (or some part of it), exit early
if let notificationsCenterFlowViewController = topMostViewController.notificationsCenterFlowViewController {
notificationsCenterFlowViewController.tappedPushNotification()
return
}
let viewModel = NotificationsCenterViewModel(notificationsController: dataStore.notificationsController, remoteNotificationsController: dataStore.remoteNotificationsController, languageLinkController: dataStore.languageLinkController)
let notificationsCenterViewController = NotificationsCenterViewController(theme: theme, viewModel: viewModel)
let dismissAndPushBlock = { [weak self] in
self?.dismissPresentedViewControllers()
self?.navigationController?.pushViewController(notificationsCenterViewController, animated: true)
}
guard let editingFlowViewController = editingFlowViewControllerInHierarchy,
editingFlowViewController.shouldDisplayExitConfirmationAlert else {
dismissAndPushBlock()
return
}
presentEditorAlert(on: topMostViewController, confirmationBlock: dismissAndPushBlock)
}
var editingFlowViewControllerInHierarchy: EditingFlowViewController? {
var currentController: UIViewController? = navigationController
while let presentedViewController = currentController?.presentedViewController {
if let presentedNavigationController = (presentedViewController as? UINavigationController) {
for viewController in presentedNavigationController.viewControllers {
if let editingFlowViewController = viewController as? EditingFlowViewController {
return editingFlowViewController
}
}
} else if let editingFlowViewController = presentedViewController as? EditingFlowViewController {
return editingFlowViewController
}
currentController = presentedViewController
}
return nil
}
private var topMostViewController: UIViewController? {
var topViewController: UIViewController = navigationController ?? self
while let presentedViewController = topViewController.presentedViewController {
topViewController = presentedViewController
}
return topViewController
}
private func presentEditorAlert(on viewController: UIViewController, confirmationBlock: @escaping () -> Void) {
let title = CommonStrings.editorExitConfirmationTitle
let message = CommonStrings.editorExitConfirmationBody
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let discardAction = UIAlertAction(title: CommonStrings.discardEditsActionTitle, style: .destructive) { _ in
confirmationBlock()
}
let cancelAction = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel)
alertController.addAction(discardAction)
alertController.addAction(cancelAction)
viewController.present(alertController, animated: true, completion: nil)
}
}
fileprivate extension UIViewController {
/// Returns self or embedded view controller (if self is a UINavigationController) if conforming to NotificationsCenterFlowViewController
/// Does not consider presenting view controllers
var notificationsCenterFlowViewController: NotificationsCenterFlowViewController? {
if let viewController = self as? NotificationsCenterFlowViewController {
return viewController
}
if let navigationController = self as? UINavigationController,
let viewController = navigationController.viewControllers.last as? NotificationsCenterFlowViewController {
return viewController
}
return nil
}
}
/// View Controllers that have an editing element (Section editor flow, User talk pages, Article description editor)
protocol EditingFlowViewController where Self: UIViewController {
var shouldDisplayExitConfirmationAlert: Bool { get }
}
extension EditingFlowViewController {
var shouldDisplayExitConfirmationAlert: Bool {
return true
}
}
/// View Controllers that are a part of the Notifications Center flow
protocol NotificationsCenterFlowViewController where Self: UIViewController {
// hook called after the user taps a push notification while in the foregound.
// use if needed to tweak the view heirarchy to display the Notifications Center
func tappedPushNotification()
}
// MARK: Importing Reading Lists - CreateReadingListDelegate
extension WMFAppViewController: CreateReadingListDelegate {
func createReadingListViewController(_ createReadingListViewController: CreateReadingListViewController, didCreateReadingListWith name: String, description: String?, articles: [WMFArticle]) {
guard !articles.isEmpty else {
WMFAlertManager.sharedInstance.showErrorAlert(ImportReadingListError.missingArticles, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
return
}
do {
createReadingListViewController.createReadingListButton.isEnabled = false
let readingList = try dataStore.readingListsController.createReadingList(named: name, description: description, with: articles)
ReadingListsFunnel.shared.logCompletedImport(articlesCount: articles.count)
showImportedReadingList(readingList)
} catch let error {
switch error {
case let readingListError as ReadingListError where readingListError == .listExistsWithTheSameName:
createReadingListViewController.handleReadingListNameError(readingListError)
default:
WMFAlertManager.sharedInstance.showErrorAlert(error, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
createReadingListViewController.createReadingListButton.isEnabled = true
}
}
}
}
| mit | eedbf8b2f2b96e9fa00abb496921da39 | 42.771318 | 247 | 0.708226 | 6.682249 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.