repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
exchangegroup/FitLoader | refs/heads/master | Demo/Core/Http/TegRequestUrl.swift | mit | 2 | //
// The struct keeps URL to the server.
//
import Foundation
public struct TegRequestUrl {
private func host(type: TegRequestType) -> String {
switch type {
case .MyAccount:
return "http://httpstat.us"
case .Error422:
return "https://yaushop.com"
default:
return "https://dl.dropboxusercontent.com"
}
}
public func url(requestType: TegRequestType, params: [String: String]?) -> String {
let urlPath = TegRequestUrl.makePath(requestType, values: params)
return "\(host(requestType))/\(urlPath)"
}
public static func makePath(requestType: TegRequestType, values: [String: String]?) -> String {
var url = requestType.rawValue
if let values = values {
for (name, value) in values {
let encodedValue = TegUrlEncoder.encodeUrlParameter(value)
url = url.stringByReplacingOccurrencesOfString("{\(name)}", withString: encodedValue)
}
}
return url
}
} | 19b8fd3e8008a1a0fc681afc353756c3 | 24.783784 | 97 | 0.663169 | false | false | false | false |
siberianisaev/NeutronBarrel | refs/heads/master | NeutronBarrel/StripDetectorManager.swift | mit | 1 | //
// StripDetectorManager.swift
// NeutronBarrel
//
// Created by Andrey Isaev on 02/02/2019.
// Copyright © 2019 Flerov Laboratory. All rights reserved.
//
import Foundation
enum StripDetector {
case focal
case side
// TODO: refactoring, extract encoder/channel conversion logic from strips config
case neutron
/*
mkm
*/
func deadLayer() -> CGFloat {
switch self {
case .focal:
return 0.1
case .side:
return 0.3
default:
return 0.0
}
}
}
class StripDetectorManager {
fileprivate var stripsConfigurations = [StripDetector: StripsConfiguration]()
func setStripConfiguration(_ config: StripsConfiguration, detector: StripDetector) {
stripsConfigurations[detector] = config
}
func getStripConfigurations(_ detector: StripDetector) -> StripsConfiguration {
if let sc = stripsConfigurations[detector] {
return sc
}
// Default Config
let sc = StripsConfiguration(detector: detector)
setStripConfiguration(sc, detector: detector)
return sc
}
func reset() {
stripsConfigurations.removeAll()
}
class var singleton : StripDetectorManager {
struct Static {
static let sharedInstance : StripDetectorManager = StripDetectorManager()
}
return Static.sharedInstance
}
class func cleanStripConfigs() {
StripDetectorManager.singleton.stripsConfigurations.removeAll()
}
}
| 034e1c2cb4c996253818e56ee38148db | 23.307692 | 88 | 0.625316 | false | true | false | false |
HamzaGhazouani/HGPlaceholders | refs/heads/master | HGPlaceholders/Classes/Views/TableView.swift | mit | 1 | //
// TableView.swift
// Pods
//
// Created by Hamza Ghazouani on 20/07/2017.
//
//
import UIKit
/// The delegate of a TableView/CollectionView object must adopt the PlaceholderDelegate protocol. the method of the protocol allow the delegate to perform placeholders action.
public protocol PlaceholderDelegate: AnyObject {
/// Performs the action to the delegate of the table or collection view
///
/// - Parameters:
/// - view: the table view or the collection
/// - placeholder: The placeholder source of the action
func view(_ view: Any, actionButtonTappedFor placeholder: Placeholder)
}
/// A table view that allows to show easily placeholders like no results, no internet connection, etc
open class TableView: UITableView {
// MARK: - Public properties
/// The placeholdersProvider property is responsible for the placeholders views and data
final public var placeholdersProvider = PlaceholdersProvider.default {
willSet {
/// before changing the placeholders data, we should be sure that the tableview is in the default configuration. Otherwise If the dataSource and the delegate are in placeholder configuration, and we set the new data, the old one will be released and we will lose the defaultDataSource and defaultDelegate (they will be set to nil)
showDefault()
}
}
/**
* The object that acts as the delegate of the table view placeholders.
* The delegate must adopt the PlaceholderDelegate protocol. The delegate is not retained.
*/
public weak var placeholderDelegate: PlaceholderDelegate?
/**
* The object that acts as the data source of the table view.
* The data source must adopt the UITableViewDataSource protocol. The data source is not retained.
*/
weak open override var dataSource: UITableViewDataSource? {
didSet {
/* we save only the initial data source (and not a placeholder datasource) to allow to go back to the initial data */
if dataSource is PlaceholderDataSourceDelegate {
return
}
defaultDataSource = dataSource
}
}
/**
* The object that acts as the delegate of the table view.
* The delegate must adopt the UITableViewDelegate protocol. The delegate is not retained.
*/
open override weak var delegate: UITableViewDelegate? {
didSet {
/* we save only the initial delegate (and not the placeholder delegate) to allow to go back to the initial one */
if delegate is PlaceholderDataSourceDelegate {
return
}
defaultDelegate = delegate
}
}
/**
* Returns an accessory view that is displayed above the table.
* The default value is nil. The table header view is different from a section header.
*/
open override var tableHeaderView: UIView? {
didSet {
if tableHeaderView == nil {
return
}
defaultTableHeaderView = tableHeaderView
}
}
/**
* Returns an accessory view that is displayed below the table.
* The default value is nil. The table footer view is different from a section footer.
*/
open override var tableFooterView: UIView? {
didSet {
if tableFooterView == nil { return }
defaultTableFooterView = tableFooterView
}
}
/**
* Keeps user seperatorStyle instead of overriding with system default
* The default value is UITableViewCellSeparatorStyle.singleLine
*/
open override var separatorStyle: UITableViewCell.SeparatorStyle {
didSet {
defaultSeparatorStyle = separatorStyle
}
}
/**
* A Boolean value that determines whether bouncing always occurs when the placeholder is shown.
* The default value is false
*/
open var placeholdersAlwaysBounceVertical = false
// MARK: - Private properties
/// The defaultDataSource is used to allow to go back to the initial data source of the table view after switching to a placeholder data source
internal weak var defaultDataSource: UITableViewDataSource?
/// The defaultDelegate is used to allow to go back to the initial delegate of the table view after switching to a placeholder delegate
internal weak var defaultDelegate: UITableViewDelegate?
/// The defaultSeparatorStyle is used to save the tableview separator style, because, when you switch to a placeholder, is changed to `.none`
fileprivate var defaultSeparatorStyle: UITableViewCell.SeparatorStyle!
/// The defaultAlwaysBounceVertical is used to save the tableview bouncing setup, because, when you switch to a placeholder, the vertical bounce is disabled
fileprivate var defaultAlwaysBounceVertical: Bool!
/// The defaultTableViewHeader is used to save the tableview header when you switch to placeholders
fileprivate var defaultTableHeaderView: UIView?
/// The defaultTableViewFooter is used to save the tableview footer when you switch to placeholders
fileprivate var defaultTableFooterView: UIView?
// MARK: - init methods
/**
Returns an table view initialized from data in a given unarchiver.
- parameter aDecoder: An unarchiver object.
- returns: self, initialized using the data in decoder.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Initializes and returns a table view object having the given frame and style.
Returns an initialized TableView object, or nil if the object could not be successfully initialized.
- parameter frame: A rectangle specifying the initial location and size of the table view in its superview’s coordinates. The frame of the table view changes as table cells are added and deleted.
- parameter style: A constant that specifies the style of the table view. See Table View Style for descriptions of valid constants.
- returns: Returns an initialized TableView object, or nil if the object could not be successfully initialized.
*/
override public init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
setup()
}
/**
* Config the table view to be able to show placeholders
*/
private func setup() {
// register the placeholder view cell
register(cellType: PlaceholderTableViewCell.self)
defaultSeparatorStyle = separatorStyle
defaultAlwaysBounceVertical = alwaysBounceVertical
defaultTableHeaderView = tableHeaderView
defaultTableFooterView = tableFooterView
customSetup()
}
/// Implement this method of you want to add new default placeholdersProvider, new default cell, etc
open func customSetup() {}
// MARK: - Manage table view data and placeholders
/**
Switch to different data sources and delegate of the table view (placeholders and initial data source & delegate)
- parameter theSource: the selected data source
- parameter theDelegate: the selected delegate
*/
internal func switchTo(dataSource theDataSource: UITableViewDataSource?, delegate theDelegate: UITableViewDelegate? = nil) {
// if the data source and delegate are already set, no need to switch
if dataSource === theDataSource && delegate === theDelegate {
return
}
if let placeholderDataSource = theDataSource as? PlaceholderDataSourceDelegate {
// placeholder configuration
super.separatorStyle = .none
alwaysBounceVertical = placeholdersAlwaysBounceVertical
let style = placeholderDataSource.placeholder.style
if style?.shouldShowTableViewHeader != true { // style = nil or shouldShowTableViewHeader == false
tableHeaderView = nil
}
if style?.shouldShowTableViewFooter != true {
tableFooterView = nil
}
}
else {
// default configuration
separatorStyle = defaultSeparatorStyle
alwaysBounceVertical = defaultAlwaysBounceVertical
tableHeaderView = defaultTableHeaderView
tableFooterView = defaultTableFooterView
}
dataSource = theDataSource
delegate = theDelegate
super.reloadData()
}
/// The total number of rows in all sections of the tableView
private func numberOfRowsInAllSections() -> Int {
let numberOfSections = defaultDataSource?.numberOfSections?(in: self) ?? 1
var rows = 0
for i in 0 ..< numberOfSections {
rows += defaultDataSource?.tableView(self, numberOfRowsInSection: i) ?? 0
}
return rows
}
/**
Reloads the rows and sections of the table view.
If the number of rows == 0 it shows no results placeholder
*/
open override func reloadData() {
// if the tableview is empty we switch automatically to no data placeholder
if numberOfRowsInAllSections() == 0 {
showNoResultsPlaceholder()
return
}
// if the data source is in no data placeholder, and the user tries to reload data, we will switch automatically to default
if dataSource is PlaceholderDataSourceDelegate {
showDefault()
return
}
super.reloadData()
}
/**
Called when the adjusted content insets of the scroll view change.
*/
open override func adjustedContentInsetDidChange() {
if dataSource is PlaceholderDataSourceDelegate {
// Force table view to recalculate the cell height, because the method tableView:heightForRowAt: is called before adjusting the content of the scroll view
guard let indexPaths = indexPathsForVisibleRows else { return }
reloadRows(at: indexPaths, with: .automatic)
}
}
}
extension UITableView {
/**
Register a NIB-Based `UITableViewCell` subclass (conforming to `Reusable` & `NibLoadable`)
- parameter cellType: the `UITableViewCell` (`Reusable` & `NibLoadable`-conforming) subclass to register
- seealso: `register(_:,forCellReuseIdentifier:)`
*/
final func register<T: UITableViewCell>(cellType: T.Type)
where T: Reusable & NibLoadable {
self.register(cellType.nib, forCellReuseIdentifier: cellType.reuseIdentifier)
}
}
| 09f75e24b0d1c631f610245427e99d7a | 38.599265 | 342 | 0.665026 | false | false | false | false |
zapdroid/RXWeather | refs/heads/master | Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift | mit | 1 | //
// Sink.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
class Sink<O: ObserverType>: Disposable {
fileprivate let _observer: O
fileprivate let _cancel: Cancelable
fileprivate var _disposed: Bool
#if DEBUG
fileprivate var _numberOfConcurrentCalls: AtomicInt = 0
#endif
init(observer: O, cancel: Cancelable) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
_observer = observer
_cancel = cancel
_disposed = false
}
final func forwardOn(_ event: Event<O.E>) {
#if DEBUG
if AtomicIncrement(&_numberOfConcurrentCalls) > 1 {
rxFatalError("Warning: Recursive call or synchronization error!")
}
defer {
_ = AtomicDecrement(&_numberOfConcurrentCalls)
}
#endif
if _disposed {
return
}
_observer.on(event)
}
final func forwarder() -> SinkForward<O> {
return SinkForward(forward: self)
}
final var disposed: Bool {
return _disposed
}
func dispose() {
_disposed = true
_cancel.dispose()
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
final class SinkForward<O: ObserverType>: ObserverType {
typealias E = O.E
private let _forward: Sink<O>
init(forward: Sink<O>) {
_forward = forward
}
final func on(_ event: Event<E>) {
switch event {
case .next:
_forward._observer.on(event)
case .error, .completed:
_forward._observer.on(event)
_forward._cancel.dispose()
}
}
}
| abda847ef57726129ffea62dbb145416 | 21.246914 | 81 | 0.552719 | false | false | false | false |
lemonkey/iOS | refs/heads/master | WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/ListerKit/CloudListCoordinator.swift | mit | 1 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `CloudListCoordinator` class handles querying for and interacting with lists stored as files in iCloud Drive.
*/
import Foundation
@objc public class CloudListCoordinator: ListCoordinator {
// MARK: Properties
public weak var delegate: ListCoordinatorDelegate?
/// Closure executed after the first update provided by the coordinator regarding tracked URLs.
private var firstQueryUpdateHandler: (Void -> Void)?
/// Initialized asynchronously in init(predicate:).
private var _documentsDirectory: NSURL!
private var documentsDirectory: NSURL {
var documentsDirectory: NSURL!
dispatch_sync(documentsDirectoryQueue) {
documentsDirectory = self._documentsDirectory
}
return documentsDirectory
}
private var metadataQuery: NSMetadataQuery
/// A private, local queue to `CloudListCoordinator` that is used to ensure serial accesss to `documentsDirectory`.
private let documentsDirectoryQueue = dispatch_queue_create("com.example.apple-samplecode.lister.cloudlistcoordinator", DISPATCH_QUEUE_CONCURRENT)
// MARK: Initializers
public convenience init(pathExtension: String, firstQueryUpdateHandler: (Void -> Void)? = nil) {
let predicate = NSPredicate(format: "(%K.pathExtension = %@)", argumentArray: [NSMetadataItemURLKey, pathExtension])
self.init(predicate: predicate, firstQueryUpdateHandler: firstQueryUpdateHandler)
}
public convenience init(lastPathComponent: String, firstQueryUpdateHandler: (Void -> Void)? = nil) {
let predicate = NSPredicate(format: "(%K.lastPathComponent = %@)", argumentArray: [NSMetadataItemURLKey, lastPathComponent])
self.init(predicate: predicate, firstQueryUpdateHandler: firstQueryUpdateHandler)
}
private init(predicate: NSPredicate, firstQueryUpdateHandler: (Void -> Void)?) {
self.firstQueryUpdateHandler = firstQueryUpdateHandler
metadataQuery = NSMetadataQuery()
// These search scopes search for files in iCloud Drive.
metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope, NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope]
metadataQuery.predicate = predicate
dispatch_barrier_async(documentsDirectoryQueue) {
let cloudContainerURL = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)
self._documentsDirectory = cloudContainerURL?.URLByAppendingPathComponent("Documents")
}
// Observe the query.
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "metadataQueryDidFinishGathering:", name: NSMetadataQueryDidFinishGatheringNotification, object: metadataQuery)
notificationCenter.addObserver(self, selector: "metadataQueryDidUpdate:", name: NSMetadataQueryDidUpdateNotification, object: metadataQuery)
}
// MARK: Lifetime
deinit {
// Stop observing the query.
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: NSMetadataQueryDidFinishGatheringNotification, object: metadataQuery)
notificationCenter.removeObserver(self, name: NSMetadataQueryDidUpdateNotification, object: metadataQuery)
}
// MARK: ListCoordinator
public func startQuery() {
// `NSMetadataQuery` should always be started on the main thread.
dispatch_async(dispatch_get_main_queue()) {
self.metadataQuery.startQuery()
return
}
}
public func stopQuery() {
// `NSMetadataQuery` should always be stopped on the main thread.
dispatch_async(dispatch_get_main_queue()) {
self.metadataQuery.stopQuery()
}
}
public func createURLForList(list: List, withName name: String) {
let documentURL = documentURLForName(name)
ListUtilities.createList(list, atURL: documentURL) { error in
if let realError = error {
self.delegate?.listCoordinatorDidFailCreatingListAtURL(documentURL, withError: realError)
}
else {
self.delegate?.listCoordinatorDidUpdateContents(insertedURLs: [documentURL], removedURLs: [], updatedURLs: [])
}
}
}
public func canCreateListWithName(name: String) -> Bool {
if name.isEmpty {
return false
}
let documentURL = documentURLForName(name)
return !NSFileManager.defaultManager().fileExistsAtPath(documentURL.path!)
}
public func removeListAtURL(URL: NSURL) {
ListUtilities.removeListAtURL(URL) { error in
if let realError = error {
self.delegate?.listCoordinatorDidFailRemovingListAtURL(URL, withError: realError)
}
else {
self.delegate?.listCoordinatorDidUpdateContents(insertedURLs: [], removedURLs: [URL], updatedURLs: [])
}
}
}
// MARK: NSMetadataQuery Notifications
@objc private func metadataQueryDidFinishGathering(notifcation: NSNotification) {
metadataQuery.disableUpdates()
let metadataItems = metadataQuery.results as! [NSMetadataItem]
let insertedURLs = metadataItems.map { $0.valueForAttribute(NSMetadataItemURLKey) as! NSURL }
delegate?.listCoordinatorDidUpdateContents(insertedURLs: insertedURLs, removedURLs: [], updatedURLs: [])
metadataQuery.enableUpdates()
// Execute the `firstQueryUpdateHandler`, it will contain the closure from initialization on first update.
if let handler = firstQueryUpdateHandler {
handler()
// Set `firstQueryUpdateHandler` to an empty closure so that the handler provided is only run on first update.
firstQueryUpdateHandler = nil
}
}
/**
Private methods that are used with Objective-C for notifications, target / action, etc. should
be marked as @objc.
*/
@objc private func metadataQueryDidUpdate(notification: NSNotification) {
metadataQuery.disableUpdates()
var insertedURLs = [NSURL]()
var removedURLs = [NSURL]()
var updatedURLs = [NSURL]()
let metadataItemToURLTransform: NSMetadataItem -> NSURL = { metadataItem in
return metadataItem.valueForAttribute(NSMetadataItemURLKey) as! NSURL
}
let insertedMetadataItemsOrNil: AnyObject? = notification.userInfo?[NSMetadataQueryUpdateAddedItemsKey]
if let insertedMetadataItems = insertedMetadataItemsOrNil as? [NSMetadataItem] {
insertedURLs += insertedMetadataItems.map(metadataItemToURLTransform)
}
let removedMetadataItemsOrNil: AnyObject? = notification.userInfo?[NSMetadataQueryUpdateRemovedItemsKey]
if let removedMetadataItems = removedMetadataItemsOrNil as? [NSMetadataItem] {
removedURLs += removedMetadataItems.map(metadataItemToURLTransform)
}
let updatedMetadataItemsOrNil: AnyObject? = notification.userInfo?[NSMetadataQueryUpdateChangedItemsKey]
if let updatedMetadataItems = updatedMetadataItemsOrNil as? [NSMetadataItem] {
let completelyDownloadedUpdatedMetadataItems = updatedMetadataItems.filter { updatedMetadataItem in
let downloadStatus = updatedMetadataItem.valueForAttribute(NSMetadataUbiquitousItemDownloadingStatusKey) as! String
return downloadStatus == NSMetadataUbiquitousItemDownloadingStatusCurrent
}
updatedURLs += completelyDownloadedUpdatedMetadataItems.map(metadataItemToURLTransform)
}
delegate?.listCoordinatorDidUpdateContents(insertedURLs: insertedURLs, removedURLs: removedURLs, updatedURLs: updatedURLs)
metadataQuery.enableUpdates()
}
// MARK: Convenience
private func documentURLForName(name: String) -> NSURL {
let documentURLWithoutExtension = documentsDirectory.URLByAppendingPathComponent(name)
return documentURLWithoutExtension.URLByAppendingPathExtension(AppConfiguration.listerFileExtension)
}
}
| 6c5da29b97397992f1c2180fe5c68351 | 40.823529 | 166 | 0.690577 | false | false | false | false |
vmanot/swift-package-manager | refs/heads/master | Sources/PackageGraph/RepositoryPackageContainerProvider.swift | apache-2.0 | 1 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Dispatch
import Basic
import PackageLoading
import PackageModel
import SourceControl
import class PackageDescription4.Package
import Utility
/// Adaptor for exposing repositories as PackageContainerProvider instances.
///
/// This is the root class for bridging the manifest & SCM systems into the
/// interfaces used by the `DependencyResolver` algorithm.
public class RepositoryPackageContainerProvider: PackageContainerProvider {
public typealias Container = BasePackageContainer
let repositoryManager: RepositoryManager
let manifestLoader: ManifestLoaderProtocol
/// The tools version currently in use. Only the container versions less than and equal to this will be provided by
/// the container.
let currentToolsVersion: ToolsVersion
/// The tools version loader.
let toolsVersionLoader: ToolsVersionLoaderProtocol
/// Queue for callbacks.
private let callbacksQueue = DispatchQueue(label: "org.swift.swiftpm.container-provider")
/// Create a repository-based package provider.
///
/// - Parameters:
/// - repositoryManager: The repository manager responsible for providing repositories.
/// - manifestLoader: The manifest loader instance.
/// - currentToolsVersion: The current tools version in use.
/// - toolsVersionLoader: The tools version loader.
public init(
repositoryManager: RepositoryManager,
manifestLoader: ManifestLoaderProtocol,
currentToolsVersion: ToolsVersion = ToolsVersion.currentToolsVersion,
toolsVersionLoader: ToolsVersionLoaderProtocol = ToolsVersionLoader()
) {
self.repositoryManager = repositoryManager
self.manifestLoader = manifestLoader
self.currentToolsVersion = currentToolsVersion
self.toolsVersionLoader = toolsVersionLoader
}
public func getContainer(
for identifier: Container.Identifier,
skipUpdate: Bool,
completion: @escaping (Result<Container, AnyError>) -> Void
) {
// If the container is local, just create and return a local package container.
if identifier.isLocal {
callbacksQueue.async {
let container = LocalPackageContainer(identifier,
manifestLoader: self.manifestLoader,
toolsVersionLoader: self.toolsVersionLoader,
currentToolsVersion: self.currentToolsVersion)
completion(Result(container))
}
return
}
// Resolve the container using the repository manager.
repositoryManager.lookup(repository: identifier.repository, skipUpdate: skipUpdate) { result in
// Create the container wrapper.
let container = result.mapAny { handle -> Container in
// Open the repository.
//
// FIXME: Do we care about holding this open for the lifetime of the container.
let repository = try handle.open()
return RepositoryPackageContainer(
identifier: identifier,
repository: repository,
manifestLoader: self.manifestLoader,
toolsVersionLoader: self.toolsVersionLoader,
currentToolsVersion: self.currentToolsVersion
)
}
completion(container)
}
}
}
enum RepositoryPackageResolutionError: Swift.Error {
/// A requested repository could not be cloned.
case unavailableRepository
}
/// A package reference.
///
/// This represents a reference to a package containing its identity and location.
public struct PackageReference: PackageContainerIdentifier, JSONMappable, JSONSerializable {
/// Compute identity of a package given its URL.
public static func computeIdentity(packageURL: String) -> String {
// Get the last path component of the URL.
var lastComponent = packageURL.split(separator: "/", omittingEmptySubsequences: true).last!
// Strip `.git` suffix if present.
//
// FIXME: We need String() here because of https://bugs.swift.org/browse/SR-5627
if String(lastComponent).hasSuffix(".git") {
lastComponent = lastComponent[...lastComponent.index(lastComponent.endIndex, offsetBy: -5)]
}
return String(lastComponent).lowercased()
}
/// The identity of the package.
public let identity: String
/// The repository of the package.
///
/// This should only be accessed when the reference is not local.
public var repository: RepositorySpecifier {
precondition(!isLocal)
return RepositorySpecifier(url: path)
}
/// The path of the package.
///
/// This could be a remote repository, local repository or local package.
public let path: String
/// The package reference is a local package, i.e., it does not reference
/// a git repository.
public let isLocal: Bool
/// Create a package reference given its identity and repository.
public init(identity: String, path: String, isLocal: Bool = false) {
assert(identity == identity.lowercased(), "The identity is expected to be lowercased")
self.identity = identity
self.path = path
self.isLocal = isLocal
}
public static func ==(lhs: PackageReference, rhs: PackageReference) -> Bool {
return lhs.identity == rhs.identity
}
public var hashValue: Int {
return identity.hashValue
}
public init(json: JSON) throws {
self.identity = try json.get("identity")
self.path = try json.get("path")
self.isLocal = try json.get("isLocal")
}
public func toJSON() -> JSON {
return .init([
"identity": identity,
"path": path,
"isLocal": isLocal,
])
}
}
public typealias RepositoryPackageConstraint = PackageContainerConstraint<PackageReference>
/// Base class for the package container.
public class BasePackageContainer: PackageContainer {
public typealias Identifier = PackageReference
public let identifier: Identifier
/// The manifest loader.
let manifestLoader: ManifestLoaderProtocol
/// The tools version loader.
let toolsVersionLoader: ToolsVersionLoaderProtocol
/// The current tools version in use.
let currentToolsVersion: ToolsVersion
public func versions(filter isIncluded: (Version) -> Bool) -> AnySequence<Version> {
fatalError("This should never be called")
}
public func getDependencies(at version: Version) throws -> [PackageContainerConstraint<Identifier>] {
fatalError("This should never be called")
}
public func getDependencies(at revision: String) throws -> [PackageContainerConstraint<Identifier>] {
fatalError("This should never be called")
}
public func getUnversionedDependencies() throws -> [PackageContainerConstraint<Identifier>] {
fatalError("This should never be called")
}
fileprivate init(
_ identifier: Identifier,
manifestLoader: ManifestLoaderProtocol,
toolsVersionLoader: ToolsVersionLoaderProtocol,
currentToolsVersion: ToolsVersion
) {
self.identifier = identifier
self.manifestLoader = manifestLoader
self.toolsVersionLoader = toolsVersionLoader
self.currentToolsVersion = currentToolsVersion
}
}
/// Local package container.
///
/// This class represent packages that are referenced locally in the file system.
/// There is no need to perform any git operations on such packages and they
/// should be used as-is. Infact, they might not even have a git repository.
/// Examples: Root packages, local dependencies, edited packages.
public class LocalPackageContainer: BasePackageContainer, CustomStringConvertible {
/// The file system that shoud be used to load this package.
let fs: FileSystem
public override func getUnversionedDependencies() throws -> [PackageContainerConstraint<Identifier>] {
// Load the tools version.
let toolsVersion = try toolsVersionLoader.load(at: AbsolutePath(identifier.path), fileSystem: fs)
// Ensure current tools supports this package.
guard self.currentToolsVersion >= toolsVersion else {
// FIXME: Throw from here
fatalError()
}
// Load the manifest.
let manifest = try manifestLoader.load(
packagePath: AbsolutePath(identifier.path),
baseURL: identifier.path,
version: nil,
manifestVersion: toolsVersion.manifestVersion,
fileSystem: fs)
return manifest.package.dependencyConstraints()
}
public init(
_ identifier: Identifier,
manifestLoader: ManifestLoaderProtocol,
toolsVersionLoader: ToolsVersionLoaderProtocol,
currentToolsVersion: ToolsVersion,
fs: FileSystem = localFileSystem
) {
assert(URL.scheme(identifier.path) == nil)
self.fs = fs
super.init(
identifier,
manifestLoader: manifestLoader,
toolsVersionLoader: toolsVersionLoader,
currentToolsVersion: currentToolsVersion
)
}
public var description: String {
return "LocalPackageContainer(\(identifier.path))"
}
}
/// Adaptor to expose an individual repository as a package container.
public class RepositoryPackageContainer: BasePackageContainer, CustomStringConvertible {
// A wrapper for getDependencies() errors. This adds additional information
// about the container to identify it for diagnostics.
public struct GetDependenciesErrorWrapper: Swift.Error {
/// The container which had this error.
public let containerIdentifier: String
/// The source control reference i.e. version, branch, revsion etc.
public let reference: String
/// The actual error that occurred.
public let underlyingError: Swift.Error
}
/// The available version list (in reverse order).
public override func versions(filter isIncluded: (Version) -> Bool) -> AnySequence<Version> {
return AnySequence(reversedVersions.filter(isIncluded).lazy.filter({
guard let toolsVersion = try? self.toolsVersion(for: $0),
self.currentToolsVersion >= toolsVersion else {
return false
}
return true
}))
}
/// The opened repository.
let repository: Repository
/// The versions in the repository and their corresponding tags.
let knownVersions: [Version: String]
/// The versions in the repository sorted by latest first.
let reversedVersions: [Version]
/// The cached dependency information.
private var dependenciesCache: [String: [RepositoryPackageConstraint]] = [:]
private var dependenciesCacheLock = Lock()
init(
identifier: PackageReference,
repository: Repository,
manifestLoader: ManifestLoaderProtocol,
toolsVersionLoader: ToolsVersionLoaderProtocol,
currentToolsVersion: ToolsVersion
) {
self.repository = repository
// Compute the map of known versions.
//
// FIXME: Move this utility to a more stable location.
let knownVersions = Git.convertTagsToVersionMap(repository.tags)
self.knownVersions = knownVersions
self.reversedVersions = [Version](knownVersions.keys).sorted().reversed()
super.init(
identifier,
manifestLoader: manifestLoader,
toolsVersionLoader: toolsVersionLoader,
currentToolsVersion: currentToolsVersion
)
}
public var description: String {
return "RepositoryPackageContainer(\(identifier.repository.url.debugDescription))"
}
public func getTag(for version: Version) -> String? {
return knownVersions[version]
}
/// Returns revision for the given tag.
public func getRevision(forTag tag: String) throws -> Revision {
return try repository.resolveRevision(tag: tag)
}
/// Returns revision for the given identifier.
public func getRevision(forIdentifier identifier: String) throws -> Revision {
return try repository.resolveRevision(identifier: identifier)
}
/// Returns the tools version of the given version of the package.
private func toolsVersion(for version: Version) throws -> ToolsVersion {
let tag = knownVersions[version]!
let revision = try repository.resolveRevision(tag: tag)
let fs = try repository.openFileView(revision: revision)
return try toolsVersionLoader.load(at: .root, fileSystem: fs)
}
public override func getDependencies(at version: Version) throws -> [RepositoryPackageConstraint] {
do {
return try cachedDependencies(forIdentifier: version.description) {
let tag = knownVersions[version]!
let revision = try repository.resolveRevision(tag: tag)
return try getDependencies(at: revision, version: version)
}
} catch {
throw GetDependenciesErrorWrapper(
containerIdentifier: identifier.repository.url, reference: version.description, underlyingError: error)
}
}
public override func getDependencies(at revision: String) throws -> [RepositoryPackageConstraint] {
do {
return try cachedDependencies(forIdentifier: revision) {
// resolve the revision identifier and return its dependencies.
let revision = try repository.resolveRevision(identifier: revision)
return try getDependencies(at: revision)
}
} catch {
throw GetDependenciesErrorWrapper(
containerIdentifier: identifier.repository.url, reference: revision, underlyingError: error)
}
}
private func cachedDependencies(
forIdentifier identifier: String,
getDependencies: () throws -> [RepositoryPackageConstraint]
) throws -> [RepositoryPackageConstraint] {
return try dependenciesCacheLock.withLock {
if let result = dependenciesCache[identifier] {
return result
}
let result = try getDependencies()
dependenciesCache[identifier] = result
return result
}
}
/// Returns dependencies of a container at the given revision.
private func getDependencies(
at revision: Revision,
version: Version? = nil
) throws -> [RepositoryPackageConstraint] {
let fs = try repository.openFileView(revision: revision)
// Load the tools version.
let toolsVersion = try toolsVersionLoader.load(at: .root, fileSystem: fs)
// Load the manifest.
let manifest = try manifestLoader.load(
package: AbsolutePath.root,
baseURL: identifier.repository.url,
version: version,
manifestVersion: toolsVersion.manifestVersion,
fileSystem: fs)
return manifest.package.dependencyConstraints()
}
public override func getUnversionedDependencies() throws -> [PackageContainerConstraint<Identifier>] {
// We just return an empty array if requested for unversioned dependencies.
return []
}
}
| 3cb9448a5f4e9f523994b1f16e6541db | 35.957845 | 119 | 0.670426 | false | false | false | false |
biohazardlover/ByTrain | refs/heads/master | ByTrain/Services/AllStationsService.swift | mit | 1 | //
// AllStationsService.swift
// ByTrain
//
// Created by Leon Li on 18/01/2018.
// Copyright © 2018 pp. All rights reserved.
//
import Alamofire
import JavaScriptCore
class AllStationsService: ByTrainService { }
extension AllStationsService: ServiceType {
var path: String {
return "/otn/resources/js/framework/station_name.js"
}
var method: HTTPMethod {
return .get
}
var parameters: [String : Any?] {
return [:]
}
var decoder: (Data) throws -> [Station] {
return { data -> [Station] in
guard let string = String(data: data, encoding: .utf8) else {
return []
}
guard
let context = JSContext(),
let _ = context.evaluateScript(string),
let value = context.objectForKeyedSubscript("station_names"),
let station_names = value.toString()
else {
return []
}
return station_names
.split(separator: "@")
.map { stationName -> Station in
return stationName
.split(separator: "|")
.enumerated()
.reduce(Station(), { station, entry -> Station in
var station = station
switch entry.offset {
case 0:
station.stationNameThreeDigitPinyin = String(entry.element)
case 1:
station.stationName = String(entry.element)
case 2:
station.stationCode = String(entry.element)
case 3:
station.stationNameFullPinyin = String(entry.element)
case 4:
station.stationNameIntials = String(entry.element)
default:
break
}
return station
})
}
}
}
}
| dfbefb52fc6af56a695b21a1e7d6fcac | 31.666667 | 91 | 0.431677 | false | false | false | false |
MichaelRow/MusicPlayer | refs/heads/master | Sources/Player/Spotify/Spotify.swift | gpl-3.0 | 1 | //
// Spotify.swift
// MusicPlayer
//
// Created by Michael Row on 2017/8/31.
//
import Foundation
import ScriptingBridge
import SpotifyBridge
class Spotify {
var spotifyPlayer: SpotifyApplication
var currentTrack: MusicTrack?
weak var delegate: MusicPlayerDelegate?
var rememberedTrackStateDate = Date()
fileprivate(set) var hashValue: Int
required init?() {
guard let player = SBApplication(bundleIdentifier: MusicPlayerName.spotify.bundleID) else { return nil }
spotifyPlayer = player
hashValue = Int(arc4random())
}
deinit {
stopPlayerTracking()
}
// MARK: - Player Event Handle
func pauseEvent() {
PlayerTimer.shared.unregister(self)
delegate?.player(self, playbackStateChanged: .paused, atPosition: playerPosition)
}
func stoppedEvent() {
PlayerTimer.shared.unregister(self)
delegate?.playerDidQuit(self)
}
func playingEvent() {
musicTrackCheckEvent()
delegate?.player(self, playbackStateChanged: .playing, atPosition: playerPosition)
startPeriodTimerObserving()
}
// MARK: - Notification Events
@objc func playerInfoChanged(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let playerState = userInfo["Player State"] as? String
else { return }
switch playerState {
case "Paused":
pauseEvent()
case "Stopped":
stoppedEvent()
case "Playing":
playingEvent()
default:
break
}
}
// MARK: - Timer Events
func startPeriodTimerObserving() {
// start timer
let event = PlayerTimer.Event(kind: .Infinite, precision: MusicPlayerConfig.TimerInterval) { time in
self.repositionCheckEvent()
}
PlayerTimer.shared.register(self, event: event)
// write down the track start time
rememberedTrackStateDate = trackStartDate
}
}
// MARK: - Spotify Track
extension SpotifyTrack {
var musicTrack: MusicTrack? {
guard let id = id?(),
let title = name,
let duration = duration
else { return nil }
var url: URL? = nil
if let spotifyUrl = spotifyUrl {
url = URL(fileURLWithPath: spotifyUrl)
}
return MusicTrack(id: id, title: title, album: album, artist: artist, duration: TimeInterval(duration), artwork: artwork, lyrics: nil, url: url, originalTrack: self as? SBObject)
}
}
| 327352eb05f877028cd618803d943431 | 25.029412 | 186 | 0.604896 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/struct tables/PokemonTable.swift | gpl-2.0 | 1 | //
// PokemonTable.swift
// GoD Tool
//
// Created by Stars Momodu on 25/03/2021.
//
import Foundation
let TMProperties = (1 ... 50).map {
return GoDStructProperties.byte(name: "TM\(String(format: "%02d", $0)) " + XGTMs.tm($0).move.name.unformattedString, description: "", type: .bool)
}
let HMProperties = (1 ... 8).map {
return GoDStructProperties.byte(name: "HM\(String(format: "%02d", $0)) " + XGTMs.tm($0 + 50).move.name.unformattedString, description: "", type: .bool)
}
#if GAME_XD
let tutorProperties = (1 ... 12).map {
return GoDStructProperties.byte(name: "TutorMove\(String(format: "%02d", $0)) " + XGTMs.tutor($0).move.name.unformattedString, description: "", type: .bool)
}
#endif
let statsStructShort = GoDStruct(name: "Stats", format: [
.short(name: "HP", description: "", type: .uint),
.short(name: "Attack", description: "", type: .uint),
.short(name: "Defense", description: "", type: .uint),
.short(name: "Sp.Atk", description: "", type: .uint),
.short(name: "Sp.Def", description: "", type: .uint),
.short(name: "Speed", description: "", type: .uint)
])
let statsStructByte = GoDStruct(name: "Byte Stats", format: [
.byte(name: "HP", description: "", type: .uint),
.byte(name: "Attack", description: "", type: .uint),
.byte(name: "Defense", description: "", type: .uint),
.byte(name: "Sp.Atk", description: "", type: .uint),
.byte(name: "Sp.Def", description: "", type: .uint),
.byte(name: "Speed", description: "", type: .uint)
])
let evolutionStruct = GoDStruct(name: "Evolution", format: [
.byte(name: "Evolution Method", description: "", type: .evolutionMethod),
.short(name: "Evolution Condition", description: "", type: .uintHex),
.short(name: "Evolved Form", description: "", type: .pokemonID)
])
let levelUpMoveStruct = GoDStruct(name: "Level Up Move", format: [
.byte(name: "Level", description: "", type: .uint),
.short(name: "Move", description: "", type: .moveID)
])
let spritesStruct = GoDStruct(name: "Pokemon Sprites", format: [
.byte(name: "Pokedex Colour ID", description: "", type: .uintHex),
.short(name: "Face ID", description: "The index of the image for the pokemon's face", type: .indexOfEntryInTable(table: pokeFacesTable, nameProperty: nil)),
] + (
game == .XD
? [.word(name: "Purify Chamber Image ID", description: "File identifier for the animated texture", type: .fsysFileIdentifier(fsysName: "poke_dance"))]
: [.word(name: "Body Image ID", description: "File identifier for the animated texture", type: .fsysFileIdentifier(fsysName: "poke_body"))]
)
)
#if GAME_XD
let pokemonStatsStruct = GoDStruct(name: "Pokemon Stats", format: [
.byte(name: "Level up Rate", description: "Determines how much exp it takes for the pokemon to level up", type: .expRate),
.byte(name: "Catch Rate", description: "", type: .uint),
.byte(name: "Gender Ratio", description: "", type: .genderRatio),
.short(name: "Exp yield", description: "Determines how much exp you get for defeating this pokemon species", type: .uint),
.short(name: "Base Happiness", description: "Default happiness when this pokemon is caught", type: .uintHex),
.short(name: "Height", description: "Height in meters x10", type: .int),
.short(name: "Weight", description: "Weight in kg x10", type: .int),
.short(name: "Cry ID", description: "", type: .uintHex),
.short(name: "Unknown 1", description: "", type: .uintHex),
.short(name: "Unknown 2", description: "Something sound related", type: .uintHex),
.short(name: "National Dex Index", description: "", type: .uint),
.short(name: "Hoenn dex regional id", description: "If not in the Hoenn dex then listed after deoxys", type: .uint),
.word(name: "Name ID", description: "", type: .msgID(file: .common_rel)),
.word(name: "Species Name ID", description: "The species name used in the pokedex entry", type: .msgID(file: .typeAndFsysName(.msg, "pda_menu"))),
.word(name: "Unknown 3", description: "unused?", type: .uintHex),
.word(name: "Unknown 4", description: "", type: .uintHex),
.word(name: "Unknown 5", description: "", type: .uintHex),
// .word(name: "Model ID", description: "", type: .indexOfEntryInTable(table: pkxFsysIdentifiers, nameProperty: nil))
.word(name: "Model ID", description: "", type: .pkxPokemonID),
.array(name: "Types", description: "", property:
.byte(name: "Type", description: "", type: .typeID), count: 2),
.array(name: "Abilities", description: "", property:
.byte(name: "Ability", description: "", type: .abilityID), count: 2),
]
+ TMProperties + HMProperties + tutorProperties
+ [
.array(name: "Wild Items", description: "The Items pokemon of this species may hold when encountered in the wild", property:
.short(name: "Wild Item", description: "", type: .itemID), count: 2),
.array(name: "Egg Moves", description: "", property:
.short(name: "Egg Move", description: "", type: .moveID), count: 8),
.subStruct(name: "Base Stats", description: "", property: statsStructShort),
.subStruct(name: "EV Yields", description: "The EVs given for defeating this pokemon species", property: statsStructShort),
.array(name: "Evolutions", description: "", property:
.subStruct(name: "Evolution", description: "", property: evolutionStruct), count: 5),
.array(name: "Level Up Moves", description: "", property:
.subStruct(name: "Level Up Move", description: "", property: levelUpMoveStruct), count: 19),
.word(name: "Padding", description: "", type: .null),
.subStruct(name: "Regular Sprites", description: "", property: spritesStruct),
.subStruct(name: "Shiny Sprites", description: "", property: spritesStruct)
]
)
#else
let pokemonStatsStruct = GoDStruct(name: "Pokemon Stats", format: [
.byte(name: "Level up Rate", description: "Determines how much exp it takes for the pokemon to level up", type: .expRate),
.byte(name: "Catch Rate", description: "", type: .uint),
.byte(name: "Gender Ratio", description: "", type: .genderRatio),
.byte(name: "Unknown", description: "", type: .uint),
.byte(name: "Unknown Value", description: "", type: .uintHex),
.short(name: "Exp yield", description: "Determines how much exp you get for defeating this pokemon species", type: .uint),
.short(name: "Base Happiness", description: "Default happiness when this pokemon is caught", type: .uintHex),
.short(name: "Height", description: "Height in meters x10", type: .int),
.short(name: "Weight", description: "Weight in kg x10", type: .int),
.short(name: "Cry ID", description: "", type: .uintHex),
.short(name: "National Dex Index", description: "", type: .uint),
.short(name: "Unknown 2", description: "Same as national id?", type: .uintHex),
.short(name: "Hoenn Regional Dex ID", description: "If not in the Hoenn dex then listed after deoxys", type: .uintHex),
.short(name: "Unknown 4", description: "", type: .uintHex),
.word(name: "Name ID", description: "", type: .msgID(file: .common_rel)),
.word(name: "Species Name ID", description: "The species name used in the pokedex entry", type: .msgID(file: .typeAndFsysName(.msg, "pda_menu"))),
.word(name: "Unknown 5", description: "unused?", type: .uintHex),
.word(name: "Unknown 6", description: "", type: .uintHex),
.word(name: "Unknown 7", description: "", type: .uintHex),
.word(name: "Model ID", description: "", type: .pkxPokemonID),
.array(name: "Types", description: "", property:
.byte(name: "Type", description: "", type: .typeID), count: 2),
.array(name: "Abilities", description: "", property:
.byte(name: "Ability", description: "", type: .abilityID), count: 2),
]
+ TMProperties + HMProperties
+ [
.array(name: "Egg Groups", description: "", property:
.byte(name: "Egg Group", description: "", type: .eggGroup), count: 2),
.array(name: "Wild Items", description: "The Items pokemon of this species may hold when encountered in the wild", property:
.short(name: "Wild Item", description: "", type: .itemID), count: 2),
.array(name: "Egg Moves", description: "", property:
.short(name: "Egg Move", description: "", type: .moveID), count: 8),
.subStruct(name: "Base Stats", description: "", property: statsStructShort),
.subStruct(name: "EV Yields", description: "The EVs given for defeating this pokemon species", property: statsStructShort),
.array(name: "Evolutions", description: "", property:
.subStruct(name: "Evolution", description: "", property: evolutionStruct), count: 5),
.array(name: "Level Up Moves", description: "", property:
.subStruct(name: "Level Up Move", description: "", property: levelUpMoveStruct), count: 19),
.word(name: "Padding", description: "", type: .null),
.subStruct(name: "Regular Sprites", description: "", property: spritesStruct),
.subStruct(name: "Shiny Sprites", description: "", property: spritesStruct)
]
)
#endif
let pokemonStatsTable = CommonStructTable(index: .PokemonStats, properties: pokemonStatsStruct, documentByIndex: false)
| 054a0bfe78605bce8fcbf3121b20989a | 56.571429 | 158 | 0.679901 | false | false | false | false |
DroidsOnRoids/GCMSender | refs/heads/master | GCMSender/StoreManager.swift | mit | 1 | //
// StoreManager.swift
// GCM Sender
//
// Created by Pawel Bednorz on 08/12/15.
// Copyright © 2015 Droids on Roids. All rights reserved.
//
import Foundation
class StoreManager {
private static let UserDefaults = NSUserDefaults.standardUserDefaults()
private static let ApiKeyStoreName = "ApiKeyStore"
private static let RecipientTokenStoreName = "RecipientTokenStore"
static var apiKey: String {
get {
if let apiKeyValue = UserDefaults.objectForKey(ApiKeyStoreName) {
return apiKeyValue as! String
}
return ""
}
set(newApiKey) {
UserDefaults.setObject(newApiKey, forKey: ApiKeyStoreName)
}
}
static var recipientToken: String {
get {
if let apiKeyValue = UserDefaults.objectForKey(RecipientTokenStoreName) {
return apiKeyValue as! String
}
return ""
}
set(newApiKey) {
UserDefaults.setObject(newApiKey, forKey: RecipientTokenStoreName)
}
}
static func clearStore() {
if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier {
UserDefaults.removePersistentDomainForName(bundleIdentifier)
}
}
}
| 9894af34cce33d30a1db1ffc13256360 | 26.680851 | 85 | 0.611068 | false | false | false | false |
Shahn-Auronas/OraChat | refs/heads/master | OraChat/OraChat/NetworkingCalls.swift | mit | 1 | //
// NetworkingCalls.swift
// OraChat
//
// Created by Shahn Auronas on 1/24/17.
// Copyright © 2017 ShahnAuronas. All rights reserved.
//
import Foundation
class NetworkingCalls: NSObject {
typealias SuccessBlock = ((_ task: URLSessionDataTask, _ responseObject: Any?) -> Void)?
typealias FailureBlock = ((_ task: URLSessionDataTask, _ error: Error?) -> Void)?
//MARK: - GET Methods
class func authorizeLogout(successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
getServiceRequest(NetworkingConstants.logoutURL, parameters: [:], successBlock: success, failureBlock: failure)
}
class func readCurrentUser(successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
getServiceRequest(NetworkingConstants.currentUserURL, parameters: [:], successBlock: success, failureBlock: failure)
}
class func listChats(parameters: [String: String], successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
let page = parameters["page"]
let limit = parameters["limit"]
let queryString = "?page=\(page)&limit=\(limit)"
let url = "\(NetworkingConstants.chatsURL)\(queryString)"
getServiceRequest(url, parameters: parameters, successBlock: success, failureBlock: failure)
}
class func listMessages(parameters: [String: String], successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
let id = parameters["id"]
let page = parameters["page"]
let limit = parameters["limit"]
let url = "\(NetworkingConstants.chatsURL)/\(id)/chat_messages?page=\(page)&limit=\(limit)"
getServiceRequest(url, parameters: parameters, successBlock: success, failureBlock: failure)
}
private class func getServiceRequest(_ url: String,
parameters: [String: String]?,
successBlock success: SuccessBlock,
failureBlock failure: FailureBlock) {
if let baseURL: URL = baseURL("\(NetworkingConstants.baseURL)\(url)", parameters: parameters) {
let request = createRequest(url: baseURL, httpMethod: "GET", httpBody: nil)
makeRequest(request, successBlock: success, failureBlock: failure)
}
}
//MARK: - POST Methods
class func authorizeLogin(parameters: [String: String]?, successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
postServiceRequest(NetworkingConstants.loginURL, parameters: parameters, successBlock: success, failureBlock: failure)
}
class func registerUsers(parameters: [String: String]?, successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
postServiceRequest(NetworkingConstants.usersURL, parameters: parameters, successBlock: success, failureBlock: failure)
}
class func createChat(parameters: [String: String], successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
postServiceRequest(NetworkingConstants.chatsURL, parameters: parameters, successBlock: success, failureBlock: failure)
}
class func createMessage(parameters: [String: String], successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
let url = "\(NetworkingConstants.chatsURL)/\(parameters["id"])/chat_messages"
postServiceRequest(url, parameters: parameters, successBlock: success, failureBlock: failure)
}
private class func postServiceRequest(_ url: String, parameters: [String: String]?, successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
if let baseURL = baseURL("\(NetworkingConstants.baseURL)\(url)", parameters: parameters) {
print("url: \(baseURL)")
do {
let httpBody = try JSONSerialization.data(withJSONObject: parameters ?? [:], options: .prettyPrinted)
let request = createRequest(url: baseURL, httpMethod: "POST", httpBody: httpBody)
makeRequest(request, successBlock: success, failureBlock: failure)
} catch {
print("Error: \(error) serializing JSON")
}
}
}
//MARK: - PATCH Methods
class func updateCurrentUser(parameters: [String: String]?, successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
patchServiceRequest(NetworkingConstants.currentUserURL, parameters: parameters, successBlock: success, failureBlock: failure)
}
class func updateChat(parameters: [String: String], successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
let url = "\(NetworkingConstants.chatsURL)\(parameters["id"])"
patchServiceRequest(url, parameters: parameters, successBlock: success, failureBlock: failure)
}
private class func patchServiceRequest(_ url: String, parameters: [String: String]?, successBlock success: SuccessBlock, failureBlock failure: FailureBlock) {
if let baseURL = baseURL("\(NetworkingConstants.baseURL)\(url))", parameters: parameters) {
print("url: \(baseURL)")
do {
let data = try JSONSerialization.data(withJSONObject: parameters ?? [:], options: .prettyPrinted)
let request = createRequest(url: baseURL, httpMethod: "PATCH", httpBody: data)
makeRequest(request, successBlock: success, failureBlock: failure)
} catch {
print("Error: \(error) serializing JSON")
}
}
}
//MARK: Helpers
private class func baseURL(_ base: String, parameters: [String: String]?) -> URL? {
guard var components = URLComponents(string: base) else {
return nil
}
var queryItems: [URLQueryItem] = []
if let params = parameters {
if params.keys.count > 0 {
for (key, _) in params {
queryItems.append(URLQueryItem(name: key, value: params[key]))
}
components.queryItems = queryItems
}
}
return components.url!
}
private class func createRequest(url: URL, httpMethod: String, httpBody: Data?) -> URLRequest {
let request = NSMutableURLRequest(url: url)
request.httpMethod = httpMethod
request.addValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue(NetworkingConstants.bearer, forHTTPHeaderField: "Authorization")
request.httpBody = httpBody
return request as URLRequest
}
private class func makeRequest(_ request: URLRequest,
successBlock success: SuccessBlock,
failureBlock failure: FailureBlock) {
var sessionDataTask: URLSessionDataTask = URLSessionDataTask()
sessionDataTask = URLSession.shared.dataTask(with: request, completionHandler: {
(data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async {
if let urlResponse = response {
print("status Code: \((urlResponse as! HTTPURLResponse).statusCode)")
if (data != nil) && (success != nil) && ((urlResponse as! HTTPURLResponse).statusCode < 400) {
do {
let responseObject: Any = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
success!(sessionDataTask, responseObject)
} catch {
failure!(sessionDataTask, nil)
}
} else {
if let responseError = error, let responseFailure = failure {
responseFailure(sessionDataTask, responseError)
}
}
}
}
})
sessionDataTask.resume()
}
}
| f02bfa4747b95c54a5589444f81d908c | 49.49375 | 162 | 0.631142 | false | false | false | false |
zerozheng/ZZQRCode | refs/heads/master | QRCode/ViewController.swift | mit | 1 | //
// ViewController.swift
// QRCode
//
// Created by zero on 17/2/6.
// Copyright © 2017年 zero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func scan(_ sender: Any) {
let vc = ScanVC()
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func detect(button:UIButton) {
QRImageDetector.detectImage(image: button.currentImage!) { (result, error) in
if error == false {
self.showMessage(result!)
}
}
}
@IBAction func generate() {
let image = QRCodeGenerator.generateImage("develop by zero zheng", avatarImage: UIImage(named: "default.jpeg"))
let vc: GenerateVC = GenerateVC()
vc.imageView.image = image
self.navigationController?.pushViewController(vc, animated: true)
}
func showMessage(_ message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "ok", style: .`default`, handler: nil))
alert.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
extension ViewController: ScanVCDelegate {
func scanVC(vc: ScanVC, didFoundResult result: String) {
self.showMessage(result)
}
}
| 4de26e77f068a9ab542278c050548026 | 28.836735 | 119 | 0.629275 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Kickstarter-iOS/Features/PaymentMethods/Controller/PaymentMethodsViewController.swift | apache-2.0 | 1 | import KsApi
import Library
import Prelude
import Stripe
import UIKit
protocol PaymentMethodsViewControllerDelegate: AnyObject {
func cancelLoadingPaymentMethodsViewController(
_ viewController: PaymentMethodsViewController)
}
internal final class PaymentMethodsViewController: UIViewController, MessageBannerViewControllerPresenting {
private let dataSource = PaymentMethodsDataSource()
private let viewModel: PaymentMethodsViewModelType = PaymentMethodsViewModel()
private var paymentSheetFlowController: PaymentSheet.FlowController?
private weak var cancellationDelegate: PaymentMethodsViewControllerDelegate?
@IBOutlet private var tableView: UITableView!
fileprivate lazy var editButton: UIBarButtonItem = {
UIBarButtonItem(
title: Strings.discovery_favorite_categories_buttons_edit(),
style: .plain,
target: self,
action: #selector(edit)
)
}()
internal var messageBannerViewController: MessageBannerViewController?
public static func instantiate() -> PaymentMethodsViewController {
return Storyboard.Settings.instantiate(PaymentMethodsViewController.self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.messageBannerViewController = self.configureMessageBannerViewController(on: self)
self.tableView.register(nib: .CreditCardCell)
self.tableView.dataSource = self.dataSource
self.tableView.delegate = self
self.configureHeaderFooterViews()
self.navigationItem.rightBarButtonItem = self.editButton
self.editButton.possibleTitles = [
Strings.discovery_favorite_categories_buttons_edit(),
Strings.Done()
]
self.dataSource.deletionHandler = { [weak self] creditCard in
self?.viewModel.inputs.shouldCancelPaymentSheetAppearance(state: true)
self?.viewModel.inputs.didDelete(creditCard, visibleCellCount: self?.tableView.visibleCells.count ?? 0)
}
self.viewModel.inputs.viewDidLoad()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.ksr_sizeHeaderFooterViewsToFit()
}
override func bindStyles() {
super.bindStyles()
_ = self
|> settingsViewControllerStyle
|> UIViewController.lens.title %~ { _ in
Strings.Payment_methods()
}
_ = self.tableView
|> tableViewStyle
|> tableViewSeparatorStyle
}
override func bindViewModel() {
super.bindViewModel()
self.editButton.rac.enabled = self.viewModel.outputs.editButtonIsEnabled
self.viewModel.outputs.cancelAddNewCardLoadingState
.observeForUI()
.observeValues { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.cancellationDelegate?.cancelLoadingPaymentMethodsViewController(strongSelf)
}
self.viewModel.outputs.paymentMethods
.observeForUI()
.observeValues { [weak self] result in
self?.dataSource.load(creditCards: result)
self?.tableView.reloadData()
}
self.viewModel.outputs.reloadData
.observeForUI()
.observeValues { [weak self] in
self?.tableView.reloadData()
}
self.viewModel.outputs.goToAddCardScreenWithIntent
.observeForUI()
.observeValues { [weak self] intent in
self?.goToAddCardScreen(with: intent)
}
self.viewModel.outputs.goToPaymentSheet
.observeForUI()
.observeValues { [weak self] data in
guard let strongSelf = self else { return }
strongSelf.goToPaymentSheet(data: data)
}
self.viewModel.outputs.errorLoadingPaymentMethodsOrSetupIntent
.observeForUI()
.observeValues { [weak self] message in
self?.messageBannerViewController?.showBanner(with: .error, message: message)
}
self.viewModel.outputs.presentBanner
.observeForUI()
.observeValues { [weak self] message in
self?.messageBannerViewController?.showBanner(with: .success, message: message)
}
self.viewModel.outputs.tableViewIsEditing
.observeForUI()
.observeValues { [weak self] isEditing in
self?.tableView.setEditing(isEditing, animated: true)
}
self.viewModel.outputs.showAlert
.observeForControllerAction()
.observeValues { [weak self] message in
self?.present(UIAlertController.genericError(message), animated: true)
}
self.viewModel.outputs.editButtonTitle
.observeForUI()
.observeValues { [weak self] title in
_ = self?.editButton
?|> \.title %~ { _ in title }
}
self.viewModel.outputs.setStripePublishableKey
.observeForUI()
.observeValues {
STPAPIClient.shared.publishableKey = $0
}
}
// MARK: - Actions
@objc private func edit() {
self.viewModel.inputs.editButtonTapped()
self.viewModel.inputs.shouldCancelPaymentSheetAppearance(state: true)
}
private func goToAddCardScreen(with intent: AddNewCardIntent) {
let vc = AddNewCardViewController.instantiate()
vc.configure(with: intent)
vc.delegate = self
let nav = UINavigationController(rootViewController: vc)
nav.modalPresentationStyle = .formSheet
self.present(nav, animated: true) { self.viewModel.inputs.addNewCardPresented() }
}
// MARK: - Private Helpers
private func goToPaymentSheet(data: PaymentSheetSetupData) {
PaymentSheet.FlowController
.create(
setupIntentClientSecret: data.clientSecret,
configuration: data.configuration
) { [weak self] result in
guard let strongSelf = self else { return }
switch result {
case let .failure(error):
strongSelf.viewModel.inputs.shouldCancelPaymentSheetAppearance(state: true)
strongSelf.messageBannerViewController?
.showBanner(with: .error, message: error.localizedDescription)
case let .success(paymentSheetFlowController):
let topViewController = strongSelf.navigationController?.topViewController
let paymentSheetShownWithinPaymentMethodsContext = topViewController is PaymentMethodsViewController
if paymentSheetShownWithinPaymentMethodsContext {
strongSelf.paymentSheetFlowController = paymentSheetFlowController
strongSelf.paymentSheetFlowController?.presentPaymentOptions(from: strongSelf) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.confirmPaymentResult(with: data.clientSecret)
}
}
}
}
}
private func confirmPaymentResult(with clientSecret: String) {
guard self.paymentSheetFlowController?.paymentOption != nil else {
self.viewModel.inputs.shouldCancelPaymentSheetAppearance(state: true)
return
}
self.paymentSheetFlowController?.confirm(from: self) { [weak self] paymentResult in
guard let strongSelf = self else { return }
strongSelf.viewModel.inputs.shouldCancelPaymentSheetAppearance(state: true)
guard let existingPaymentOption = strongSelf.paymentSheetFlowController?.paymentOption else { return }
switch paymentResult {
case .completed:
strongSelf.viewModel.inputs
.paymentSheetDidAdd(newCard: existingPaymentOption, setupIntent: clientSecret)
case .canceled:
strongSelf.messageBannerViewController?
.showBanner(with: .error, message: Strings.general_error_something_wrong())
case let .failed(error):
strongSelf.messageBannerViewController?.showBanner(with: .error, message: error.localizedDescription)
}
}
}
private func configureHeaderFooterViews() {
if let header = SettingsTableViewHeader.fromNib(nib: Nib.SettingsTableViewHeader) {
header.configure(with: Strings.Any_payment_methods_you_saved_to_Kickstarter())
let headerContainer = UIView(frame: .zero)
_ = (header, headerContainer) |> ksr_addSubviewToParent()
self.tableView.tableHeaderView = headerContainer
_ = (header, headerContainer) |> ksr_constrainViewToEdgesInParent()
_ = header.widthAnchor.constraint(equalTo: self.tableView.widthAnchor)
|> \.priority .~ .defaultHigh
|> \.isActive .~ true
}
if let footer = PaymentMethodsFooterView.fromNib(nib: Nib.PaymentMethodsFooterView) {
footer.delegate = self
self.cancellationDelegate = footer
let footerContainer = UIView(frame: .zero)
_ = (footer, footerContainer) |> ksr_addSubviewToParent()
self.tableView.tableFooterView = footerContainer
_ = (footer, footerContainer) |> ksr_constrainViewToEdgesInParent()
_ = footer.widthAnchor.constraint(equalTo: self.tableView.widthAnchor)
|> \.priority .~ .defaultHigh
|> \.isActive .~ true
}
}
}
extension PaymentMethodsViewController: UITableViewDelegate {
func tableView(_: UITableView, heightForFooterInSection _: Int) -> CGFloat {
return 0.1
}
func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat {
return 0.1
}
}
extension PaymentMethodsViewController: PaymentMethodsFooterViewDelegate {
internal func paymentMethodsFooterViewDidTapAddNewCardButton(_: PaymentMethodsFooterView) {
self.viewModel.inputs.paymentMethodsFooterViewDidTapAddNewCardButton()
}
}
extension PaymentMethodsViewController: AddNewCardViewControllerDelegate {
func addNewCardViewController(
_: AddNewCardViewController,
didAdd _: UserCreditCards.CreditCard,
withMessage message: String
) {
self.dismiss(animated: true) {
self.viewModel.inputs.addNewCardSucceeded(with: message)
}
}
func addNewCardViewControllerDismissed(_: AddNewCardViewController) {
self.dismiss(animated: true) {
self.viewModel.inputs.addNewCardDismissed()
}
}
}
// MARK: - Styles
private let tableViewStyle: TableViewStyle = { (tableView: UITableView) in
tableView
|> \.backgroundColor .~ UIColor.clear
|> \.rowHeight .~ Styles.grid(11)
|> \.allowsSelection .~ false
}
private let tableViewSeparatorStyle: TableViewStyle = { tableView in
tableView
|> \.separatorStyle .~ .singleLine
|> \.separatorColor .~ .ksr_support_300
|> \.separatorInset .~ .init(left: Styles.grid(2))
}
| 3820a6bcbbc44a4837cd667891e92838 | 31.387302 | 110 | 0.713782 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/UI/PlacePage/Components/PlacePageInfoViewController.swift | apache-2.0 | 5 | class InfoItemViewController: UIViewController {
enum Style {
case regular
case link
}
typealias TapHandler = () -> Void
@IBOutlet var imageView: UIImageView!
@IBOutlet var infoLabel: UILabel!
@IBOutlet var accessoryImage: UIImageView!
@IBOutlet var separatorView: UIView!
@IBOutlet var tapGestureRecognizer: UITapGestureRecognizer!
var tapHandler: TapHandler?
var style: Style = .regular {
didSet {
switch style {
case .regular:
imageView?.styleName = "MWMBlack"
infoLabel?.styleName = "blackPrimaryText"
case .link:
imageView?.styleName = "MWMBlue"
infoLabel?.styleName = "linkBlueText"
}
}
}
var canShowMenu = false
@IBAction func onTap(_ sender: UITapGestureRecognizer) {
tapHandler?()
}
@IBAction func onLongPress(_ sender: UILongPressGestureRecognizer) {
guard sender.state == .began, canShowMenu else { return }
let menuController = UIMenuController.shared
menuController.setTargetRect(infoLabel.frame, in: self.view)
infoLabel.becomeFirstResponder()
menuController.setMenuVisible(true, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
if style == .link {
imageView.styleName = "MWMBlue"
infoLabel.styleName = "linkBlueText"
}
}
}
protocol PlacePageInfoViewControllerDelegate: AnyObject {
func didPressCall()
func didPressWebsite()
func didPressEmail()
func didPressLocalAd()
}
class PlacePageInfoViewController: UIViewController {
private struct Const {
static let coordinatesKey = "PlacePageInfoViewController_coordinatesKey"
}
private typealias TapHandler = InfoItemViewController.TapHandler
private typealias Style = InfoItemViewController.Style
@IBOutlet var stackView: UIStackView!
private lazy var openingHoursView: OpeningHoursViewController = {
storyboard!.instantiateViewController(ofType: OpeningHoursViewController.self)
}()
private var rawOpeningHoursView: InfoItemViewController?
private var phoneView: InfoItemViewController?
private var websiteView: InfoItemViewController?
private var emailView: InfoItemViewController?
private var cuisineView: InfoItemViewController?
private var operatorView: InfoItemViewController?
private var wifiView: InfoItemViewController?
private var addressView: InfoItemViewController?
private var coordinatesView: InfoItemViewController?
private var localAdsButton: UIButton?
var placePageInfoData: PlacePageInfoData!
weak var delegate: PlacePageInfoViewControllerDelegate?
var showFormattedCoordinates: Bool {
get {
UserDefaults.standard.bool(forKey: Const.coordinatesKey)
}
set {
UserDefaults.standard.set(newValue, forKey: Const.coordinatesKey)
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let openingHours = placePageInfoData.openingHours {
openingHoursView.openingHours = openingHours
addToStack(openingHoursView)
} else if let openingHoursString = placePageInfoData.openingHoursString {
rawOpeningHoursView = createInfoItem(openingHoursString, icon: UIImage(named: "ic_placepage_open_hours"))
rawOpeningHoursView?.infoLabel.numberOfLines = 0
}
if let phone = placePageInfoData.phone {
var cellStyle: Style = .regular
if let phoneUrl = placePageInfoData.phoneUrl, UIApplication.shared.canOpenURL(phoneUrl) {
cellStyle = .link
}
phoneView = createInfoItem(phone, icon: UIImage(named: "ic_placepage_phone_number"), style: cellStyle) { [weak self] in
self?.delegate?.didPressCall()
}
}
if let website = placePageInfoData.website {
websiteView = createInfoItem(website, icon: UIImage(named: "ic_placepage_website"), style: .link) { [weak self] in
self?.delegate?.didPressWebsite()
}
}
if let email = placePageInfoData.email {
emailView = createInfoItem(email, icon: UIImage(named: "ic_placepage_email"), style: .link) { [weak self] in
self?.delegate?.didPressEmail()
}
}
if let cuisine = placePageInfoData.cuisine {
cuisineView = createInfoItem(cuisine, icon: UIImage(named: "ic_placepage_cuisine"))
}
if let ppOperator = placePageInfoData.ppOperator {
operatorView = createInfoItem(ppOperator, icon: UIImage(named: "ic_placepage_operator"))
}
if placePageInfoData.wifiAvailable {
wifiView = createInfoItem(L("WiFi_available"), icon: UIImage(named: "ic_placepage_wifi"))
}
if let address = placePageInfoData.address {
addressView = createInfoItem(address, icon: UIImage(named: "ic_placepage_adress"))
}
if let formattedCoordinates = placePageInfoData.formattedCoordinates,
let rawCoordinates = placePageInfoData.rawCoordinates {
let coordinates = showFormattedCoordinates ? formattedCoordinates : rawCoordinates
coordinatesView = createInfoItem(coordinates, icon: UIImage(named: "ic_placepage_coordinate")) {
[unowned self] in
self.showFormattedCoordinates = !self.showFormattedCoordinates
let coordinates = self.showFormattedCoordinates ? formattedCoordinates : rawCoordinates
self.coordinatesView?.infoLabel.text = coordinates
}
} else if let formattedCoordinates = placePageInfoData.formattedCoordinates {
coordinatesView = createInfoItem(formattedCoordinates, icon: UIImage(named: "ic_placepage_coordinate"))
} else if let rawCoordinates = placePageInfoData.rawCoordinates {
coordinatesView = createInfoItem(rawCoordinates, icon: UIImage(named: "ic_placepage_coordinate"))
}
coordinatesView?.accessoryImage.image = UIImage(named: "ic_placepage_change")
coordinatesView?.accessoryImage.isHidden = false
coordinatesView?.canShowMenu = true
switch placePageInfoData.localAdsStatus {
case .candidate:
localAdsButton = createLocalAdsButton(L("create_campaign_button"))
case .customer:
localAdsButton = createLocalAdsButton(L("view_campaign_button"))
case .notAvailable, .hidden:
coordinatesView?.separatorView.isHidden = true
@unknown default:
fatalError()
}
}
// MARK: private
@objc private func onLocalAdsButton(_ sender: UIButton) {
delegate?.didPressLocalAd()
}
private func createLocalAdsButton(_ title: String) -> UIButton {
let button = UIButton()
button.setTitle(title, for: .normal)
button.styleName = "FlatNormalTransButtonBig"
button.heightAnchor.constraint(equalToConstant: 44).isActive = true
stackView.addArrangedSubview(button)
button.addTarget(self, action: #selector(onLocalAdsButton(_:)), for: .touchUpInside)
return button
}
private func createInfoItem(_ info: String,
icon: UIImage?,
style: Style = .regular,
tapHandler: TapHandler? = nil) -> InfoItemViewController {
let vc = storyboard!.instantiateViewController(ofType: InfoItemViewController.self)
addToStack(vc)
vc.imageView.image = icon
vc.infoLabel.text = info
vc.style = style
vc.tapHandler = tapHandler
return vc;
}
private func addToStack(_ viewController: UIViewController) {
addChild(viewController)
stackView.addArrangedSubview(viewController.view)
viewController.didMove(toParent: self)
}
}
| f0722fdf651d393c0ae13f523d98b014 | 34.418269 | 125 | 0.719967 | false | false | false | false |
wuyezhiguhun/DDSwift | refs/heads/master | DDSwift/基本变量使用/Controller/DDBasicTypeVC.swift | mit | 1 | //
// DDBasicTypeVC.swift
// DDSwift
//
// Created by 王允顶 on 17/4/25.
// Copyright © 2017年 王允顶. All rights reserved.
//
// 基本数据类型
import UIKit
class DDBasicTypeVC: RootViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.orange
self.view.addSubview(self.oneButton)
self.addAllViewLayout()
// Do any additional setup after loading the view.
}
func addAllViewLayout() -> Void {
// self.oneButton.autoPinEdge(toSuperviewEdge: ALEdge.left)
// self.oneButton.autoPinEdge(toSuperviewEdge: ALEdge.top)
// self.oneButton.autoSetDimension(ALDimension.width, toSize: 100)
// self.oneButton.autoSetDimension(ALDimension.height, toSize: 30)
}
func setNavigation() -> Void {
//图片的方式添加按钮
let leftImage = UIImage(named: "back_neihan")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: leftImage, style: UIBarButtonItemStyle.done, target: self, action:#selector(backTouch))
}
override func backTouch() -> Void {
dismiss(animated: true, completion: nil)
}
func ontButtonTouch() -> Void {
print("点击按钮")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var _oneButton: UIButton?
var oneButton: UIButton {
get {
if _oneButton == nil {
_oneButton = UIButton(type: UIButtonType.custom)
_oneButton?.backgroundColor = UIColor.white
_oneButton?.setTitle("按钮", for: UIControlState.normal)
_oneButton?.setTitleColor(UIColor.blue, for: UIControlState.normal)
_oneButton?.addTarget(self, action: #selector(ontButtonTouch), for: UIControlEvents.touchUpInside)
}
return _oneButton!
}
set {
}
}
}
| 09dec594c273c19a6617db8bec7758b3 | 30.323077 | 158 | 0.631139 | false | false | false | false |
ALoginov/ALLoadingView | refs/heads/master | ALLoadingView/ViewController.swift | mit | 1 | /*
Copyright (c) 2015 Artem Loginov
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate var step = 0
fileprivate var updateTimer = Timer()
@IBAction func action_testCaseOne(_ sender: AnyObject) {
ALLoadingView.manager.resetToDefaults()
ALLoadingView.manager.blurredBackground = true
ALLoadingView.manager.windowRatio = 0.6
ALLoadingView.manager.showLoadingView(ofType: .message, windowMode: .windowed)
ALLoadingView.manager.hideLoadingView(withDelay: 2.0)
}
@IBAction func action_testCaseTwo(_ sender: AnyObject) {
ALLoadingView.manager.resetToDefaults()
ALLoadingView.manager.blurredBackground = true
ALLoadingView.manager.animationDuration = 1.0
ALLoadingView.manager.itemSpacing = 30.0
ALLoadingView.manager.showLoadingView(ofType: .messageWithIndicator, windowMode: .fullscreen)
ALLoadingView.manager.hideLoadingView(withDelay: 2.0)
}
@IBAction func action_testCaseThree(_ sender: AnyObject) {
ALLoadingView.manager.resetToDefaults()
ALLoadingView.manager.blurredBackground = true
ALLoadingView.manager.itemSpacing = 50.0
ALLoadingView.manager.showLoadingView(ofType: .messageWithIndicatorAndCancelButton, windowMode: .fullscreen)
ALLoadingView.manager.cancelCallback = {
ALLoadingView.manager.hideLoadingView()
}
}
@IBAction func action_testCaseFour(_ sender: AnyObject) {
ALLoadingView.manager.resetToDefaults()
ALLoadingView.manager.itemSpacing = 30.0
ALLoadingView.manager.showLoadingView(ofType: .progress) {
ALLoadingView.manager.updateProgressLoadingView(withMessage: "Initializing", forProgress: 0.05)
self.step = 1
self.updateTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.updateProgress), userInfo: nil, repeats: true)
}
}
@IBAction func action_testCaseFive(_ sender: AnyObject) {
ALLoadingView.manager.resetToDefaults()
ALLoadingView.manager.itemSpacing = 20.0
ALLoadingView.manager.windowRatio = 0.6
ALLoadingView.manager.messageText = "Press on Cancel button to change text and progress value"
ALLoadingView.manager.showLoadingView(ofType: .progressWithCancelButton, windowMode: .windowed)
ALLoadingView.manager.cancelCallback = {
[unowned self] in
self.iterate()
}
}
var caseFiveStep = 0
func iterate() {
guard caseFiveStep < 5 else {
caseFiveStep = 0
ALLoadingView.manager.hideLoadingView()
return
}
caseFiveStep += 1
ALLoadingView.manager.updateProgressLoadingView(withMessage: "Count = \(caseFiveStep)", forProgress: 0.2 * Float(caseFiveStep))
}
@objc func updateProgress() {
let steps = ["Initializing", "Downloading data", "Extracting files", "Parsing data", "Updating database", "Saving"]
ALLoadingView.manager.updateProgressLoadingView(withMessage: steps[step], forProgress: 0.2 * Float(step))
step += 1
if step == steps.count {
ALLoadingView.manager.hideLoadingView()
updateTimer.invalidate()
}
}
}
| 8ae85c23a26b10e1a3494f962dfecd44 | 41.089286 | 166 | 0.696224 | false | false | false | false |
JadenGeller/Calcula | refs/heads/master | Sources/Term.swift | mit | 1 | //
// Term.swift
// Calcula
//
// Created by Jaden Geller on 12/21/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
public func lambda(body: Term -> Term) -> Term {
return Term(lambdaBody: body)
}
/// A lambda calculus term.
public enum Term {
// Constained constant.
case constant(Any)
/// Value that will be determined by the input of a lambda abstraction.
case variable(Binding)
/// Lambda abstraction capable of taking a single input and substituting it into the expression.
indirect case lambda(Binding, Term)
/// Application of the left hand term to the right hand term.
indirect case application(Term, Term)
}
extension Term {
public init(lambdaBody: Term -> Term) {
let argument = Binding()
self = .lambda(argument, lambdaBody(.variable(argument)))
}
public subscript(argument: Term) -> Term {
return .application(self, argument)
}
}
extension Term {
public static func freeVariable() -> Term {
return .variable(Binding())
}
/// The set of identifiers that are not bound by a lambda abstraction.
public var freeVariables: Set<Binding> {
switch self {
case .constant:
return []
case .variable(let binding):
return [binding]
case .lambda(let argument, let lambda):
return lambda.freeVariables.subtract([argument])
case .application(let lhs, let rhs):
return lhs.freeVariables.union(rhs.freeVariables)
}
}
}
extension Term {
/// Returns `true` if `lhs` and `rhs` are structurally equal without doing any reduction, `false` otherwise.
/// If a constant term is compared, will return `nil` to indicate comparison failed. (As a limitation of Swift,
/// it is not possible to check if two `Any` values are equal.)
// TODO: Once Equatable can be used as an existential in some way, update this and don't return an optional.
public static func structurallyEqual(lhs: Term, _ rhs: Term, withContext context: [Binding : Binding] = [:]) -> Bool? {
switch (lhs, rhs) {
case (.constant, .constant):
return nil
case (.variable(let leftBinding), .variable(let rightBinding)):
return leftBinding == rightBinding || context[leftBinding] == rightBinding
case (.lambda(let leftArgument, let leftBody), .lambda(let rightArgument, let rightBody)):
var contextCopy = context
contextCopy[leftArgument] = rightArgument
return structurallyEqual(leftBody, rightBody, withContext: contextCopy)
case (.application(let leftLhs, let leftRhs), .application(let rightLhs, let rightRhs)):
guard let leftEqual = structurallyEqual(leftLhs, rightLhs, withContext: context) else { return nil }
guard leftEqual == true else { return false }
guard let rightEqual = structurallyEqual(leftRhs, rightRhs, withContext: context) else { return nil }
guard rightEqual == true else { return false }
return true
default:
return false
}
}
}
| 38c4adc0956f1f65188e46bd8be45d52 | 36.070588 | 123 | 0.645192 | false | false | false | false |
lelandjansen/fatigue | refs/heads/master | ios/fatigue/LegalCell.swift | apache-2.0 | 1 | import UIKit
class LegalCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
weak var delegate: OnboardingDelegate?
let titleLabel: UILabel = {
let label = UILabel()
label.text = "A few formalities"
label.font = .systemFont(ofSize: 22)
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.textColor = .dark
return label
}()
let legalTextView: UITextView = {
let view = UITextView()
if let path = Bundle.main.path(forResource: "LEGAL", ofType: String()) {
let fileManager = FileManager()
let contents = fileManager.contents(atPath: path)
let fileText = NSString(data: contents!, encoding: String.Encoding.utf8.rawValue)! as String
view.text = fileText.trimmingCharacters(in: .whitespacesAndNewlines)
}
view.isEditable = false
view.font = .systemFont(ofSize: 14)
view.textColor = .dark
view.backgroundColor = .clear
view.textAlignment = .justified
return view
}()
let agreeButton: UIButton = {
let button = UIButton.createStyledSelectButton(withColor: .violet)
button.setTitle("I Agree", for: .normal)
return button
}()
func handleAgreeButton() {
if self.agreeButton.isSelected {
self.delegate?.moveToNextPage()
return
}
let alertController = UIAlertController(title: "Confirmation", message: String(), preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "I Agree", style: .default, handler: { _ in
self.agreeButton.isSelected = true
self.delegate?.addNextPage()
self.delegate?.moveToNextPage()
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
delegate?.presentViewController(alertController)
}
func setupViews() {
addSubview(titleLabel)
addSubview(agreeButton)
addSubview(legalTextView)
let padding: CGFloat = 16
titleLabel.anchorWithConstantsToTop(
topAnchor,
left: leftAnchor,
right: rightAnchor,
topConstant: 3 * padding,
leftConstant: padding,
rightConstant: padding
)
let buttonBottomPadding: CGFloat = 2 * padding
agreeButton.anchorWithConstantsToTop(
topAnchor,
left: leftAnchor,
bottom: bottomAnchor,
right: rightAnchor,
topConstant: frame.height - UIConstants.buttonHeight - buttonBottomPadding,
leftConstant: (frame.width - UIConstants.buttonWidth) / 2,
bottomConstant: buttonBottomPadding,
rightConstant: (frame.width - UIConstants.buttonWidth) / 2
)
agreeButton.addTarget(self, action: #selector(handleAgreeButton), for: .touchUpInside)
legalTextView.anchorWithConstantsToTop(
titleLabel.bottomAnchor,
left: leftAnchor,
bottom: agreeButton.topAnchor,
right: rightAnchor,
topConstant: padding,
leftConstant: padding / 2,
bottomConstant: padding,
rightConstant: padding / 2
)
}
}
| 319e2bbb5d7f5407a09de13dca542cd4 | 34.545455 | 113 | 0.608127 | false | false | false | false |
biboran/dao | refs/heads/master | Example/Tests/Item.swift | mit | 1 | //
// Item.swift
// DAO
//
// Created by Timofey on 3/23/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import DAO
struct Item: Persistable, Equatable {
typealias PrimaryKeyType = String
let name: String
static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.name == rhs.name
}
}
| a22a2636d7cc7308cd87713db48ed283 | 14.590909 | 52 | 0.638484 | false | false | false | false |
mentrena/SyncKit | refs/heads/master | SyncKit/Classes/CoreData/DefaultCoreDataAdapterProvider.swift | mit | 1 | //
// DefaultCoreDataAdapterProvider.swift
// Pods
//
// Created by Manuel Entrena on 22/06/2019.
//
import Foundation
import CloudKit
import CoreData
/// Default implementation of the `AdapterProvider`. Creates a `CoreDataAdapter` for the the given `NSManagedObjectContext` and record zone ID.
@objc public class DefaultCoreDataAdapterProvider: NSObject, AdapterProvider {
let zoneID: CKRecordZone.ID
let managedObjectContext: NSManagedObjectContext
let appGroup: String?
public private(set) var adapter: CoreDataAdapter!
/// Create a new model adapter provider.
/// - Parameters:
/// - managedObjectContext: `NSManagedObjectContext` to be used by the model adapter.
/// - zoneID: `CKRecordZone.ID` to be used by the model adapter.
/// - appGroup: Optional app group.
@objc public init(managedObjectContext: NSManagedObjectContext, zoneID: CKRecordZone.ID, appGroup: String? = nil) {
self.managedObjectContext = managedObjectContext
self.zoneID = zoneID
self.appGroup = appGroup
super.init()
adapter = createAdapter()
}
fileprivate func createAdapter() -> CoreDataAdapter {
let delegate = DefaultCoreDataAdapterDelegate.shared
let stack = CoreDataStack(storeType: NSSQLiteStoreType,
model: CoreDataAdapter.persistenceModel,
storeURL: DefaultCoreDataAdapterProvider.storeURL(appGroup: appGroup))
return CoreDataAdapter(persistenceStack: stack, targetContext: managedObjectContext, recordZoneID: zoneID, delegate: delegate)
}
// MARK: - File directory
/**
* If using app groups, SyncKit offers the option to store its tracking database in the shared container so that it's
* accessible by SyncKit from any of the apps in the group. This method returns the path used in this case.
*
* @param appGroup Identifier of an App Group this app belongs to.
*
* @return File path, in the shared container, where SyncKit will store its tracking database.
*/
static func storeURL(appGroup: String?) -> URL {
return applicationStoresPath(appGroup: appGroup).appendingPathComponent(storeFileName())
}
private static func applicationDocumentsDirectory() -> URL {
#if os(iOS) || os(watchOS)
return FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last!
#else
let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
return urls.last!.appendingPathComponent("com.mentrena.QSCloudKitSynchronizer")
#endif
}
private static func applicationDocumentsDirectory(appGroup: String?) -> URL {
if let appGroup = appGroup {
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)!
}
return applicationDocumentsDirectory()
}
private static func applicationStoresPath(appGroup: String?) -> URL {
return DefaultCoreDataAdapterProvider.applicationDocumentsDirectory(appGroup: appGroup).appendingPathComponent("Stores")
}
private static func storeFileName() -> String {
return "QSSyncStore"
}
}
extension DefaultCoreDataAdapterProvider {
public func cloudKitSynchronizer(_ synchronizer: CloudKitSynchronizer, modelAdapterForRecordZoneID recordZoneID: CKRecordZone.ID) -> ModelAdapter? {
guard recordZoneID == zoneID else { return nil }
return adapter
}
public func cloudKitSynchronizer(_ synchronizer: CloudKitSynchronizer, zoneWasDeletedWithZoneID recordZoneID: CKRecordZone.ID) {
let adapterHasSyncedBefore = adapter.serverChangeToken != nil
if recordZoneID == zoneID && adapterHasSyncedBefore {
adapter.deleteChangeTracking()
synchronizer.removeModelAdapter(adapter)
adapter = createAdapter()
synchronizer.addModelAdapter(adapter)
}
}
}
| 483450af978df80d134abcc6819ee259 | 38.285714 | 152 | 0.683152 | false | false | false | false |
CaueAlvesSilva/DropDownAlert | refs/heads/master | DropDownAlert/DropDownAlert/DropDownView/DropDownView.swift | mit | 1 | //
// DropDownView.swift
// DropDownAlert
//
// Created by Cauê Silva on 06/06/17.
// Copyright © 2017 Caue Alves. All rights reserved.
//
import Foundation
import UIKit
class DropDownView: UIView {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var messageLabel: UILabel!
private var timer: Timer?
private var visibleTime: TimeInterval = 4.0
private var animationDuration: TimeInterval = 0.8
private var animationDelay: TimeInterval = 0
private var springDamping: CGFloat = 0.9
private var springVelocity: CGFloat = 0.2
var alertHeight: CGFloat {
return frame.height
}
override func awakeFromNib() {
super.awakeFromNib()
setAccessibilityIDs()
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.stopAnimation)))
}
private func setAccessibilityIDs() {
accessibilityIdentifier = "DropDownAlert.view"
messageLabel.accessibilityIdentifier = "DropDownAlert.alertImageView"
iconImageView.accessibilityIdentifier = "DropDownAlert.alertMessageLabel"
}
func startAnimation(alertDTO: DropDownAlertLayout) {
let dto = alertDTO.layoutDTO
backgroundColor = dto.backgroundColor
messageLabel.text = dto.message
messageLabel.textColor = dto.messageColor
iconImageView.image = dto.image
iconImageView.tintColor = dto.messageColor
self.visibleTime = dto.visibleTime
startAnimation()
}
private func startAnimation() {
print("# \(self.classForCoder): \(#function)")
DispatchQueue.main.safeAsync {
self.setAlertPosition(shouldDisplay: false)
UIView.animate(withDuration: self.animationDuration,
delay: self.animationDelay,
usingSpringWithDamping: self.springDamping,
initialSpringVelocity: self.springVelocity,
options: [],
animations: {
self.setAlertPosition(shouldDisplay: true) }, completion: nil)
self.timer = Timer.scheduledTimer(timeInterval: self.visibleTime, target: self, selector: #selector(self.stopAnimation), userInfo: nil, repeats: false)
}
}
func stopAnimation() {
print("# \(self.classForCoder): \(#function)")
timer?.invalidate()
DispatchQueue.main.safeAsync {
UIView.animate(withDuration: self.animationDuration, animations: {
self.setAlertPosition(shouldDisplay: false)
}, completion: { _ in
DispatchQueue.main.safeAsync {
self.removeFromSuperview()
}
})
}
}
private func setAlertPosition(shouldDisplay: Bool) {
var frame = self.frame
frame.origin.y = shouldDisplay ? 0 : -self.frame.size.width
self.frame = frame
}
}
| 0ae7b42ca9f6adef5ff97af52bbdb4c1 | 34.329412 | 163 | 0.626041 | false | false | false | false |
couchbits/iOSToolbox | refs/heads/master | Sources/Extensions/Foundation/DoubleExtensions.swift | mit | 1 | //
// DoubleExtensions.swift
// iOSToolbox
//
// Created by Dominik Gauggel on 13.09.17.
// Copyright © 2017 couchbits GmbH. All rights reserved.
//
import Foundation
public extension Double {
func equal(other: Double) -> Bool {
return abs(self.distance(to: other)) < 0.0001
}
static func equal(lhs: Double?, rhs: Double?) -> Bool {
if let lhs = lhs, let rhs = rhs {
return lhs.equal(other: rhs)
} else if lhs != nil {
return false
} else if rhs != nil {
return false
} else {
return true
}
}
}
public extension Optional where Wrapped == Double {
func equal(other: Double?) -> Bool {
guard let other = other else {
return self == nil
}
return self?.equal(other: other) ?? false
}
}
| 59315c44e836bff9d7f02721d2037c25 | 22.5 | 59 | 0.553191 | false | false | false | false |
netguru/inbbbox-ios | refs/heads/develop | Inbbbox/Source Files/Networking/PageRequest.swift | gpl-3.0 | 1 | //
// PageRequest.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 28/01/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import PromiseKit
import SwiftyJSON
typealias PageResponse = (json: JSON?, pages: (next: PageableComponent?, previous: PageableComponent?))
struct PageRequest: Requestable, Responsable {
/// Query used to create page request.
let query: Query
// Session for page request.
let session: URLSession
init(query: Query, urlSession: URLSession = URLSession.inbbboxDefaultSession()) {
self.query = query
session = urlSession
}
/// Invoke page request.
///
/// - returns: Promise which resolves with `PageResponse`
/// that contains response as JSON and components for
/// next and previous pages.
func resume() -> Promise<PageResponse> {
return Promise<PageResponse> { fulfill, reject in
do {
try APIRateLimitKeeper.sharedKeeper.verifyRateLimit()
} catch {
throw error
}
let dataTask = session.dataTask(with: foundationRequest as URLRequest) { data, response, error in
if let error = error {
reject(error); return
}
firstly {
self.responseWithData(data, response: response)
}.then { response -> Void in
var next: PageableComponent?
var previous: PageableComponent?
if let header = response.header {
next = PageableComponentSerializer.nextPageableComponentWithSentQuery(self.query,
receivedHeader: header)
previous = PageableComponentSerializer.previousPageableComponentWithSentQuery(self.query,
receivedHeader: header)
}
fulfill((
json: response.json,
pages: (
next: next,
previous: previous)
))
}.catch(execute: reject)
}
dataTask.resume()
}
}
}
| c0036678252819eccbdea4a23ea24b98 | 29.171053 | 113 | 0.536415 | false | false | false | false |
TsuiOS/LoveFreshBeen | refs/heads/master | LoveFreshBeenX/Class/Tools/Reflect/Dict2Model/Reflect+Parse.swift | mit | 1 | //
// Reflect+Parse.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
extension Reflect{
class func parsePlist(name: String) -> Self?{
let path = NSBundle.mainBundle().pathForResource(name+".plist", ofType: nil)
if path == nil {return nil}
let dict = NSDictionary(contentsOfFile: path!)
if dict == nil {return nil}
return parse(dict: dict!)
}
class func parses(arr arr: NSArray) -> [Reflect]{
var models: [Reflect] = []
for (_ , dict) in arr.enumerate(){
let model = self.parse(dict: dict as! NSDictionary)
models.append(model)
}
return models
}
class func parse(dict dict: NSDictionary) -> Self{
let model = self.init()
let mappingDict = model.mappingDict()
let ignoreProperties = model.ignorePropertiesForParse()
model.properties { (name, type, value) -> Void in
let dataDictHasKey = dict[name] != nil
let mappdictDictHasKey = mappingDict?[name] != nil
let needIgnore = ignoreProperties == nil ? false : (ignoreProperties!).contains(name)
if (dataDictHasKey || mappdictDictHasKey) && !needIgnore {
let key = mappdictDictHasKey ? mappingDict![name]! : name
if !type.isArray {
if !type.isReflect {
// print("==========\(type.realType),\(type.isOptional)")
if type.typeClass == Bool.self { //bool
model.setValue(dict[key]?.boolValue, forKeyPath: name)
}else if type.isOptional && type.realType == ReflectType.RealType.String{
let v = dict[key]
if v != nil {
let str_temp = "\(v!)"
model.setValue(str_temp, forKeyPath: name)
}
}else{
model.setValue(dict[key], forKeyPath: name)
}
}else{
//这里是模型
//首选判断字典中是否有值
let dictValue = dict[key]
if dictValue != nil { //字典中有模型
let modelValue = model.valueForKeyPath(key)
if modelValue != nil { //子模型已经初始化
model.setValue((type.typeClass as! Reflect.Type).parse(dict: dict[key] as! NSDictionary), forKeyPath: name)
}else{ //子模型没有初始化
//先主动初始化
let cls = ClassFromString(type.typeName)
model.setValue((cls as! Reflect.Type).parse(dict: dict[key] as! NSDictionary), forKeyPath: name)
}
}
}
}else{
if let res = type.isAggregate(){
var arrAggregate = []
if res is Int.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.Int, ins: 0)
}else if res is Float.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.Float, ins: 0.0)
}else if res is Double.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.Double, ins: 0.0)
}else if res is String.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.String, ins: "")
}else if res is NSNumber.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.NSNumber, ins: NSNumber())
}else{
arrAggregate = dict[key] as! [AnyObject]
}
model.setValue(arrAggregate, forKeyPath: name)
}else{
let elementModelType = ReflectType.makeClass(type) as! Reflect.Type
let dictKeyArr = dict[key] as! NSArray
var arrM: [Reflect] = []
for (_, value) in dictKeyArr.enumerate() {
let elementModel = elementModelType.parse(dict: value as! NSDictionary)
arrM.append(elementModel)
}
model.setValue(arrM, forKeyPath: name)
}
}
}
}
model.parseOver()
return model
}
class func parseAggregateArray<T>(arrDict: NSArray,basicType: ReflectType.BasicType, ins: T) -> [T]{
var intArrM: [T] = []
if arrDict.count == 0 {return intArrM}
for (_, value) in arrDict.enumerate() {
var element: T = ins
let v = "\(value)"
if T.self is Int.Type {
element = Int(Float(v)!) as! T
}
else if T.self is Float.Type {element = v.floatValue as! T}
else if T.self is Double.Type {element = v.doubleValue as! T}
else if T.self is NSNumber.Type {element = NSNumber(double: v.doubleValue!) as! T}
else{element = value as! T}
intArrM.append(element)
}
return intArrM
}
func mappingDict() -> [String: String]? {return nil}
func ignorePropertiesForParse() -> [String]? {return nil}
}
| 8f6cd0923c70cff3acb93b90da7d6060 | 34.865979 | 145 | 0.406295 | false | false | false | false |
zmian/xcore.swift | refs/heads/main | Sources/Xcore/Swift/Components/Validation/ValidationRule+Operators.swift | mit | 1 | //
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
// MARK: - Equatable
extension ValidationRule {
/// Returns a compound validation rule indicating whether two validation rules
/// are equal.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Returns: The validation rule.
public static func ==(lhs: Self, rhs: Self) -> Self {
.init { lhs.validate($0) == rhs.validate($0) }
}
/// Returns a compound validation rule indicating whether two validation rules
/// are not equal.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Returns: The validation rule.
public static func !=(lhs: Self, rhs: Self) -> Self {
.init { lhs.validate($0) != rhs.validate($0) }
}
}
// MARK: - Logical Operators
extension ValidationRule {
/// Returns a compound validation rule indicating whether two validation rules
/// are valid using logical operator `&&`.
///
/// ```swift
/// "[email protected]".validate(rule: .email && .whitelistedDomain) // valid
/// "help.example.com".validate(rule: .email && .whitelistedDomain) // invalid
/// "help.example.com".validate(rule: .email || .whitelistedDomain) // valid
/// ```
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Returns: The validation rule.
public static func &&(lhs: Self, rhs: @autoclosure @escaping () -> Self) -> Self {
.init { lhs.validate($0) && rhs().validate($0) }
}
/// Returns a compound validation rule indicating whether either of two
/// validation rules are valid using logical operator `||`.
///
/// ```swift
/// "[email protected]".validate(rule: .email && .whitelistedDomain) // valid
/// "help.example.com".validate(rule: .email && .whitelistedDomain) // invalid
/// "help.example.com".validate(rule: .email || .whitelistedDomain) // valid
/// ```
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Returns: The validation rule.
public static func ||(lhs: Self, rhs: @autoclosure @escaping () -> Self) -> Self {
.init { lhs.validate($0) || rhs().validate($0) }
}
/// Returns a negation validation rule.
///
/// ```swift
/// "[email protected]".validate(rule: !.email) // invalid
/// ```
///
/// - Parameter validation: The validation rule to negate.
/// - Returns: The validation rule.
public static prefix func !(_ rule: Self) -> Self {
.init { !rule.validate($0) }
}
}
| c09ab3dcb25227361fe2a3c6121b9fe6 | 32.168675 | 86 | 0.584453 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureTransaction/Sources/FeatureTransactionUI/Sell/SellFlowListener.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Foundation
import PlatformUIKit
protocol SellFlowListening: AnyObject {
func sellFlowDidComplete(with result: TransactionFlowResult)
func presentKYCFlow(from viewController: UIViewController, completion: @escaping (Bool) -> Void)
}
final class SellFlowListener: SellFlowListening {
private let subject = PassthroughSubject<TransactionFlowResult, Never>()
private let kycRouter: PlatformUIKit.KYCRouting
private let alertViewPresenter: PlatformUIKit.AlertViewPresenterAPI
private var cancellables = Set<AnyCancellable>()
init(
kycRouter: PlatformUIKit.KYCRouting = resolve(),
alertViewPresenter: PlatformUIKit.AlertViewPresenterAPI = resolve()
) {
self.kycRouter = kycRouter
self.alertViewPresenter = alertViewPresenter
}
var publisher: AnyPublisher<TransactionFlowResult, Never> {
subject.eraseToAnyPublisher()
}
deinit {
subject.send(completion: .finished)
}
func sellFlowDidComplete(with result: TransactionFlowResult) {
subject.send(result)
}
func presentKYCFlow(from viewController: UIViewController, completion: @escaping (Bool) -> Void) {
kycRouter.presentKYCUpgradeFlowIfNeeded(from: viewController, requiredTier: .tier2)
.receive(on: DispatchQueue.main)
.sink { [alertViewPresenter] completionResult in
guard case .failure(let error) = completionResult else {
return
}
alertViewPresenter.error(
in: viewController,
message: String(describing: error),
action: nil
)
} receiveValue: { result in
completion(result == .completed || result == .skipped)
}
.store(in: &cancellables)
}
}
| b56bfee14565cd46626321d79f2b2c3d | 32.586207 | 102 | 0.660164 | false | false | false | false |
ciamic/Smashtag | refs/heads/master | Smashtag/TweetImageViewController.swift | mit | 1 | //
// TweetImageViewController.swift
//
// Copyright (c) 2017 michelangelo
//
// 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 UIKit
///This ViewController is mostly reused from the Cassini project.
class TweetImageViewController: UIViewController {
// MARK: - Model
var imageURL: URL? {
didSet {
image = nil
if view.window != nil { //postpone image fetching if we are not on screen yet
fetchImage()
}
}
}
// we set this with "internal" accessibility level (was private in Cassini project)
// so that if we already have the downloaded image we can set it during prepare for segue
// to avoid to re-download it.
var image: UIImage? {
get {
return imageView.image
}
set {
imageView.image = newValue
imageView.sizeToFit()
scrollView?.contentSize = imageView.frame.size
spinner?.stopAnimating()
scrollViewHasBeenScrolledOrZoomed = false
scale()
centerImageInScrollView()
}
}
// MARK: - Outlets
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
scrollView.delegate = self
scrollView.minimumZoomScale = 0.5
scrollView.maximumZoomScale = 1.5
scrollView.addSubview(imageView)
scrollView.contentSize = imageView.frame.size
}
}
// MARK: - Properties
fileprivate var imageView = UIImageView()
fileprivate var scrollViewHasBeenScrolledOrZoomed = false
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
imageView.contentMode = .scaleAspectFit
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if image == nil { // we are going on screen so if necessary
fetchImage() // fetch the image
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scale()
centerImageInScrollView()
}
fileprivate func fetchImage() {
if let url = imageURL {
// fire up the spinner we're about to execute something on another thread
spinner?.startAnimating()
// put a closure on the "user initiated" system queue
// this closure calls NSData(contentsOfURL:) which blocks
// waiting for network response
// it's fine for it to block the "user initiated" queue
// because that's a concurrent queue
// (so other closures on that queue can run concurrently even as this one's blocked)
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
let contentsOfURL = try? Data(contentsOf: url) // blocks! can't be on main queue!
// now that we got the data from the network
// we want to put it up in the UI
// but we can only do that on the main queue
// so we queue up a closure here to do that
DispatchQueue.main.async { [weak self] in
// since it could take a long time to fetch the image data
// we make sure here that the image we fetched
// is still the one this ViewController wants to display
// and the controller (i.e. self) is still "alive"!
if url == self?.imageURL {
if let imageData = contentsOfURL {
self?.image = UIImage(data: imageData)
// setting the image will stop the spinner animating
} else {
self?.spinner?.stopAnimating()
}
} else {
// just to see in the console when this happens
debugPrint("ignored data returned from url \(url)")
}
}
}
}
}
// MARK: - Utility
fileprivate func scale() {
guard scrollView != nil, !scrollViewHasBeenScrolledOrZoomed,
imageView.bounds.size.width > 0, imageView.bounds.size.height > 0 else {
return
}
let widthScale = scrollView.bounds.size.width / imageView.bounds.size.width
let heightScale = scrollView.bounds.size.height / imageView.bounds.size.height
let minZoomScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minZoomScale
scrollView.zoomScale = minZoomScale
scrollView.maximumZoomScale = minZoomScale > 1 ? minZoomScale * 2 : 2
}
fileprivate func centerImageInScrollView() {
guard scrollView != nil else {
return
}
var imageViewContentsFrame = imageView.frame
//UIView.animate(withDuration: 0.25) {
if imageViewContentsFrame.size.width < self.scrollView.bounds.size.width {
imageViewContentsFrame.origin.x = (self.scrollView.bounds.size.width - imageViewContentsFrame.size.width) / 2.0
} else {
imageViewContentsFrame.origin.x = 0.0
}
if imageViewContentsFrame.size.height < self.scrollView.bounds.size.height {
imageViewContentsFrame.origin.y = (self.scrollView.bounds.size.height - imageViewContentsFrame.size.height) / 2.0
} else {
imageViewContentsFrame.origin.y = 0.0
}
self.imageView.frame = imageViewContentsFrame
//}
}
}
extension TweetImageViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollViewHasBeenScrolledOrZoomed = true
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollViewHasBeenScrolledOrZoomed = true
centerImageInScrollView()
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
| c2b6a2934e05713837670b9ba9d4edb0 | 36.923858 | 129 | 0.608085 | false | false | false | false |
allevato/swift-protobuf | refs/heads/master | Sources/PluginLibrary/CodePrinter.swift | apache-2.0 | 3 | // Sources/PluginLibrary/CodePrinter.swift - Code output
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This provides some basic indentation management for emitting structured
/// source code text.
///
// -----------------------------------------------------------------------------
/// Prints code with automatic indentation based on calls to `indent` and
/// `outdent`.
public struct CodePrinter {
/// Reserve an initial buffer of 64KB scalars to eliminate some reallocations
/// in smaller files.
private static let initialBufferSize = 65536
/// The string content that was printed.
public var content: String {
return String(contentScalars)
}
/// See if anything was printed.
public var isEmpty: Bool { return content.isEmpty }
/// The Unicode scalar buffer used to build up the printed contents.
private var contentScalars = String.UnicodeScalarView()
/// The `UnicodeScalarView` representing a single indentation step.
private let singleIndent: String.UnicodeScalarView
/// The current indentation level (a collection of spaces).
private var indentation = String.UnicodeScalarView()
/// Keeps track of whether the printer is currently sitting at the beginning
/// of a line.
private var atLineStart = true
public init(indent: String.UnicodeScalarView = " ".unicodeScalars) {
contentScalars.reserveCapacity(CodePrinter.initialBufferSize)
singleIndent = indent
}
/// Writes the given strings to the printer.
///
/// - Parameter text: A variable-length list of strings to be printed.
public mutating func print(_ text: String...) {
for t in text {
for scalar in t.unicodeScalars {
// Indent at the start of a new line, unless it's a blank line.
if atLineStart && scalar != "\n" {
contentScalars.append(contentsOf: indentation)
}
contentScalars.append(scalar)
atLineStart = (scalar == "\n")
}
}
}
/// Increases the printer's indentation level.
public mutating func indent() {
indentation.append(contentsOf: singleIndent)
}
/// Decreases the printer's indentation level.
///
/// - Precondition: The printer must not have an indentation level.
public mutating func outdent() {
let indentCount = singleIndent.count
precondition(indentation.count >= indentCount, "Cannot outdent past the left margin")
indentation.removeLast(indentCount)
}
}
| a63286a4fba67f0ebab54729b8974560 | 33.303797 | 89 | 0.667897 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/Calling/CallGridView/CallParticipantViews/BaseCallParticipantView.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2020 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 UIKit
import avs
import WireSyncEngine
class BaseCallParticipantView: OrientableView, AVSIdentifierProvider {
// MARK: - Public Properties
var stream: Stream {
didSet {
updateUserDetails()
updateBorderStyle()
updateVideoKind()
hideVideoViewsIfNeeded()
}
}
var shouldShowActiveSpeakerFrame: Bool {
didSet {
updateBorderStyle()
}
}
var shouldShowBorderWhenVideoIsStopped: Bool {
didSet {
updateBorderStyle()
}
}
/// indicates wether or not the view is shown in full in the grid
var isMaximized: Bool = false {
didSet {
updateBorderStyle()
updateFillMode()
updateScalableView()
}
}
var shouldFill: Bool {
return isMaximized ? false : videoKind.shouldFill
}
let userDetailsView = CallParticipantDetailsView()
var scalableView: ScalableView?
var avatarView = UserImageView(size: .normal)
var userSession = ZMUserSession.shared()
private(set) var videoView: AVSVideoViewProtocol?
// MARK: - Private Properties
private var delta: OrientationDelta = OrientationDelta()
private var detailsConstraints: UserDetailsConstraints?
private var isCovered: Bool
private var adjustedInsets: UIEdgeInsets {
safeAreaInsetsOrFallback.adjusted(for: delta)
}
private var userDetailsAlpha: CGFloat {
isCovered ? 0 : 1
}
// MARK: - View Life Cycle
init(stream: Stream,
isCovered: Bool,
shouldShowActiveSpeakerFrame: Bool,
shouldShowBorderWhenVideoIsStopped: Bool,
pinchToZoomRule: PinchToZoomRule) {
self.stream = stream
self.isCovered = isCovered
self.shouldShowActiveSpeakerFrame = shouldShowActiveSpeakerFrame
self.shouldShowBorderWhenVideoIsStopped = shouldShowBorderWhenVideoIsStopped
self.pinchToZoomRule = pinchToZoomRule
super.init(frame: .zero)
setupViews()
createConstraints()
updateUserDetails()
updateVideoKind()
updateBorderStyle()
hideVideoViewsIfNeeded()
NotificationCenter.default.addObserver(self, selector: #selector(updateUserDetailsVisibility), name: .videoGridVisibilityChanged, object: nil)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup
func updateUserDetails() {
userDetailsView.name = stream.user?.name
userDetailsView.microphoneIconStyle = MicrophoneIconStyle(state: stream.microphoneState, shouldPulse: stream.activeSpeakerState.isSpeakingNow)
userDetailsView.alpha = userDetailsAlpha
}
func setupViews() {
addSubview(avatarView)
addSubview(userDetailsView)
backgroundColor = .graphite
avatarView.user = stream.user
avatarView.userSession = userSession
userDetailsView.alpha = 0
}
func createConstraints() {
[avatarView, userDetailsView].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
}
detailsConstraints = UserDetailsConstraints(
view: userDetailsView,
superview: self,
safeAreaInsets: adjustedInsets
)
NSLayoutConstraint.activate([
userDetailsView.heightAnchor.constraint(equalToConstant: 24),
avatarView.centerXAnchor.constraint(equalTo: centerXAnchor),
avatarView.centerYAnchor.constraint(equalTo: centerYAnchor),
avatarView.widthAnchor.constraint(equalToConstant: 88),
avatarView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, multiplier: 0.7),
avatarView.heightAnchor.constraint(equalTo: avatarView.widthAnchor)
])
}
private func hideVideoViewsIfNeeded() {
scalableView?.isHidden = !stream.isSharingVideo
}
// MARK: - Pinch To Zoom
var pinchToZoomRule: PinchToZoomRule {
didSet {
guard oldValue != pinchToZoomRule else { return }
updateScalableView()
}
}
func updateScalableView() {
scalableView?.isScalingEnabled = shouldEnableScaling
}
var shouldEnableScaling: Bool {
switch pinchToZoomRule {
case .enableWhenFitted:
return !shouldFill
case .enableWhenMaximized:
return isMaximized
}
}
// MARK: - Fill Mode
private var videoKind: VideoKind = .none {
didSet {
guard oldValue != videoKind else { return }
updateFillMode()
updateScalableView()
}
}
private func updateVideoKind() {
videoKind = VideoKind(videoState: stream.videoState)
}
private func updateFillMode() {
// Reset scale if the view was zoomed in
scalableView?.resetScale()
videoView?.shouldFill = shouldFill
}
// MARK: - Border Style
private func updateBorderStyle() {
let showBorderForActiveSpeaker = shouldShowActiveSpeakerFrame && stream.isParticipantUnmutedAndSpeakingNow
let showBorderForAudioParticipant = shouldShowBorderWhenVideoIsStopped && !stream.isSharingVideo
layer.borderWidth = (showBorderForActiveSpeaker || showBorderForAudioParticipant) && !isMaximized ? 1 : 0
layer.borderColor = showBorderForActiveSpeaker ? UIColor.accent().cgColor : UIColor.black.cgColor
}
// MARK: - Orientation & Layout
override func layoutSubviews() {
super.layoutSubviews()
detailsConstraints?.updateEdges(with: adjustedInsets)
}
func layout(forInterfaceOrientation interfaceOrientation: UIInterfaceOrientation,
deviceOrientation: UIDeviceOrientation) {
guard let superview = superview else { return }
delta = .equal
transform = CGAffineTransform(rotationAngle: delta.radians)
frame = superview.bounds
layoutSubviews()
}
// MARK: - Visibility
@objc private func updateUserDetailsVisibility(_ notification: Notification?) {
guard let isCovered = notification?.userInfo?[CallGridViewController.isCoveredKey] as? Bool else {
return
}
self.isCovered = isCovered
UIView.animate(
withDuration: 0.2,
delay: 0,
options: [.curveEaseInOut, .beginFromCurrentState],
animations: {
self.userDetailsView.alpha = self.userDetailsAlpha
})
}
// MARK: - Accessibility for automation
override var accessibilityIdentifier: String? {
get {
let name = stream.user?.name ?? ""
let maximizationState = isMaximized ? "maximized" : "minimized"
let activityState = stream.isParticipantUnmutedAndActive ? "active" : "inactive"
let viewKind = stream.isSharingVideo ? "videoView" : "audioView"
return "\(viewKind).\(name).\(maximizationState).\(activityState)"
}
set {}
}
}
// MARK: - User Details Constraints
private struct UserDetailsConstraints {
private let bottom: NSLayoutConstraint
private let leading: NSLayoutConstraint
private let trailing: NSLayoutConstraint
private let margin: CGFloat = 8
init(view: UIView, superview: UIView, safeAreaInsets insets: UIEdgeInsets) {
bottom = view.bottomAnchor.constraint(equalTo: superview.bottomAnchor)
leading = view.leadingAnchor.constraint(equalTo: superview.leadingAnchor)
trailing = view.trailingAnchor.constraint(lessThanOrEqualTo: superview.trailingAnchor)
updateEdges(with: insets)
NSLayoutConstraint.activate([bottom, leading, trailing])
}
func updateEdges(with insets: UIEdgeInsets) {
leading.constant = margin + insets.left
trailing.constant = -(margin + insets.right)
bottom.constant = -(margin + insets.bottom)
}
}
| 5d13d8893c87428d377d5bc7dc5e86a6 | 30.713768 | 150 | 0.664458 | false | false | false | false |
MessageKit/MessageKit | refs/heads/main | Sources/Controllers/MessagesViewController+Menu.swift | mit | 1 | // MIT License
//
// Copyright (c) 2017-2022 MessageKit
//
// 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 UIKit
extension MessagesViewController {
// MARK: Internal
// MARK: - Register / Unregister Observers
internal func addMenuControllerObservers() {
NotificationCenter.default.addObserver(
self,
selector: #selector(MessagesViewController.menuControllerWillShow(_:)),
name: UIMenuController.willShowMenuNotification,
object: nil)
}
internal func removeMenuControllerObservers() {
NotificationCenter.default.removeObserver(self, name: UIMenuController.willShowMenuNotification, object: nil)
}
// MARK: Private
// MARK: - Helpers
private var navigationBarFrame: CGRect {
guard let navigationController = navigationController, !navigationController.navigationBar.isHidden else {
return .zero
}
return navigationController.navigationBar.frame
}
// MARK: - Notification Handlers
/// Show menuController and set target rect to selected bubble
@objc
private func menuControllerWillShow(_ notification: Notification) {
guard
let currentMenuController = notification.object as? UIMenuController,
let selectedIndexPath = selectedIndexPathForMenu else { return }
NotificationCenter.default.removeObserver(self, name: UIMenuController.willShowMenuNotification, object: nil)
defer {
NotificationCenter.default.addObserver(
self,
selector: #selector(MessagesViewController.menuControllerWillShow(_:)),
name: UIMenuController.willShowMenuNotification,
object: nil)
selectedIndexPathForMenu = nil
}
currentMenuController.hideMenu()
guard let selectedCell = messagesCollectionView.cellForItem(at: selectedIndexPath) as? MessageContentCell else {
return
}
let selectedCellMessageBubbleFrame = selectedCell.convert(selectedCell.messageContainerView.frame, to: view)
var messageInputBarFrame: CGRect = .zero
if let messageInputBarSuperview = messageInputBar.superview {
messageInputBarFrame = view.convert(messageInputBar.frame, from: messageInputBarSuperview)
}
var topNavigationBarFrame: CGRect = navigationBarFrame
if navigationBarFrame != .zero, let navigationBarSuperview = navigationController?.navigationBar.superview {
topNavigationBarFrame = view.convert(navigationController!.navigationBar.frame, from: navigationBarSuperview)
}
let menuHeight = currentMenuController.menuFrame.height
let selectedCellMessageBubblePlusMenuFrame = CGRect(
selectedCellMessageBubbleFrame.origin.x,
selectedCellMessageBubbleFrame.origin.y - menuHeight,
selectedCellMessageBubbleFrame.size.width,
selectedCellMessageBubbleFrame.size.height + 2 * menuHeight)
var targetRect: CGRect = selectedCellMessageBubbleFrame
currentMenuController.arrowDirection = .default
/// Message bubble intersects with navigationBar and keyboard
if
selectedCellMessageBubblePlusMenuFrame.intersects(topNavigationBarFrame),
selectedCellMessageBubblePlusMenuFrame.intersects(messageInputBarFrame)
{
let centerY = (
selectedCellMessageBubblePlusMenuFrame.intersection(messageInputBarFrame)
.minY + selectedCellMessageBubblePlusMenuFrame.intersection(topNavigationBarFrame).maxY) / 2
targetRect = CGRect(selectedCellMessageBubblePlusMenuFrame.midX, centerY, 1, 1)
} /// Message bubble only intersects with navigationBar
else if selectedCellMessageBubblePlusMenuFrame.intersects(topNavigationBarFrame) {
currentMenuController.arrowDirection = .up
}
currentMenuController.showMenu(from: view, rect: targetRect)
}
}
| 53728e32e13b4f6bb809a12bdec37c6d | 39.641026 | 116 | 0.765931 | false | false | false | false |
phatblat/realm-cocoa | refs/heads/master | RealmSwift/Tests/CompactionTests.swift | apache-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// 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 RealmSwift
// MARK: Expected Sizes
private var expectedTotalBytesBefore = 0
private let expectedUsedBytesBeforeMin = 50000
private var count = 1000
// MARK: Helpers
private func fileSize(path: String) -> Int {
let attributes = try! FileManager.default.attributesOfItem(atPath: path)
return attributes[.size] as! Int
}
// MARK: Tests
class CompactionTests: TestCase {
override func setUp() {
super.setUp()
autoreleasepool {
// Make compactable Realm
let realm = realmWithTestPath()
let uuid = UUID().uuidString
try! realm.write {
realm.create(SwiftStringObject.self, value: ["A"])
for _ in 0..<count {
realm.create(SwiftStringObject.self, value: [uuid])
}
realm.create(SwiftStringObject.self, value: ["B"])
}
}
expectedTotalBytesBefore = fileSize(path: testRealmURL().path)
}
func testSuccessfulCompactOnLaunch() {
// Configure the Realm to compact on launch
let config = Realm.Configuration(fileURL: testRealmURL(),
shouldCompactOnLaunch: { totalBytes, usedBytes in
// Confirm expected sizes
XCTAssertEqual(totalBytes, expectedTotalBytesBefore)
XCTAssert((usedBytes < totalBytes) && (usedBytes > expectedUsedBytesBeforeMin))
return true
})
// Confirm expected sizes before and after opening the Realm
XCTAssertEqual(fileSize(path: config.fileURL!.path), expectedTotalBytesBefore)
let realm = try! Realm(configuration: config)
XCTAssertLessThan(fileSize(path: config.fileURL!.path), expectedTotalBytesBefore)
// Validate that the file still contains what it should
XCTAssertEqual(realm.objects(SwiftStringObject.self).count, count + 2)
XCTAssertEqual("A", realm.objects(SwiftStringObject.self).first?.stringCol)
XCTAssertEqual("B", realm.objects(SwiftStringObject.self).last?.stringCol)
}
}
| 57a24c0c7989120d90519f7478d1cd72 | 36.88 | 91 | 0.6283 | false | true | false | false |
mattiaberretti/MBDesign | refs/heads/master | MBDesign/Classes/Testo/BaseTextField.swift | mit | 1 | //
// BaseTextField.swift
// MaterialDesign
//
// Created by Mattia on 29/05/18.
//
import UIKit
public class BaseTextField: UITextField, TextField {
@IBOutlet
public var nextField : TextField?
@IBOutlet
public var previusField : TextField?
@IBInspectable
public var showDone : Bool = true
@IBOutlet
public var scrollItem: ScrollableItem?
private var scrollManager : ScrollManager!
override public func awakeFromNib() {
super.awakeFromNib()
if self.mostraBarra {
let dimensioni = UIScreen.main.bounds
let barra = UINavigationBar(frame: CGRect(x: 0, y: -44, width: dimensioni.size.width, height: 44))
barra.items = [self.barra]
self.inputAccessoryView = barra
}
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: OperationQueue.main) { (notifica) in
guard let manager = self.scrollManager else { return }
guard let frame = notifica.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
manager.scroll(altezzaTastiera: frame.size.height)
}
}
private var mostraBarra : Bool {
return showDone || nextField != nil || previusField != nil
}
private lazy var doneBtn: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneBtn(_:)))
}()
private lazy var backBtn: UIBarButtonItem = {
let ritorno = UIBarButtonItem(title: "<", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.backBtn(_:)))
if self.previusField == nil {
ritorno.isEnabled = false
}
return ritorno
}()
private lazy var nextBtn: UIBarButtonItem = {
let ritorno = UIBarButtonItem(title: ">", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.nextBtn(_:)))
if self.nextField == nil {
ritorno.isEnabled = false
}
return ritorno
}()
lazy var barra: UINavigationItem = {
let item = UINavigationItem(title: self.placeholder ?? "")
item.rightBarButtonItem = self.doneBtn
item.leftBarButtonItems = [self.backBtn, self.nextBtn]
return item
}()
@objc
private func nextBtn(_ sender : UIBarButtonItem){
guard let prossimo = self.nextField else {
return
}
let _ = prossimo.becomeFirstResponder()
}
@objc
private func backBtn(_ sender : UIBarButtonItem){
guard let precedente = self.previusField else {
return
}
let _ = precedente.becomeFirstResponder()
}
@objc
private func doneBtn(_ sender : UIBarButtonItem){
let _ = self.resignFirstResponder()
}
override public func resignFirstResponder() -> Bool {
self.scrollManager?.destroy()
self.scrollManager = nil
return super.resignFirstResponder()
}
override public func becomeFirstResponder() -> Bool {
if let item = self.scrollItem {
self.scrollManager = ScrollManager(testo: self, container: item)
}
return super.becomeFirstResponder()
}
}
| 0ebd76c1b6b16fb6fd4006ee483af54f | 30.504673 | 161 | 0.619104 | false | false | false | false |
remlostime/OOD-Swift | refs/heads/master | Command/command.playground/Contents.swift | gpl-3.0 | 1 | //: Playground - noun: a place where people can play
protocol Command {
func execute()
}
class OpenCommand: Command {
func execute() {
print("Open \(door)")
}
init(_ door: String) {
self.door = door
}
let door: String
}
class CloseCommand: Command {
func execute() {
print("Close \(door)")
}
init(_ door: String) {
self.door = door
}
let door: String
}
class Door {
let openCommand: OpenCommand
let closeCommand: CloseCommand
init(_ door: String) {
openCommand = OpenCommand(door)
closeCommand = CloseCommand(door)
}
func open() {
openCommand.execute()
}
func close() {
closeCommand.execute()
}
}
let door = Door("Gogogo")
door.open()
door.close()
| 950fa261e8282568fb4d5195ba6a93b6 | 13.588235 | 52 | 0.611559 | false | false | false | false |
sendyhalim/Yomu | refs/heads/master | Yomu/Common/Extensions/NSView.swift | mit | 1 | //
// TextInput.swift
// Yomu
//
// Created by Sendy Halim on 8/7/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import AppKit
struct Border {
let position: BorderPosition
let width: CGFloat
let color: NSColor
let radius: CGFloat
init(position: BorderPosition, width: CGFloat, color: NSColor, radius: CGFloat = 0.0) {
self.position = position
self.width = width
self.color = color
self.radius = radius
}
}
enum BorderPosition {
case all
case left
case top
case right
case bottom
}
extension NSView {
/// Draw border based on the given `Border` spec
///
/// - parameter border: `Border` spec
func drawBorder(_ border: Border) {
wantsLayer = true
switch border.position {
case .all:
drawBorderAtLeft(width: border.width, radius: border.radius, color: border.color)
drawBorderAtTop(width: border.width, radius: border.radius, color: border.color)
drawBorderAtRight(width: border.width, radius: border.radius, color: border.color)
drawBorderAtBottom(width: border.width, radius: border.radius, color: border.color)
case .left:
drawBorderAtLeft(width: border.width, radius: border.radius, color: border.color)
case .top:
drawBorderAtTop(width: border.width, radius: border.radius, color: border.color)
case .right:
drawBorderAtRight(width: border.width, radius: border.radius, color: border.color)
case .bottom:
drawBorderAtBottom(width: border.width, radius: border.radius, color: border.color)
}
}
/// Draw a border (rectangle) at left
///
/// - parameter borderWidth: Border width in point
/// - parameter radius: Border radius
/// - parameter color: Border color
fileprivate func drawBorderAtLeft(width borderWidth: CGFloat, radius: CGFloat, color: NSColor) {
let borderFrame = CGRect(
x: 0,
y: 0,
width: borderWidth,
height: frame.size.height
)
drawBorder(frame: borderFrame, width: borderWidth, radius: radius, color: color)
}
/// Draw a border (rectangle) at top
///
/// - parameter borderWidth: Border width in point
/// - parameter radius: Border radius
/// - parameter color: Border color
fileprivate func drawBorderAtTop(width borderWidth: CGFloat, radius: CGFloat, color: NSColor) {
let yPosition = isFlipped ? 0 : frame.size.height - borderWidth
let borderFrame = CGRect(
x: 0,
y: yPosition,
width: frame.size.width,
height: borderWidth
)
drawBorder(frame: borderFrame, width: borderWidth, radius: radius, color: color)
}
/// Draw a border (rectangle) at right
///
/// - parameter borderWidth: Border width in point
/// - parameter radius: Border radius
/// - parameter color: Border color
fileprivate func drawBorderAtRight(width borderWidth: CGFloat, radius: CGFloat, color: NSColor) {
let borderFrame = CGRect(
x: frame.size.width - borderWidth,
y: 0,
width: borderWidth,
height: frame.size.height
)
drawBorder(frame: borderFrame, width: borderWidth, radius: radius, color: color)
}
/// Draw a border (rectangle) at bottom
///
/// - parameter borderWidth: Border width in point
/// - parameter radius: Border radius
/// - parameter color: Border color
fileprivate func drawBorderAtBottom(width borderWidth: CGFloat, radius: CGFloat, color: NSColor) {
let yPosition = isFlipped ? frame.size.height - borderWidth : 0
let borderFrame = CGRect(
x: 0,
y: yPosition,
width: frame.size.width,
height: borderWidth
)
drawBorder(frame: borderFrame, width: borderWidth, radius: radius, color: color)
}
/// Draw border based on the given frame, will use layer to draw the border.
///
/// - parameter borderFrame: Border layer frame
/// - parameter borderWidth: Border width in point
/// - parameter radius: Border radius
/// - parameter color: Border color
fileprivate func drawBorder(
frame borderFrame: CGRect,
width: CGFloat,
radius: CGFloat,
color: NSColor
) {
let borderLayer = CALayer()
borderLayer.borderColor = color.cgColor
borderLayer.masksToBounds = true
borderLayer.borderWidth = width
borderLayer.cornerRadius = radius
borderLayer.frame = borderFrame
layer?.addSublayer(borderLayer)
}
}
| 85320c1fb38f3b889a56e622e7eade47 | 28.624161 | 100 | 0.668781 | false | false | false | false |
Finb/V2ex-Swift | refs/heads/master | View/RightNodeTableViewCell.swift | mit | 1 | //
// RightNodeTableViewCell.swift
// V2ex-Swift
//
// Created by huangfeng on 1/23/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class RightNodeTableViewCell: UITableViewCell {
var nodeNameLabel: UILabel = {
let label = UILabel()
label.font = v2Font(15)
return label
}()
var panel = UIView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.setup();
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup()->Void{
self.selectionStyle = .none
self.backgroundColor = UIColor.clear
self.contentView.addSubview(panel)
self.panel.snp.makeConstraints{ (make) -> Void in
make.left.top.right.equalTo(self.contentView)
make.bottom.equalTo(self.contentView).offset(-1 * SEPARATOR_HEIGHT)
}
panel.addSubview(self.nodeNameLabel)
self.nodeNameLabel.snp.makeConstraints{ (make) -> Void in
make.right.equalTo(panel).offset(-22)
make.centerY.equalTo(panel)
}
self.themeChangedHandler = {[weak self] (style) -> Void in
self?.refreshBackgroundColor()
self?.nodeNameLabel.textColor = V2EXColor.colors.v2_LeftNodeTintColor
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated);
self.refreshBackgroundColor()
}
func refreshBackgroundColor() {
if self.isSelected {
self.panel.backgroundColor = V2EXColor.colors.v2_LeftNodeBackgroundHighLightedColor
}
else{
self.panel.backgroundColor = V2EXColor.colors.v2_LeftNodeBackgroundColor
}
}
}
| e5fd9e788fd5fbc995cdbc6f41976a3c | 29.269841 | 95 | 0.619297 | false | false | false | false |
devxoul/Carte | refs/heads/master | Sources/Carte/CarteViewController.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if os(iOS)
import UIKit
open class CarteViewController: UITableViewController {
open lazy var items = Carte.items
open var configureDetailViewController: ((CarteDetailViewController) -> Void)?
override open func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("Open Source Licenses", comment: "Open Source Licenses")
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.adjustLeftBarButtonItemIfNeeded()
}
private func adjustLeftBarButtonItemIfNeeded() {
guard self.navigationItem.leftBarButtonItem == nil else { return }
let isPresented = (self.presentingViewController != nil)
if isPresented {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(self.doneButtonDidTap)
)
}
}
@objc open dynamic func doneButtonDidTap() {
self.dismiss(animated: true)
}
}
extension CarteViewController {
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = self.items[indexPath.row]
cell.textLabel?.text = item.displayName
cell.detailTextLabel?.text = item.licenseName
cell.accessoryType = .disclosureIndicator
return cell
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let carteItem = self.items[indexPath.row]
let detailViewController = CarteDetailViewController(item: carteItem)
self.configureDetailViewController?(detailViewController)
self.navigationController?.pushViewController(detailViewController, animated: true)
}
}
open class CarteDetailViewController: UIViewController {
public let carteItem: CarteItem
open var textView: UITextView = {
let textView = UITextView()
textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
textView.font = UIFont.preferredFont(forTextStyle: .footnote)
textView.isEditable = false
textView.alwaysBounceVertical = true
textView.dataDetectorTypes = .link
return textView
}()
public init(item: CarteItem) {
self.carteItem = item
super.init(nibName: nil, bundle: nil)
self.title = item.displayName
self.textView.text = item.licenseText
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func viewDidLoad() {
self.view.backgroundColor = UIColor.white
self.textView.frame = self.view.bounds
self.textView.contentOffset = .zero
self.view.addSubview(self.textView)
}
}
#endif
| f6171854b5cc7c9473cdbabd3c9b82ac | 35.121739 | 112 | 0.743621 | false | false | false | false |
riteshhgupta/RGListKit | refs/heads/master | Carthage/Checkouts/ReactiveCocoa/Carthage/Checkouts/ReactiveSwift/Sources/Signal.swift | mit | 3 | import Foundation
import Result
/// A push-driven stream that sends Events over time, parameterized by the type
/// of values being sent (`Value`) and the type of failure that can occur
/// (`Error`). If no failures should be possible, NoError can be specified for
/// `Error`.
///
/// An observer of a Signal will see the exact same sequence of events as all
/// other observers. In other words, events will be sent to all observers at the
/// same time.
///
/// Signals are generally used to represent event streams that are already “in
/// progress,” like notifications, user input, etc. To represent streams that
/// must first be _started_, see the SignalProducer type.
///
/// A Signal is kept alive until either of the following happens:
/// 1. its input observer receives a terminating event; or
/// 2. it has no active observers, and is not being retained.
public final class Signal<Value, Error: Swift.Error> {
/// The `Signal` core which manages the event stream.
///
/// A `Signal` is the externally retained shell of the `Signal` core. The separation
/// enables an explicit metric for the `Signal` self-disposal in case of having no
/// observer and no external retain.
///
/// `Signal` ownership graph from the perspective of an operator.
/// Note that there is no circular strong reference in the graph.
/// ```
/// ------------ -------------- --------
/// | | | endObserve | | |
/// | | <~~ weak ~~~ | disposable | <== strong === | |
/// | | -------------- | | ... downstream(s)
/// | Upstream | ------------ | |
/// | Core | === strong ==> | Observer | === strong ==> | Core |
/// ------------ ===\\ ------------ -------- ===\\
/// \\ ------------------ ^^ \\
/// \\ | Signal (shell) | === strong ==// \\
/// \\ ------------------ \\
/// || strong || strong
/// vv vv
/// ------------------- -------------------
/// | Other observers | | Other observers |
/// ------------------- -------------------
/// ```
private let core: Core
private final class Core {
/// The disposable associated with the signal.
///
/// Disposing of `disposable` is assumed to remove the generator
/// observer from its attached `Signal`, so that the generator observer
/// as the last +1 retain of the `Signal` core may deinitialize.
private let disposable: CompositeDisposable
/// The state of the signal.
private var state: State
/// Used to ensure that all state accesses are serialized.
private let stateLock: Lock
/// Used to ensure that events are serialized during delivery to observers.
private let sendLock: Lock
fileprivate init(_ generator: (Observer, Lifetime) -> Void) {
state = .alive(Bag(), hasDeinitialized: false)
stateLock = Lock.make()
sendLock = Lock.make()
disposable = CompositeDisposable()
// The generator observer retains the `Signal` core.
generator(Observer(action: self.send, interruptsOnDeinit: true), Lifetime(disposable))
}
private func send(_ event: Event) {
if event.isTerminating {
// Recursive events are disallowed for `value` events, but are permitted
// for termination events. Specifically:
//
// - `interrupted`
// It can inadvertently be sent by downstream consumers as part of the
// `SignalProducer` mechanics.
//
// - `completed`
// If a downstream consumer weakly references an object, invocation of
// such consumer may cause a race condition with its weak retain against
// the last strong release of the object. If the `Lifetime` of the
// object is being referenced by an upstream `take(during:)`, a
// signal recursion might occur.
//
// So we would treat termination events specially. If it happens to
// occur while the `sendLock` is acquired, the observer call-out and
// the disposal would be delegated to the current sender, or
// occasionally one of the senders waiting on `sendLock`.
self.stateLock.lock()
if case let .alive(observers, _) = state {
self.state = .terminating(observers, .init(event))
self.stateLock.unlock()
} else {
self.stateLock.unlock()
}
tryToCommitTermination()
} else {
self.sendLock.lock()
self.stateLock.lock()
if case let .alive(observers, _) = self.state {
self.stateLock.unlock()
for observer in observers {
observer.send(event)
}
} else {
self.stateLock.unlock()
}
self.sendLock.unlock()
// Check if the status has been bumped to `terminating` due to a
// terminal event being sent concurrently or recursively.
//
// The check is deliberately made outside of the `sendLock` so that it
// covers also any potential concurrent terminal event in one shot.
//
// Related PR:
// https://github.com/ReactiveCocoa/ReactiveSwift/pull/112
//
// While calling `tryToCommitTermination` is sufficient, this is a fast
// path for the recurring value delivery.
//
// Note that this cannot be `try` since any concurrent observer bag
// manipulation might then cause the terminating state being missed.
stateLock.lock()
if case .terminating = state {
stateLock.unlock()
tryToCommitTermination()
} else {
stateLock.unlock()
}
}
}
/// Observe the Signal by sending any future events to the given observer.
///
/// - parameters:
/// - observer: An observer to forward the events to.
///
/// - returns: A `Disposable` which can be used to disconnect the observer,
/// or `nil` if the signal has already terminated.
fileprivate func observe(_ observer: Observer) -> Disposable? {
var token: Bag<Observer>.Token?
stateLock.lock()
if case let .alive(observers, hasDeinitialized) = state {
var newObservers = observers
token = newObservers.insert(observer)
self.state = .alive(newObservers, hasDeinitialized: hasDeinitialized)
}
stateLock.unlock()
if let token = token {
return AnyDisposable { [weak self] in
self?.removeObserver(with: token)
}
} else {
observer.sendInterrupted()
return nil
}
}
/// Remove the observer associated with the given token.
///
/// - parameters:
/// - token: The token of the observer to remove.
private func removeObserver(with token: Bag<Observer>.Token) {
stateLock.lock()
if case let .alive(observers, hasDeinitialized) = state {
var newObservers = observers
let observer = newObservers.remove(using: token)
self.state = .alive(newObservers, hasDeinitialized: hasDeinitialized)
// Ensure `observer` is deallocated after `stateLock` is
// released to avoid deadlocks.
withExtendedLifetime(observer) {
// Start the disposal of the `Signal` core if the `Signal` has
// deinitialized and there is no active observer.
tryToDisposeSilentlyIfQualified(unlocking: stateLock)
}
} else {
stateLock.unlock()
}
}
/// Try to commit the termination, or in other words transition the signal from a
/// terminating state to a terminated state.
///
/// It fails gracefully if the signal is alive or has terminated. Calling this
/// method as a result of a false positive `terminating` check is permitted.
///
/// - precondition: `stateLock` must not be acquired by the caller.
private func tryToCommitTermination() {
// Acquire `stateLock`. If the termination has still not yet been
// handled, take it over and bump the status to `terminated`.
stateLock.lock()
if case let .terminating(observers, terminationKind) = state {
// Try to acquire the `sendLock`, and fail gracefully since the current
// lock holder would attempt to commit after it is done anyway.
if sendLock.try() {
state = .terminated
stateLock.unlock()
if let event = terminationKind.materialize() {
for observer in observers {
observer.send(event)
}
}
sendLock.unlock()
disposable.dispose()
return
}
}
stateLock.unlock()
}
/// Try to dispose of the signal silently if the `Signal` has deinitialized and
/// has no observer.
///
/// It fails gracefully if the signal is terminating or terminated, has one or
/// more observers, or has not deinitialized.
///
/// - precondition: `stateLock` must have been acquired by the caller.
///
/// - parameters:
/// - stateLock: The `stateLock` acquired by the caller.
private func tryToDisposeSilentlyIfQualified(unlocking stateLock: Lock) {
assert(!stateLock.try(), "Calling `unconditionallyTerminate` without acquiring `stateLock`.")
if case let .alive(observers, true) = state, observers.isEmpty {
// Transition to `terminated` directly only if there is no event delivery
// on going.
if sendLock.try() {
self.state = .terminated
stateLock.unlock()
sendLock.unlock()
disposable.dispose()
return
}
self.state = .terminating(Bag(), .silent)
stateLock.unlock()
tryToCommitTermination()
return
}
stateLock.unlock()
}
/// Acknowledge the deinitialization of the `Signal`.
fileprivate func signalDidDeinitialize() {
stateLock.lock()
// Mark the `Signal` has now deinitialized.
if case let .alive(observers, false) = state {
state = .alive(observers, hasDeinitialized: true)
}
// Attempt to start the disposal of the signal if it has no active observer.
tryToDisposeSilentlyIfQualified(unlocking: stateLock)
}
deinit {
disposable.dispose()
}
}
/// Initialize a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// - note: The disposable returned from the closure will be automatically
/// disposed if a terminating event is sent to the observer. The
/// Signal itself will remain alive until the observer is released.
///
/// - parameters:
/// - generator: A closure that accepts an implicitly created observer
/// that will act as an event emitter for the signal.
public init(_ generator: (Observer, Lifetime) -> Void) {
core = Core(generator)
}
/// Observe the Signal by sending any future events to the given observer.
///
/// - note: If the Signal has already terminated, the observer will
/// immediately receive an `interrupted` event.
///
/// - parameters:
/// - observer: An observer to forward the events to.
///
/// - returns: A `Disposable` which can be used to disconnect the observer,
/// or `nil` if the signal has already terminated.
@discardableResult
public func observe(_ observer: Observer) -> Disposable? {
return core.observe(observer)
}
deinit {
core.signalDidDeinitialize()
}
/// The state of a `Signal`.
///
/// `SignalState` is guaranteed to be laid out as a tagged pointer by the Swift
/// compiler in the support targets of the Swift 3.0.1 ABI.
///
/// The Swift compiler has also an optimization for enums with payloads that are
/// all reference counted, and at most one no-payload case.
private enum State {
// `TerminationKind` is constantly pointer-size large to keep `Signal.Core`
// allocation size independent of the actual `Value` and `Error` types.
enum TerminationKind {
case completed
case interrupted
case failed(Swift.Error)
case silent
init(_ event: Event) {
switch event {
case .value:
fatalError()
case .interrupted:
self = .interrupted
case let .failed(error):
self = .failed(error)
case .completed:
self = .completed
}
}
func materialize() -> Event? {
switch self {
case .completed:
return .completed
case .interrupted:
return .interrupted
case let .failed(error):
return .failed(error as! Error)
case .silent:
return nil
}
}
}
/// The `Signal` is alive.
case alive(Bag<Observer>, hasDeinitialized: Bool)
/// The `Signal` has received a termination event, and is about to be
/// terminated.
case terminating(Bag<Observer>, TerminationKind)
/// The `Signal` has terminated.
case terminated
}
}
extension Signal {
/// A Signal that never sends any events to its observers.
public static var never: Signal {
return self.init { observer, lifetime in
// If `observer` deinitializes, the `Signal` would interrupt which is
// undesirable for `Signal.never`.
lifetime.observeEnded { _ = observer }
}
}
/// A Signal that completes immediately without emitting any value.
public static var empty: Signal {
return self.init { observer, _ in
observer.sendCompleted()
}
}
/// Create a `Signal` that will be controlled by sending events to an
/// input observer.
///
/// - note: The `Signal` will remain alive until a terminating event is sent
/// to the input observer, or until it has no observers and there
/// are no strong references to it.
///
/// - parameters:
/// - disposable: An optional disposable to associate with the signal, and
/// to be disposed of when the signal terminates.
///
/// - returns: A 2-tuple of the output end of the pipe as `Signal`, and the input end
/// of the pipe as `Signal.Observer`.
public static func pipe(disposable: Disposable? = nil) -> (output: Signal, input: Observer) {
var observer: Observer!
let signal = self.init { innerObserver, lifetime in
observer = innerObserver
lifetime += disposable
}
return (signal, observer)
}
}
public protocol SignalProtocol: class {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The materialized `self`.
var signal: Signal<Value, Error> { get }
}
extension Signal: SignalProtocol {
public var signal: Signal<Value, Error> {
return self
}
}
extension Signal: SignalProducerConvertible {
public var producer: SignalProducer<Value, Error> {
return SignalProducer(self)
}
}
extension Signal {
/// Observe `self` for all events being emitted.
///
/// - note: If `self` has terminated, the closure would be invoked with an
/// `interrupted` event immediately.
///
/// - parameters:
/// - action: A closure to be invoked with every event from `self`.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observe(_ action: @escaping Signal<Value, Error>.Observer.Action) -> Disposable? {
return observe(Observer(action))
}
/// Observe `self` for all values being emitted, and if any, the failure.
///
/// - parameters:
/// - action: A closure to be invoked with values from `self`, or the propagated
/// error should any `failed` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeResult(_ action: @escaping (Result<Value, Error>) -> Void) -> Disposable? {
return observe(
Observer(
value: { action(.success($0)) },
failed: { action(.failure($0)) }
)
)
}
/// Observe `self` for its completion.
///
/// - parameters:
/// - action: A closure to be invoked when a `completed` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeCompleted(_ action: @escaping () -> Void) -> Disposable? {
return observe(Observer(completed: action))
}
/// Observe `self` for its failure.
///
/// - parameters:
/// - action: A closure to be invoked with the propagated error, should any
/// `failed` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeFailed(_ action: @escaping (Error) -> Void) -> Disposable? {
return observe(Observer(failed: action))
}
/// Observe `self` for its interruption.
///
/// - note: If `self` has terminated, the closure would be invoked immediately.
///
/// - parameters:
/// - action: A closure to be invoked when an `interrupted` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeInterrupted(_ action: @escaping () -> Void) -> Disposable? {
return observe(Observer(interrupted: action))
}
}
extension Signal where Error == NoError {
/// Observe `self` for all values being emitted.
///
/// - parameters:
/// - action: A closure to be invoked with values from `self`.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeValues(_ action: @escaping (Value) -> Void) -> Disposable? {
return observe(Observer(value: action))
}
}
extension Signal {
/// Perform an action upon every event from `self`. The action may generate zero or
/// more events.
///
/// - precondition: The action must be synchronous.
///
/// - parameters:
/// - transform: A closure that creates the said action from the given event
/// closure.
///
/// - returns: A signal that forwards events yielded by the action.
internal func flatMapEvent<U, E>(_ transform: @escaping Event.Transformation<U, E>) -> Signal<U, E> {
return Signal<U, E> { observer, lifetime in
lifetime += self.observe(Signal.Observer(observer, transform))
}
}
/// Map each value in the signal to a new value.
///
/// - parameters:
/// - transform: A closure that accepts a value from the `value` event and
/// returns a new value.
///
/// - returns: A signal that will send new values.
public func map<U>(_ transform: @escaping (Value) -> U) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.map(transform))
}
/// Map each value in the signal to a new value by applying a key path.
///
/// - parameters:
/// - keyPath: A key path relative to the signal's `Value` type.
///
/// - returns: A signal that will send new values.
public func map<U>(_ keyPath: KeyPath<Value, U>) -> Signal<U, Error> {
return map { $0[keyPath: keyPath] }
}
/// Map errors in the signal to a new error.
///
/// - parameters:
/// - transform: A closure that accepts current error object and returns
/// a new type of error object.
///
/// - returns: A signal that will send new type of errors.
public func mapError<F>(_ transform: @escaping (Error) -> F) -> Signal<Value, F> {
return flatMapEvent(Signal.Event.mapError(transform))
}
/// Maps each value in the signal to a new value, lazily evaluating the
/// supplied transformation on the specified scheduler.
///
/// - important: Unlike `map`, there is not a 1-1 mapping between incoming
/// values, and values sent on the returned signal. If
/// `scheduler` has not yet scheduled `transform` for
/// execution, then each new value will replace the last one as
/// the parameter to `transform` once it is finally executed.
///
/// - parameters:
/// - transform: The closure used to obtain the returned value from this
/// signal's underlying value.
///
/// - returns: A signal that sends values obtained using `transform` as this
/// signal sends values.
public func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> Signal<U, Error> {
return flatMap(.latest) { value in
return SignalProducer({ transform(value) })
.start(on: scheduler)
}
}
/// Preserve only values which pass the given closure.
///
/// - parameters:
/// - isIncluded: A closure to determine whether a value from `self` should be
/// included in the returned `Signal`.
///
/// - returns: A signal that forwards the values passing the given closure.
public func filter(_ isIncluded: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.filter(isIncluded))
}
/// Applies `transform` to values from `signal` and forwards values with non `nil` results unwrapped.
/// - parameters:
/// - transform: A closure that accepts a value from the `value` event and
/// returns a new optional value.
///
/// - returns: A signal that will send new values, that are non `nil` after the transformation.
public func filterMap<U>(_ transform: @escaping (Value) -> U?) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.filterMap(transform))
}
}
extension Signal where Value: OptionalProtocol {
/// Unwrap non-`nil` values and forward them on the returned signal, `nil`
/// values are dropped.
///
/// - returns: A signal that sends only non-nil values.
public func skipNil() -> Signal<Value.Wrapped, Error> {
return flatMapEvent(Signal.Event.skipNil)
}
}
extension Signal {
/// Take up to `n` values from the signal and then complete.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to take from the signal.
///
/// - returns: A signal that will yield the first `count` values from `self`
public func take(first count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
guard count >= 1 else { return .empty }
return flatMapEvent(Signal.Event.take(first: count))
}
/// Collect all values sent by the signal then forward them as a single
/// array and complete.
///
/// - note: When `self` completes without collecting any value, it will send
/// an empty array of values.
///
/// - returns: A signal that will yield an array of values when `self`
/// completes.
public func collect() -> Signal<[Value], Error> {
return flatMapEvent(Signal.Event.collect)
}
/// Collect at most `count` values from `self`, forward them as a single
/// array and complete.
///
/// - note: When the count is reached the array is sent and the signal
/// starts over yielding a new array of values.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not have `count` values. Alternatively, if were
/// not collected any values will sent an empty array of values.
///
/// - precondition: `count` should be greater than zero.
///
public func collect(count: Int) -> Signal<[Value], Error> {
return flatMapEvent(Signal.Event.collect(count: count))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the returned `Signal`.
///
/// ````
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .observeValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 3)
/// observer.send(value: 4)
/// observer.send(value: 7)
/// observer.send(value: 1)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
/// ````
///
/// - parameters:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted. The new value
/// is included in the collected values.
///
/// - returns: A signal of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ collectedValues: [Value]) -> Bool) -> Signal<[Value], Error> {
return flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the returned `Signal`.
///
/// ````
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values, value in value == 7 }
/// .observeValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 1)
/// observer.send(value: 7)
/// observer.send(value: 7)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
/// ````
///
/// - parameters:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted. The new value
/// is **not** included in the collected values, and is included when
/// the next value is received.
///
/// - returns: A signal of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> Signal<[Value], Error> {
return flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Forward all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal that will yield `self` values on provided scheduler.
public func observe(on scheduler: Scheduler) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.observe(on: scheduler))
}
}
extension Signal {
/// Combine the latest value of the receiver with the latest value from the
/// given signal.
///
/// - note: The returned signal will not send a value until both inputs have
/// sent at least one value each.
///
/// - note: If either signal is interrupted, the returned signal will also
/// be interrupted.
///
/// - note: The returned signal will not complete until both inputs
/// complete.
///
/// - parameters:
/// - otherSignal: A signal to combine `self`'s value with.
///
/// - returns: A signal that will yield a tuple containing values of `self`
/// and given signal.
public func combineLatest<U>(with other: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal.combineLatest(self, other)
}
/// Delay `value` and `completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// - note: failed and `interrupted` events are always scheduled
/// immediately.
///
/// - precondition: `interval` must be non-negative number.
///
/// - parameters:
/// - interval: Interval to delay `value` and `completed` events by.
/// - scheduler: A scheduler to deliver delayed events on.
///
/// - returns: A signal that will delay `value` and `completed` events and
/// will yield them on given scheduler.
public func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.delay(interval, on: scheduler))
}
/// Skip first `count` number of values then act as usual.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to skip.
///
/// - returns: A signal that will skip the first `count` values, then
/// forward everything afterward.
public func skip(first count: Int) -> Signal<Value, Error> {
guard count != 0 else { return self }
return flatMapEvent(Signal.Event.skip(first: count))
}
/// Treat all Events from `self` as plain values, allowing them to be
/// manipulated just like any other value.
///
/// In other words, this brings Events “into the monad”.
///
/// - note: When a Completed or Failed event is received, the resulting
/// signal will send the Event itself and then complete. When an
/// Interrupted event is received, the resulting signal will send
/// the Event itself and then interrupt.
///
/// - returns: A signal that sends events as its values.
public func materialize() -> Signal<Event, NoError> {
return flatMapEvent(Signal.Event.materialize)
}
}
extension Signal where Value: EventProtocol, Error == NoError {
/// Translate a signal of `Event` _values_ into a signal of those events
/// themselves.
///
/// - returns: A signal that sends values carried by `self` events.
public func dematerialize() -> Signal<Value.Value, Value.Error> {
return flatMapEvent(Signal.Event.dematerialize)
}
}
extension Signal {
/// Inject side effects to be performed upon the specified signal events.
///
/// - parameters:
/// - event: A closure that accepts an event and is invoked on every
/// received event.
/// - failed: A closure that accepts error object and is invoked for
/// failed event.
/// - completed: A closure that is invoked for `completed` event.
/// - interrupted: A closure that is invoked for `interrupted` event.
/// - terminated: A closure that is invoked for any terminating event.
/// - disposed: A closure added as disposable when signal completes.
/// - value: A closure that accepts a value from `value` event.
///
/// - returns: A signal with attached side-effects for given event cases.
public func on(
event: ((Event) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil,
terminated: (() -> Void)? = nil,
disposed: (() -> Void)? = nil,
value: ((Value) -> Void)? = nil
) -> Signal<Value, Error> {
return Signal { observer, lifetime in
if let action = disposed {
lifetime.observeEnded(action)
}
lifetime += signal.observe { receivedEvent in
event?(receivedEvent)
switch receivedEvent {
case let .value(v):
value?(v)
case let .failed(error):
failed?(error)
case .completed:
completed?()
case .interrupted:
interrupted?()
}
if receivedEvent.isTerminating {
terminated?()
}
observer.send(receivedEvent)
}
}
}
}
private struct SampleState<Value> {
var latestValue: Value?
var isSignalCompleted: Bool = false
var isSamplerCompleted: Bool = false
}
extension Signal {
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when`sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A signal that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A signal that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input signals have completed, or interrupt if
/// either input signal is interrupted.
public func sample<T>(with sampler: Signal<T, NoError>) -> Signal<(Value, T), Error> {
return Signal<(Value, T), Error> { observer, lifetime in
let state = Atomic(SampleState<Value>())
lifetime += self.observe { event in
switch event {
case let .value(value):
state.modify {
$0.latestValue = value
}
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify {
$0.isSignalCompleted = true
return $0.isSamplerCompleted
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
lifetime += sampler.observe { event in
switch event {
case .value(let samplerValue):
if let value = state.value.latestValue {
observer.send(value: (value, samplerValue))
}
case .completed:
let shouldComplete: Bool = state.modify {
$0.isSamplerCompleted = true
return $0.isSignalCompleted
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
case .failed:
break
}
}
}
}
/// Forward the latest value from `self` whenever `sampler` sends a `value`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A signal that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A signal that will send values from `self`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input
/// signals have completed, or interrupt if either input signal
/// is interrupted.
public func sample(on sampler: Signal<(), NoError>) -> Signal<Value, Error> {
return sample(with: sampler)
.map { $0.0 }
}
/// Forward the latest value from `samplee` with the value from `self` as a
/// tuple, only when `self` sends a `value` event.
/// This is like a flipped version of `sample(with:)`, but `samplee`'s
/// terminal events are completely ignored.
///
/// - note: If `self` fires before a value has been observed on `samplee`,
/// nothing happens.
///
/// - parameters:
/// - samplee: A signal whose latest value is sampled by `self`.
///
/// - returns: A signal that will send values from `self` and `samplee`,
/// sampled (possibly multiple times) by `self`, then terminate
/// once `self` has terminated. **`samplee`'s terminated events
/// are ignored**.
public func withLatest<U>(from samplee: Signal<U, NoError>) -> Signal<(Value, U), Error> {
return Signal<(Value, U), Error> { observer, lifetime in
let state = Atomic<U?>(nil)
lifetime += samplee.observeValues { value in
state.value = value
}
lifetime += self.observe { event in
switch event {
case let .value(value):
if let value2 = state.value {
observer.send(value: (value, value2))
}
case .completed:
observer.sendCompleted()
case let .failed(error):
observer.send(error: error)
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forward the latest value from `samplee` with the value from `self` as a
/// tuple, only when `self` sends a `value` event.
/// This is like a flipped version of `sample(with:)`, but `samplee`'s
/// terminal events are completely ignored.
///
/// - note: If `self` fires before a value has been observed on `samplee`,
/// nothing happens.
///
/// - parameters:
/// - samplee: A producer whose latest value is sampled by `self`.
///
/// - returns: A signal that will send values from `self` and `samplee`,
/// sampled (possibly multiple times) by `self`, then terminate
/// once `self` has terminated. **`samplee`'s terminated events
/// are ignored**.
public func withLatest<U>(from samplee: SignalProducer<U, NoError>) -> Signal<(Value, U), Error> {
return Signal<(Value, U), Error> { observer, lifetime in
samplee.startWithSignal { signal, disposable in
lifetime += disposable
lifetime += self.withLatest(from: signal).observe(observer)
}
}
}
}
extension Signal {
/// Forwards events from `self` until `lifetime` ends, at which point the
/// returned signal will complete.
///
/// - parameters:
/// - lifetime: A lifetime whose `ended` signal will cause the returned
/// signal to complete.
///
/// - returns: A signal that will deliver events until `lifetime` ends.
public func take(during lifetime: Lifetime) -> Signal<Value, Error> {
return Signal<Value, Error> { observer, innerLifetime in
innerLifetime += self.observe(observer)
innerLifetime += lifetime.observeEnded(observer.sendCompleted)
}
}
/// Forward events from `self` until `trigger` sends a `value` or
/// `completed` event, at which point the returned signal will complete.
///
/// - parameters:
/// - trigger: A signal whose `value` or `completed` events will stop the
/// delivery of `value` events from `self`.
///
/// - returns: A signal that will deliver events until `trigger` sends
/// `value` or `completed` events.
public func take(until trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal<Value, Error> { observer, lifetime in
lifetime += self.observe(observer)
lifetime += trigger.observe { event in
switch event {
case .value, .completed:
observer.sendCompleted()
case .failed, .interrupted:
break
}
}
}
}
/// Do not forward any values from `self` until `trigger` sends a `value` or
/// `completed` event, at which point the returned signal behaves exactly
/// like `signal`.
///
/// - parameters:
/// - trigger: A signal whose `value` or `completed` events will start the
/// deliver of events on `self`.
///
/// - returns: A signal that will deliver events once the `trigger` sends
/// `value` or `completed` events.
public func skip(until trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer, lifetime in
let disposable = SerialDisposable()
lifetime += disposable
disposable.inner = trigger.observe { event in
switch event {
case .value, .completed:
disposable.inner = self.observe(observer)
case .failed, .interrupted:
break
}
}
}
}
/// Forward events from `self` with history: values of the returned signal
/// are a tuples whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A signal that sends tuples that contain previous and current
/// sent values of `self`.
public func combinePrevious(_ initial: Value) -> Signal<(Value, Value), Error> {
return flatMapEvent(Signal.Event.combinePrevious(initial: initial))
}
/// Forward events from `self` with history: values of the returned signal
/// are a tuples whose first member is the previous value and whose second member
/// is the current value.
///
/// The returned `Signal` would not emit any tuple until it has received at least two
/// values.
///
/// - returns: A signal that sends tuples that contain previous and current
/// sent values of `self`.
public func combinePrevious() -> Signal<(Value, Value), Error> {
return flatMapEvent(Signal.Event.combinePrevious(initial: nil))
}
/// Combine all values from `self`, and forward only the final accumulated result.
///
/// See `scan(_:_:)` if the resulting producer needs to forward also the partial
/// results.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be used in the
/// next call of `nextPartialResult`, or emit to the returned
/// `Signal` when `self` completes.
///
/// - returns: A signal that sends the final result as `self` completes.
public func reduce<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.reduce(initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward only the final accumulated result.
///
/// See `scan(into:_:)` if the resulting producer needs to forward also the partial
/// results.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be used in the
/// next call of `nextPartialResult`, or emit to the returned
/// `Signal` when `self` completes.
///
/// - returns: A signal that sends the final result as `self` completes.
public func reduce<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.reduce(into: initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the partial results and the final
/// result.
///
/// See `reduce(_:_:)` if the resulting producer needs to forward only the final
/// result.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be forwarded,
/// and would be used in the next call of `nextPartialResult`.
///
/// - returns: A signal that sends the partial results of the accumuation, and the
/// final result as `self` completes.
public func scan<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.scan(initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the partial results and the final
/// result.
///
/// See `reduce(into:_:)` if the resulting producer needs to forward only the final
/// result.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be forwarded,
/// and would be used in the next call of `nextPartialResult`.
///
/// - returns: A signal that sends the partial results of the accumuation, and the
/// final result as `self` completes.
public func scan<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.scan(into: initialResult, nextPartialResult))
}
}
extension Signal where Value: Equatable {
/// Forward only values from `self` that are not equal to its immediately preceding
/// value.
///
/// - note: The first value is always forwarded.
///
/// - returns: A signal which conditionally forwards values from `self`.
public func skipRepeats() -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.skipRepeats(==))
}
}
extension Signal {
/// Forward only values from `self` that are not considered equivalent to its
/// immediately preceding value.
///
/// - note: The first value is always forwarded.
///
/// - parameters:
/// - isEquivalent: A closure to determine whether two values are equivalent.
///
/// - returns: A signal which conditionally forwards values from `self`.
public func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.skipRepeats(isEquivalent))
}
/// Do not forward any value from `self` until `shouldContinue` returns `false`, at
/// which point the returned signal starts to forward values from `self`, including
/// the one leading to the toggling.
///
/// - parameters:
/// - shouldContinue: A closure to determine whether the skipping should continue.
///
/// - returns: A signal which conditionally forwards values from `self`.
public func skip(while shouldContinue: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.skip(while: shouldContinue))
}
/// Forward events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A signal to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A signal which passes through `value`, failed, and
/// `interrupted` events from `self` until `replacement` sends
/// an event, at which point the returned signal will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement signal: Signal<Value, Error>) -> Signal<Value, Error> {
return Signal { observer, lifetime in
let signalDisposable = self.observe { event in
switch event {
case .completed:
break
case .value, .failed, .interrupted:
observer.send(event)
}
}
lifetime += signalDisposable
lifetime += signal.observe { event in
signalDisposable?.dispose()
observer.send(event)
}
}
}
/// Wait until `self` completes and then forward the final `count` values
/// on the returned signal.
///
/// - parameters:
/// - count: Number of last events to send after `self` completes.
///
/// - returns: A signal that receives up to `count` values from `self`
/// after `self` completes.
public func take(last count: Int) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.take(last: count))
}
/// Forward any values from `self` until `shouldContinue` returns `false`, at which
/// point the returned signal would complete.
///
/// - parameters:
/// - shouldContinue: A closure to determine whether the forwarding of values should
/// continue.
///
/// - returns: A signal which conditionally forwards values from `self`.
public func take(while shouldContinue: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.take(while: shouldContinue))
}
}
extension Signal {
/// Zip elements of two signals into pairs. The elements of any Nth pair
/// are the Nth elements of the two input signals.
///
/// - parameters:
/// - otherSignal: A signal to zip values with.
///
/// - returns: A signal that sends tuples of `self` and `otherSignal`.
public func zip<U>(with other: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal.zip(self, other)
}
/// Forward the latest value on `scheduler` after at least `interval`
/// seconds have passed since *the returned signal* last sent a value.
///
/// If `self` always sends values more frequently than `interval` seconds,
/// then the returned signal will send a value every `interval` seconds.
///
/// To measure from when `self` last sent a value, see `debounce`.
///
/// - seealso: `debounce`
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If `self` terminates while a value is being throttled, that
/// value will be discarded and the returned signal will terminate
/// immediately.
///
/// - note: If the device time changed backwards before previous date while
/// a value is being throttled, and if there is a new value sent,
/// the new value will be passed anyway.
///
/// - precondition: `interval` must be non-negative number.
///
/// - parameters:
/// - interval: Number of seconds to wait between sent values.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal that sends values at least `interval` seconds
/// appart on a given scheduler.
public func throttle(_ interval: TimeInterval, on scheduler: DateScheduler) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer, lifetime in
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
lifetime += schedulerDisposable
lifetime += self.observe { event in
guard let value = event.value else {
schedulerDisposable.inner = scheduler.schedule {
observer.send(event)
}
return
}
var scheduleDate: Date!
state.modify {
$0.pendingValue = value
let proposedScheduleDate: Date
if let previousDate = $0.previousDate, previousDate.compare(scheduler.currentDate) != .orderedDescending {
proposedScheduleDate = previousDate.addingTimeInterval(interval)
} else {
proposedScheduleDate = scheduler.currentDate
}
switch proposedScheduleDate.compare(scheduler.currentDate) {
case .orderedAscending:
scheduleDate = scheduler.currentDate
case .orderedSame: fallthrough
case .orderedDescending:
scheduleDate = proposedScheduleDate
}
}
schedulerDisposable.inner = scheduler.schedule(after: scheduleDate) {
let pendingValue: Value? = state.modify { state in
defer {
if state.pendingValue != nil {
state.pendingValue = nil
state.previousDate = scheduleDate
}
}
return state.pendingValue
}
if let pendingValue = pendingValue {
observer.send(value: pendingValue)
}
}
}
}
}
/// Conditionally throttles values sent on the receiver whenever
/// `shouldThrottle` is true, forwarding values on the given scheduler.
///
/// - note: While `shouldThrottle` remains false, values are forwarded on the
/// given scheduler. If multiple values are received while
/// `shouldThrottle` is true, the latest value is the one that will
/// be passed on.
///
/// - note: If the input signal terminates while a value is being throttled,
/// that value will be discarded and the returned signal will
/// terminate immediately.
///
/// - note: If `shouldThrottle` completes before the receiver, and its last
/// value is `true`, the returned signal will remain in the throttled
/// state, emitting no further values until it terminates.
///
/// - parameters:
/// - shouldThrottle: A boolean property that controls whether values
/// should be throttled.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal that sends values only while `shouldThrottle` is false.
public func throttle<P: PropertyProtocol>(while shouldThrottle: P, on scheduler: Scheduler) -> Signal<Value, Error>
where P.Value == Bool
{
return Signal { observer, lifetime in
let initial: ThrottleWhileState<Value> = .resumed
let state = Atomic(initial)
let schedulerDisposable = SerialDisposable()
lifetime += schedulerDisposable
lifetime += shouldThrottle.producer
.skipRepeats()
.startWithValues { shouldThrottle in
let valueToSend = state.modify { state -> Value? in
guard !state.isTerminated else { return nil }
if shouldThrottle {
state = .throttled(nil)
} else {
defer { state = .resumed }
if case let .throttled(value?) = state {
return value
}
}
return nil
}
if let value = valueToSend {
schedulerDisposable.inner = scheduler.schedule {
observer.send(value: value)
}
}
}
lifetime += self.observe { event in
let eventToSend = state.modify { state -> Event? in
switch event {
case let .value(value):
switch state {
case .throttled:
state = .throttled(value)
return nil
case .resumed:
return event
case .terminated:
return nil
}
case .completed, .interrupted, .failed:
state = .terminated
return event
}
}
if let event = eventToSend {
schedulerDisposable.inner = scheduler.schedule {
observer.send(event)
}
}
}
}
}
/// Forward the latest value on `scheduler` after at least `interval`
/// seconds have passed since `self` last sent a value.
///
/// If `self` always sends values more frequently than `interval` seconds,
/// then the returned signal will never send any values.
///
/// To measure from when the *returned signal* last sent a value, see
/// `throttle`.
///
/// - seealso: `throttle`
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If the input signal terminates while a value is being debounced,
/// that value will be discarded and the returned signal will
/// terminate immediately.
///
/// - precondition: `interval` must be non-negative number.
///
/// - parameters:
/// - interval: A number of seconds to wait before sending a value.
/// - scheduler: A scheduler to send values on.
///
/// - returns: A signal that sends values that are sent from `self` at least
/// `interval` seconds apart.
public func debounce(_ interval: TimeInterval, on scheduler: DateScheduler) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer, lifetime in
let d = SerialDisposable()
lifetime += self.observe { event in
switch event {
case let .value(value):
let date = scheduler.currentDate.addingTimeInterval(interval)
d.inner = scheduler.schedule(after: date) {
observer.send(value: value)
}
case .completed, .failed, .interrupted:
d.inner = scheduler.schedule {
observer.send(event)
}
}
}
}
}
}
extension Signal {
/// Forward only those values from `self` that have unique identities across
/// the set of all values that have been seen.
///
/// - note: This causes the identities to be retained to check for
/// uniqueness.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns identity
/// value.
///
/// - returns: A signal that sends unique values during its lifetime.
public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.uniqueValues(transform))
}
}
extension Signal where Value: Hashable {
/// Forward only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// - note: This causes the values to be retained to check for uniqueness.
/// Providing a function that returns a unique value for each sent
/// value can help you reduce the memory footprint.
///
/// - returns: A signal that sends unique values during its lifetime.
public func uniqueValues() -> Signal<Value, Error> {
return uniqueValues { $0 }
}
}
private struct ThrottleState<Value> {
var previousDate: Date?
var pendingValue: Value?
}
private enum ThrottleWhileState<Value> {
case resumed
case throttled(Value?)
case terminated
var isTerminated: Bool {
switch self {
case .terminated:
return true
case .resumed, .throttled:
return false
}
}
}
private protocol SignalAggregateStrategy: class {
/// Update the latest value of the signal at `position` to be `value`.
///
/// - parameters:
/// - value: The latest value emitted by the signal at `position`.
/// - position: The position of the signal.
func update(_ value: Any, at position: Int)
/// Record the completion of the signal at `position`.
///
/// - parameters:
/// - position: The position of the signal.
func complete(at position: Int)
init(count: Int, action: @escaping (AggregateStrategyEvent) -> Void)
}
private enum AggregateStrategyEvent {
case value(ContiguousArray<Any>)
case completed
}
extension Signal {
// Threading of `CombineLatestStrategy` and `ZipStrategy`.
//
// The threading models of these strategies mirror that of `Signal.Core` to allow
// recursive termial event from the upstreams that is triggered by the combined
// values.
//
// The strategies do not unique the delivery of `completed`, since `Signal` already
// guarantees that no event would ever be delivered after a terminal event.
private final class CombineLatestStrategy: SignalAggregateStrategy {
private enum Placeholder {
case none
}
var values: ContiguousArray<Any>
private var _haveAllSentInitial: Bool
private var haveAllSentInitial: Bool {
get {
if _haveAllSentInitial {
return true
}
_haveAllSentInitial = values.reduce(true) { $0 && !($1 is Placeholder) }
return _haveAllSentInitial
}
}
private let count: Int
private let lock: Lock
private let completion: Atomic<Int>
private let action: (AggregateStrategyEvent) -> Void
func update(_ value: Any, at position: Int) {
lock.lock()
values[position] = value
if haveAllSentInitial {
action(.value(values))
}
lock.unlock()
if completion.value == self.count, lock.try() {
action(.completed)
lock.unlock()
}
}
func complete(at position: Int) {
let count: Int = completion.modify { count in
count += 1
return count
}
if count == self.count, lock.try() {
action(.completed)
lock.unlock()
}
}
init(count: Int, action: @escaping (AggregateStrategyEvent) -> Void) {
self.count = count
self.lock = Lock.make()
self.values = ContiguousArray(repeating: Placeholder.none, count: count)
self._haveAllSentInitial = false
self.completion = Atomic(0)
self.action = action
}
}
private final class ZipStrategy: SignalAggregateStrategy {
private let stateLock: Lock
private let sendLock: Lock
private var values: ContiguousArray<[Any]>
private var canEmit: Bool {
return values.reduce(true) { $0 && !$1.isEmpty }
}
private var hasConcurrentlyCompleted: Bool
private var isCompleted: ContiguousArray<Bool>
private var hasCompletedAndEmptiedSignal: Bool {
return Swift.zip(values, isCompleted).contains(where: { $0.0.isEmpty && $0.1 })
}
private var areAllCompleted: Bool {
return isCompleted.reduce(true) { $0 && $1 }
}
private let action: (AggregateStrategyEvent) -> Void
func update(_ value: Any, at position: Int) {
stateLock.lock()
values[position].append(value)
if canEmit {
var buffer = ContiguousArray<Any>()
buffer.reserveCapacity(values.count)
for index in values.indices {
buffer.append(values[index].removeFirst())
}
let shouldComplete = areAllCompleted || hasCompletedAndEmptiedSignal
sendLock.lock()
stateLock.unlock()
action(.value(buffer))
if shouldComplete {
action(.completed)
}
sendLock.unlock()
stateLock.lock()
if hasConcurrentlyCompleted {
sendLock.lock()
action(.completed)
sendLock.unlock()
}
}
stateLock.unlock()
}
func complete(at position: Int) {
stateLock.lock()
isCompleted[position] = true
if hasConcurrentlyCompleted || areAllCompleted || hasCompletedAndEmptiedSignal {
if sendLock.try() {
stateLock.unlock()
action(.completed)
sendLock.unlock()
return
}
hasConcurrentlyCompleted = true
}
stateLock.unlock()
}
init(count: Int, action: @escaping (AggregateStrategyEvent) -> Void) {
self.values = ContiguousArray(repeating: [], count: count)
self.hasConcurrentlyCompleted = false
self.isCompleted = ContiguousArray(repeating: false, count: count)
self.action = action
self.sendLock = Lock.make()
self.stateLock = Lock.make()
}
}
private final class AggregateBuilder<Strategy: SignalAggregateStrategy> {
fileprivate var startHandlers: [(_ index: Int, _ strategy: Strategy, _ action: @escaping (Signal<Never, Error>.Event) -> Void) -> Disposable?]
init() {
self.startHandlers = []
}
@discardableResult
func add<U>(_ signal: Signal<U, Error>) -> Self {
startHandlers.append { index, strategy, action in
return signal.observe { event in
switch event {
case let .value(value):
strategy.update(value, at: index)
case .completed:
strategy.complete(at: index)
case .interrupted:
action(.interrupted)
case let .failed(error):
action(.failed(error))
}
}
}
return self
}
}
private convenience init<Strategy>(_ builder: AggregateBuilder<Strategy>, _ transform: @escaping (ContiguousArray<Any>) -> Value) {
self.init { observer, lifetime in
let strategy = Strategy(count: builder.startHandlers.count) { event in
switch event {
case let .value(value):
observer.send(value: transform(value))
case .completed:
observer.sendCompleted()
}
}
for (index, action) in builder.startHandlers.enumerated() where !lifetime.hasEnded {
lifetime += action(index, strategy) { observer.send($0.map { _ in fatalError() }) }
}
}
}
private convenience init<Strategy: SignalAggregateStrategy, U, S: Sequence>(_ strategy: Strategy.Type, _ signals: S) where Value == [U], S.Iterator.Element == Signal<U, Error> {
self.init(signals.reduce(AggregateBuilder<Strategy>()) { $0.add($1) }) { $0.map { $0 as! U } }
}
private convenience init<Strategy: SignalAggregateStrategy, A, B>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>) where Value == (A, B) {
self.init(AggregateBuilder<Strategy>().add(a).add(b)) {
return ($0[0] as! A, $0[1] as! B)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) where Value == (A, B, C) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) where Value == (A, B, C, D) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) where Value == (A, B, C, D, E) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) where Value == (A, B, C, D, E, F) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) where Value == (A, B, C, D, E, F, G) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G, H>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) where Value == (A, B, C, D, E, F, G, H) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g).add(h)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G, $0[7] as! H)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G, H, I>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) where Value == (A, B, C, D, E, F, G, H, I) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g).add(h).add(i)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G, $0[7] as! H, $0[8] as! I)
}
}
private convenience init<Strategy: SignalAggregateStrategy, A, B, C, D, E, F, G, H, I, J>(_ strategy: Strategy.Type, _ a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) where Value == (A, B, C, D, E, F, G, H, I, J) {
self.init(AggregateBuilder<Strategy>().add(a).add(b).add(c).add(d).add(e).add(f).add(g).add(h).add(i).add(j)) {
return ($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F, $0[6] as! G, $0[7] as! H, $0[8] as! I, $0[9] as! J)
}
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>) -> Signal<(Value, B), Error> {
return .init(CombineLatestStrategy.self, a, b)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(Value, B, C), Error> {
return .init(CombineLatestStrategy.self, a, b, c)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C, D>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(Value, B, C, D), Error> {
return .init(CombineLatestStrategy.self, a, b, c, d)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C, D, E>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(Value, B, C, D, E), Error> {
return .init(CombineLatestStrategy.self, a, b, c, d, e)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C, D, E, F>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(Value, B, C, D, E, F), Error> {
return .init(CombineLatestStrategy.self, a, b, c, d, e, f)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C, D, E, F, G>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(Value, B, C, D, E, F, G), Error> {
return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C, D, E, F, G, H>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(Value, B, C, D, E, F, G, H), Error> {
return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g, h)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C, D, E, F, G, H, I>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I), Error> {
return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g, h, i)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<B, C, D, E, F, G, H, I, J>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I, J), Error> {
return .init(CombineLatestStrategy.self, a, b, c, d, e, f, g, h, i, j)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatest(with:)`. No events will be sent if the sequence is empty.
public static func combineLatest<S: Sequence>(_ signals: S) -> Signal<[Value], Error> where S.Iterator.Element == Signal<Value, Error> {
return .init(CombineLatestStrategy.self, signals)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>) -> Signal<(Value, B), Error> {
return .init(ZipStrategy.self, a, b)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(Value, B, C), Error> {
return .init(ZipStrategy.self, a, b, c)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C, D>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(Value, B, C, D), Error> {
return .init(ZipStrategy.self, a, b, c, d)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C, D, E>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(Value, B, C, D, E), Error> {
return .init(ZipStrategy.self, a, b, c, d, e)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C, D, E, F>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(Value, B, C, D, E, F), Error> {
return .init(ZipStrategy.self, a, b, c, d, e, f)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C, D, E, F, G>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(Value, B, C, D, E, F, G), Error> {
return .init(ZipStrategy.self, a, b, c, d, e, f, g)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C, D, E, F, G, H>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(Value, B, C, D, E, F, G, H), Error> {
return .init(ZipStrategy.self, a, b, c, d, e, f, g, h)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C, D, E, F, G, H, I>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I), Error> {
return .init(ZipStrategy.self, a, b, c, d, e, f, g, h, i)
}
/// Zip the values of all the given signals, in the manner described by `zip(with:)`.
public static func zip<B, C, D, E, F, G, H, I, J>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I, J), Error> {
return .init(ZipStrategy.self, a, b, c, d, e, f, g, h, i, j)
}
/// Zips the values of all the given signals, in the manner described by
/// `zip(with:)`. No events will be sent if the sequence is empty.
public static func zip<S: Sequence>(_ signals: S) -> Signal<[Value], Error> where S.Iterator.Element == Signal<Value, Error> {
return .init(ZipStrategy.self, signals)
}
}
extension Signal {
/// Forward events from `self` until `interval`. Then if signal isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The signal must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - precondition: `interval` must be non-negative number.
///
/// - parameters:
/// - error: Error to send with failed event if `self` is not completed
/// when `interval` passes.
/// - interval: Number of seconds to wait for `self` to complete.
/// - scheudler: A scheduler to deliver error on.
///
/// - returns: A signal that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with failed event
/// on `scheduler`.
public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateScheduler) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer, lifetime in
let date = scheduler.currentDate.addingTimeInterval(interval)
lifetime += scheduler.schedule(after: date) {
observer.send(error: error)
}
lifetime += self.observe(observer)
}
}
}
extension Signal where Error == NoError {
/// Promote a signal that does not generate failures into one that can.
///
/// - note: This does not actually cause failures to be generated for the
/// given signal, but makes it easier to combine with other signals
/// that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A signal that has an instantiatable `ErrorType`.
public func promoteError<F>(_: F.Type = F.self) -> Signal<Value, F> {
return flatMapEvent(Signal.Event.promoteError(F.self))
}
/// Promote a signal that does not generate failures into one that can.
///
/// - note: This does not actually cause failures to be generated for the
/// given signal, but makes it easier to combine with other signals
/// that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A signal that has an instantiatable `ErrorType`.
public func promoteError(_: Error.Type = Error.self) -> Signal<Value, Error> {
return self
}
/// Forward events from `self` until `interval`. Then if signal isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The signal must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheudler: A scheduler to deliver error on.
///
/// - returns: A signal that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout<NewError>(
after interval: TimeInterval,
raising error: NewError,
on scheduler: DateScheduler
) -> Signal<Value, NewError> {
return self
.promoteError(NewError.self)
.timeout(after: interval, raising: error, on: scheduler)
}
}
extension Signal where Value == Never {
/// Promote a signal that does not generate values, as indicated by `Never`, to be
/// a signal of the given type of value.
///
/// - note: The promotion does not result in any value being generated.
///
/// - parameters:
/// - _ The type of value to promote to.
///
/// - returns: A signal that forwards all terminal events from `self`.
public func promoteValue<U>(_: U.Type = U.self) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.promoteValue(U.self))
}
/// Promote a signal that does not generate values, as indicated by `Never`, to be
/// a signal of the given type of value.
///
/// - note: The promotion does not result in any value being generated.
///
/// - parameters:
/// - _ The type of value to promote to.
///
/// - returns: A signal that forwards all terminal events from `self`.
public func promoteValue(_: Value.Type = Value.self) -> Signal<Value, Error> {
return self
}
}
extension Signal where Value == Bool {
/// Create a signal that computes a logical NOT in the latest values of `self`.
///
/// - returns: A signal that emits the logical NOT results.
public func negate() -> Signal<Value, Error> {
return self.map(!)
}
/// Create a signal that computes a logical AND between the latest values of `self`
/// and `signal`.
///
/// - parameters:
/// - signal: Signal to be combined with `self`.
///
/// - returns: A signal that emits the logical AND results.
public func and(_ signal: Signal<Value, Error>) -> Signal<Value, Error> {
return self.combineLatest(with: signal).map { $0.0 && $0.1 }
}
/// Create a signal that computes a logical OR between the latest values of `self`
/// and `signal`.
///
/// - parameters:
/// - signal: Signal to be combined with `self`.
///
/// - returns: A signal that emits the logical OR results.
public func or(_ signal: Signal<Value, Error>) -> Signal<Value, Error> {
return self.combineLatest(with: signal).map { $0.0 || $0.1 }
}
}
extension Signal {
/// Apply an action to every value from `self`, and forward the value if the action
/// succeeds. If the action fails with an error, the returned `Signal` would propagate
/// the failure and terminate.
///
/// - parameters:
/// - action: An action which yields a `Result`.
///
/// - returns: A signal which forwards the values from `self` until the given action
/// fails.
public func attempt(_ action: @escaping (Value) -> Result<(), Error>) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.attempt(action))
}
/// Apply a transform to every value from `self`, and forward the transformed value
/// if the action succeeds. If the action fails with an error, the returned `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A transform which yields a `Result` of the transformed value or the
/// error.
///
/// - returns: A signal which forwards the transformed values.
public func attemptMap<U>(_ transform: @escaping (Value) -> Result<U, Error>) -> Signal<U, Error> {
return flatMapEvent(Signal.Event.attemptMap(transform))
}
}
extension Signal where Error == NoError {
/// Apply a throwable action to every value from `self`, and forward the values
/// if the action succeeds. If the action throws an error, the returned `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value.
///
/// - returns: A signal which forwards the successful values of the given action.
public func attempt(_ action: @escaping (Value) throws -> Void) -> Signal<Value, AnyError> {
return self
.promoteError(AnyError.self)
.attempt(action)
}
/// Apply a throwable transform to every value from `self`, and forward the results
/// if the action succeeds. If the transform throws an error, the returned `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - transform: A throwable transform.
///
/// - returns: A signal which forwards the successfully transformed values.
public func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> Signal<U, AnyError> {
return self
.promoteError(AnyError.self)
.attemptMap(transform)
}
}
extension Signal where Error == AnyError {
/// Apply a throwable action to every value from `self`, and forward the values
/// if the action succeeds. If the action throws an error, the returned `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value.
///
/// - returns: A signal which forwards the successful values of the given action.
public func attempt(_ action: @escaping (Value) throws -> Void) -> Signal<Value, AnyError> {
return flatMapEvent(Signal.Event.attempt(action))
}
/// Apply a throwable transform to every value from `self`, and forward the results
/// if the action succeeds. If the transform throws an error, the returned `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - transform: A throwable transform.
///
/// - returns: A signal which forwards the successfully transformed values.
public func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> Signal<U, AnyError> {
return flatMapEvent(Signal.Event.attemptMap(transform))
}
}
| e97187347442c039dc612fcf19b9771c | 35.634581 | 395 | 0.644049 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/UI/Subscription/Components/BookmarksSubscriptionButton.swift | apache-2.0 | 4 | class BookmarksSubscriptionButton: UIButton {
private let descriptionLabel = UILabel()
private let priceLabel = UILabel()
override func awakeFromNib() {
addSubview(descriptionLabel)
addSubview(priceLabel)
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
priceLabel.translatesAutoresizingMaskIntoConstraints = false
priceLabel.font = UIFont.semibold16()
priceLabel.textAlignment = .right
descriptionLabel.font = UIFont.semibold16()
descriptionLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
descriptionLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16).isActive = true
priceLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
priceLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
setTitle("", for: .normal)
}
override func setTitleColor(_ color: UIColor?, for state: UIControl.State) {
super.setTitleColor(color, for: state)
if state == .normal {
descriptionLabel.textColor = color
priceLabel.textColor = color
}
}
override func setTitle(_ title: String?, for state: UIControl.State) {
super.setTitle("", for: state)
}
func config(title: String, price: String, enabled: Bool) {
descriptionLabel.text = title
priceLabel.text = price
isEnabled = enabled
}
}
| f533b71371b62602ba63bb269277b9a9 | 32.853659 | 99 | 0.739914 | false | false | false | false |
davepagurek/raytracer | refs/heads/master | Sources/Geometry/SurfaceList.swift | mit | 1 | import VectorMath
import RaytracerLib
public struct SurfaceList: FiniteSurface {
let surfaces: [FiniteSurface]
let box: BoundingBox
let sphere: BoundingSphere
public init(surfaces: [FiniteSurface]) {
self.surfaces = surfaces
box = BoundingBox(from: surfaces.map{$0.boundingBox()})
sphere = box.boundingSphere()
}
public func boundingBox() -> BoundingBox {
return box
}
public func intersectsRay(_ ray: Ray, min: Scalar, max: Scalar) -> Intersection? {
if !sphere.intersectsRay(ray, min: min, max: max) {
return nil
}
return surfaces.reduce(nil) { (prev: Intersection?, next: Surface) -> Intersection? in
let intersection = next.intersectsRay(ray, min: min, max: max)
if let prev = prev, let intersection = intersection {
if (prev.point - ray.point).lengthSquared > (intersection.point - ray.point).lengthSquared {
return intersection
} else {
return prev
}
} else {
return prev ?? intersection
}
}
}
}
public struct UnboundedSurfaceList: Surface {
let surfaces: [Surface]
public init(surfaces: [Surface]) {
self.surfaces = surfaces
}
public func intersectsRay(_ ray: Ray, min: Scalar, max: Scalar) -> Intersection? {
return surfaces.reduce(nil) { (prev: Intersection?, next: Surface) -> Intersection? in
let intersection = next.intersectsRay(ray, min: min, max: max)
if let prev = prev, let intersection = intersection {
if (prev.point - ray.point).lengthSquared > (intersection.point - ray.point).lengthSquared {
return intersection
} else {
return prev
}
} else {
return prev ?? intersection
}
}
}
}
| 69b7304cb85e3c1095e6db232729bd96 | 28.2 | 100 | 0.635274 | false | false | false | false |
zhuhaow/Soca-iOS | refs/heads/master | Soca/View Controller/Config/AdapterConfigListTableViewController.swift | mit | 1 | //
// AdapterListTableViewController.swift
// soca
//
// Created by Zhuhao Wang on 3/10/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import UIKit
import SocaCore
import CoreData
protocol AdapterConfigDelegate {
func finishEditingConfig(config: AdapterConfig, save: Bool)
}
class AdapterConfigListTableViewController: UITableViewController, AdapterConfigDelegate, NSFetchedResultsControllerDelegate {
lazy var fetchedResultsController: NSFetchedResultsController = {
[unowned self] in
AdapterConfig.MR_fetchAllGroupedBy(nil, withPredicate: nil, sortedBy: nil, ascending: true, delegate: self)
}()
lazy var editContext: NSManagedObjectContext = {
NSManagedObjectContext.MR_context()
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func presentAdapterDetail(adapterConfig: AdapterConfig) {
var adapterViewController: AdapterConfigViewController!
switch adapterConfig {
case is SOCKS5AdapterConfig:
adapterViewController = ServerAdapterConfigViewController(adapterConfig: adapterConfig)
case is HTTPAdapterConfig, is SHTTPAdapterConfig:
adapterViewController = AuthenticationServerAdapterConfigViewController(adapterConfig: adapterConfig)
case is ShadowsocksAdapterConfig:
adapterViewController = ShadowsocksAdapterConfigViewController(adapterConfig: adapterConfig)
default:
return
}
adapterViewController.delegate = self
let navController = UINavigationController(rootViewController: adapterViewController)
self.presentViewController(navController, animated: true, completion: nil)
}
@IBAction func showAdapterTypeSheet(sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "Choose adapter type", message: nil, preferredStyle: .ActionSheet)
let HTTPAction = UIAlertAction(title: "HTTP", style: .Default) {_ in
self.presentAdapterDetail(HTTPAdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let SHTTPAction = UIAlertAction(title: "Secured HTTP", style: .Default) {_ in
self.presentAdapterDetail(SHTTPAdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let SOCKS5Action = UIAlertAction(title: "SOCKS5", style: .Default) {_ in
self.presentAdapterDetail(SOCKS5AdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let SSAction = UIAlertAction(title: "Shadowsocks", style: .Default) {_ in
self.presentAdapterDetail(ShadowsocksAdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let cancelAction = UIAlertAction(title: "cancel", style: .Cancel) {_ in }
alertController.addAction(HTTPAction)
alertController.addAction(SHTTPAction)
alertController.addAction(SOCKS5Action)
alertController.addAction(SSAction)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo).numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("adapterCell", forIndexPath: indexPath) as! UITableViewCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let adapterConfig: AdapterConfig = fetchedResultsController.objectAtIndexPath(indexPath) as! AdapterConfig
cell.textLabel!.text = adapterConfig.name
cell.detailTextLabel!.text = adapterConfig.type
if adapterConfig is DirectAdapterConfig {
cell.selectionStyle = .None
cell.accessoryType = .None
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var configToEdit = fetchedResultsController.objectAtIndexPath(indexPath).MR_inContext(editContext) as! AdapterConfig
presentAdapterDetail(configToEdit as AdapterConfig)
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if fetchedResultsController.objectAtIndexPath(indexPath) is DirectAdapterConfig {
return false
}
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let config = fetchedResultsController.objectAtIndexPath(indexPath) as! AdapterConfig
config.MR_deleteEntity()
config.managedObjectContext?.MR_saveToPersistentStoreAndWait()
}
}
// MARK: NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
case .Delete:
tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
default:
break
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Update:
configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
default:
break
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
// MARK: - AdapterConfigDelegate
func finishEditingConfig(config: AdapterConfig, save: Bool) {
dismissViewControllerAnimated(true, completion: nil)
}
}
| 4db069928bfca2cedbbc279bc092f521 | 42.203488 | 211 | 0.713228 | false | true | false | false |
Yoloabdo/CS-193P | refs/heads/master | LoginLayout/LoginLayout/User.swift | mit | 1 | //
// User.swift
// LoginLayout
//
// Created by abdelrahman mohamed on 2/10/16.
// Copyright © 2016 Abdulrhman dev. All rights reserved.
//
import Foundation
struct User {
let name: String
let company: String
let login: String
let password: String
static func login(login: String, password: String) -> User? {
if let user = database[login]{
if user.password == password {
return user
}
}
return nil
}
static let database: Dictionary<String, User> = {
var theDataBase = Dictionary<String, User>()
for user in [
User(name: "John Appleseed", company: "Apple", login: "japple", password: "foo"),
User(name: "Madison Bumgarner", company: "World Champion San Francisco Giants", login: "madbum", password: "foo"),
User(name: "John Hennessy", company: "Stanford", login: "hennessy", password: "foo"),
User(name: "Bad Guy", company: "Criminals, Inc.", login: "baddie", password: "foo")
]{
theDataBase[user.login] = user
}
return theDataBase
}()
} | 4e261abe1267641a79d99dc88a41da3a | 27.071429 | 126 | 0.563667 | false | false | false | false |
ngageoint/fog-machine | refs/heads/master | Demo/FogViewshed/FogViewshed/Utility/HGTDownloader.swift | mit | 1 | import Foundation
import UIKit
import SSZipArchive
public class HGTDownloader: NSObject, NSURLSessionDownloadDelegate {
static let DOWNLOAD_SERVER = "https://dds.cr.usgs.gov/srtm/version2_1/SRTM3/"
let onDownload:(String)->()
let onError:(String)->()
init(onDownload:(String)->(), onError:(String)->()) {
self.onDownload = onDownload
self.onError = onError
}
func downloadFile(hgtFileName: String) {
let srtmDataRegion:String = HGTRegions().getRegion(hgtFileName)
if (srtmDataRegion.isEmpty == false) {
let hgtFilePath: String = HGTDownloader.DOWNLOAD_SERVER + srtmDataRegion + "/" + hgtFileName + ".zip"
let hgtURL = NSURL(string: hgtFilePath)
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(hgtURL!.absoluteString)
let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTaskWithURL(hgtURL!)
task.resume()
}
}
// called once the download is complete
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
let response = downloadTask.response as! NSHTTPURLResponse
let statusCode = response.statusCode
// URL not found, do not proceed
if (statusCode == 200) {
//copy downloaded data to your documents directory with same name as source file
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
let destinationUrl = documentsUrl!.URLByAppendingPathComponent(location.lastPathComponent!)
let dataFromURL:NSData = NSData(contentsOfURL: location)!
if (dataFromURL.writeToURL(destinationUrl, atomically: true)) {
let status:Bool = SSZipArchive.unzipFileAtPath(destinationUrl.path!, toDestination: documentsUrl!.path!)
if(status) {
deleteFile(destinationUrl.path!)
onDownload("some file name")
} else {
onError("Problem unzipping file.")
}
}
} else {
NSLog("Received bad status code from sever.")
onError("Problem downloading file. Received bad status code from sever.")
}
}
func deleteFile(fileName: String) {
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtPath(fileName)
}
catch let error as NSError {
NSLog("Error deleting file: " + fileName + ": \(error)")
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
}
// to track progress
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
}
// if there is an error during download this will be called
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if(error != nil) {
NSLog("Download error: \(error)");
onError("Problem downloading file.")
}
}
}
| b10c2b34cdca9622e8ad6b394d6dcb17 | 43.705128 | 185 | 0.658446 | false | true | false | false |
woohyuknrg/GithubTrending | refs/heads/master | githubTests/CommitSpec.swift | mit | 1 | import Quick
import Nimble
@testable import github
class CommitSpec: QuickSpec {
override func spec() {
describe("Issue") {
var sut: Commit!
let json = [
"commit" : [
"message" : "welcome",
],
"committer" : [
"login" : "john",
],
"createdAt" : "2008-11-14T03:57:43Z"] as [String : Any]
beforeSuite {
sut = Commit.fromJSON(json)
}
context("when deserializing") {
it("should have valid title") {
expect(sut.message) == "welcome"
}
it("should have valid author") {
expect(sut.author) == "john"
}
it("should have valid creation date") {
var components = DateComponents()
components.day = 14
components.month = 11
components.year = 2008
components.hour = 3
components.minute = 57
components.second = 43
components.timeZone = TimeZone(secondsFromGMT: 0)
let date = Calendar.current.date(from: components)
expect(sut.date) == date
}
}
}
}
}
| 07bbbf4c74c506064b09b64464459a73 | 30.744681 | 71 | 0.393432 | false | false | false | false |
quickthyme/PUTcat | refs/heads/master | PUTcat/Application/Data/Variable/Entity/PCVariable.swift | apache-2.0 | 1 |
import Foundation
final class PCVariable : PCItem, PCValueItem, PCCopyable, PCLocal {
var id: String
var name: String
var value: String
init(id: String, name: String, value: String) {
self.id = id
self.name = name
self.value = value
}
convenience init(name: String, value: String) {
self.init(id: UUID().uuidString, name: name, value: value)
}
convenience init(name: String) {
self.init(name: name, value: "Value")
}
convenience init() {
self.init(name: "New Variable")
}
required convenience init(copy: PCVariable) {
self.init(name: copy.name, value: copy.value)
}
required init(fromLocal: [String:Any]) {
self.id = fromLocal["id"] as? String ?? ""
self.name = fromLocal["name"] as? String ?? ""
self.value = Base64.decode(fromLocal["value"] as? String ?? "")
}
func toLocal() -> [String:Any] {
return [
"id" : self.id,
"name" : self.name,
"value": Base64.encode(self.value)
]
}
}
extension PCVariable : PCLocalExport {
func toLocalExport() -> [String:Any] {
return self.toLocal()
}
}
struct PCParsedVariable {
var id: String
var name: String
var value: String
}
| 393bcb83b27f315e4bde5c8f570e7a10 | 22.5 | 71 | 0.567629 | false | false | false | false |
coderwjq/swiftweibo | refs/heads/master | SwiftWeibo/SwiftWeibo/Classes/Main/View/Status.swift | apache-2.0 | 1 | //
// Status.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/3.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
class Status: NSObject {
// MARK:- 属性
var created_at: String? // 微博的创建时间
var source: String? // 微博来源
var text: String? // 微博的正文
var mid: Int = 0 // 微博的id
var user: User? // 微博的作者
var pic_urls: [[String : String]]? // 微博的配图
var retweeted_status: Status? // 微博对应的转发微博
// MARK:- 自定义构造函数
init(dict: [String : AnyObject]) {
super.init()
setValuesForKeys(dict)
// 将用户字典转成用户模型对象
if let userDict = dict["user"] as? [String : AnyObject] {
user = User(dict: userDict)
}
// 将转发微博字典转成转发微博模型对象
if let retweetedStatusDict = dict["retweeted_status"] as? [String : AnyObject] {
retweeted_status = Status(dict: retweetedStatusDict)
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| 97ef17ca83ebf38066ba68e68f64ecab | 25.878049 | 88 | 0.521779 | false | false | false | false |
dreamsxin/swift | refs/heads/master | test/DebugInfo/test-foundation.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -emit-ir -g %s -o %t.ll
// RUN: FileCheck %s --check-prefix IMPORT-CHECK < %t.ll
// RUN: FileCheck %s --check-prefix LOC-CHECK < %t.ll
// RUN: llc %t.ll -filetype=obj -o %t.o
// RUN: llvm-dwarfdump %t.o | FileCheck %s --check-prefix DWARF-CHECK
// RUN: dwarfdump --verify %t.o
// REQUIRES: OS=macosx
import ObjectiveC
import Foundation
class MyObject : NSObject {
// Ensure we don't emit linetable entries for ObjC thunks.
// LOC-CHECK: define {{.*}} @_TToFC4main8MyObjectg5MyArrCSo7NSArray
// LOC-CHECK: ret {{.*}}, !dbg ![[DBG:.*]]
// LOC-CHECK: ret
var MyArr = NSArray()
// IMPORT-CHECK: filename: "test-foundation.swift"
// IMPORT-CHECK-DAG: [[FOUNDATION:[0-9]+]] = !DIModule({{.*}} name: "Foundation",{{.*}} includePath:
// IMPORT-CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "NSArray", scope: ![[FOUNDATION]]
// IMPORT-CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, {{.*}}entity: ![[FOUNDATION]]
func foo(_ obj: MyObject) {
return obj.foo(obj)
}
}
// SANITY-DAG: !DISubprogram(name: "blah",{{.*}} line: [[@LINE+2]],{{.*}} isDefinition: true
extension MyObject {
func blah() {
var _ = MyObject()
}
}
// SANITY-DAG: ![[NSOBJECT:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "NSObject",{{.*}} identifier: "_TtCSo8NSObject"
// SANITY-DAG: !DIGlobalVariable(name: "NsObj",{{.*}} line: [[@LINE+1]],{{.*}} type: ![[NSOBJECT]],{{.*}} isDefinition: true
var NsObj: NSObject
NsObj = MyObject()
var MyObj: MyObject
MyObj = NsObj as! MyObject
MyObj.blah()
public func err() {
// DWARF-CHECK: DW_AT_name{{.*}}NSError
// DWARF-CHECK: DW_AT_linkage_name{{.*}}_TtCSo7NSError
let _ = NSError(domain: "myDomain", code: 4,
userInfo: ["a":1,"b":2,"c":3])
}
// LOC-CHECK: define {{.*}}4date
public func date() {
// LOC-CHECK: call {{.*}} @_TFSSCfT21_builtinStringLiteralBp17utf8CodeUnitCountBw7isASCIIBi1__SS{{.*}}, !dbg ![[L1:.*]]
let d1 = NSDateFormatter()
// LOC-CHECK: br{{.*}}, !dbg ![[L2:.*]]
d1.dateFormat = "dd. mm. yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L2]]
// LOC-CHECK: call {{.*}} @_TFSSCfT21_builtinStringLiteralBp17utf8CodeUnitCountBw7isASCIIBi1__SS{{.*}}, !dbg ![[L3:.*]]
let d2 = NSDateFormatter()
// LOC-CHECK: br{{.*}}, !dbg ![[L4:.*]]
d2.dateFormat = "mm dd yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L4]]
}
// Make sure we build some witness tables for enums.
func useOptions(_ opt: NSURLBookmarkCreationOptions)
-> NSURLBookmarkCreationOptions {
return [opt, opt]
}
// LOC-CHECK: ![[THUNK:.*]] = distinct !DISubprogram({{.*}}linkageName: "_TToFC4main8MyObjectg5MyArrCSo7NSArray"
// LOC-CHECK-NOT: line:
// LOC-CHECK-SAME: isDefinition: true
// LOC-CHECK: ![[DBG]] = !DILocation(line: 0, scope: ![[THUNK]])
// These debug locations should all be in ordered by increasing line number.
// LOC-CHECK: ![[L1]] =
// LOC-CHECK: ![[L2]] =
// LOC-CHECK: ![[L3]] =
// LOC-CHECK: ![[L4]] =
| db67ccad1f6598cbdcdf2d12e0a80900 | 37.833333 | 132 | 0.618356 | false | false | false | false |
shaps80/Peek | refs/heads/master | Pod/Classes/Peekable/UIBarButtonItem+Peekable.swift | mit | 1 | /*
Copyright © 23/04/2016 Shaps
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
extension UIBarButtonItem {
open override func preparePeek(with coordinator: Coordinator) {
var detail = ""
if let model = target as? Peekable {
detail = String(describing: model.classForCoder)
}
var title = ""
if let action = action {
title = String(describing: action)
}
coordinator.appendStatic(keyPath: title, title: title, detail: detail, value: target, in: .actions)
coordinator.appendDynamic(keyPaths: [
"title",
"image",
"landscapeImagePhone"
], forModel: self, in: .appearance)
coordinator.appendDynamic(keyPaths: [
"tag"
], forModel: self, in: .general)
coordinator.appendDynamic(keyPaths: [
"imageInsets",
"landscapeImagePhoneInsets"
], forModel: self, in: .layout)
coordinator.appendDynamic(keyPaths: ["enabled"], forModel: self, in: .behaviour)
super.preparePeek(with: coordinator)
}
}
| 005e3e583c186f6f732b5516d0b36b13 | 34.612903 | 107 | 0.662138 | false | false | false | false |
quangvu1994/Exchange | refs/heads/master | Exchange/Model/User.swift | mit | 1 | //
// User.swift
// Exchange
//
// Created by Quang Vu on 7/4/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import Foundation
import FirebaseDatabase.FIRDataSnapshot
class User: NSObject {
// MARK: - Properties
var uid: String
var username: String
var phoneNumber: String
var oneSignalID: String = ""
var profilePictureURL: String?
var storeDescription: String = "Welcome to my store!"
// Singleton User
private static var _current: User?
init(uid: String, username: String, phoneNumber: String){
self.uid = uid
self.username = username
self.phoneNumber = phoneNumber
super.init()
}
required init?(coder aDecoder: NSCoder) {
// Decode to grab our user info
guard let uid = aDecoder.decodeObject(forKey: Constants.UserDefaults.uid) as? String,
let username = aDecoder.decodeObject(forKey: Constants.UserDefaults.username) as? String,
let phoneNumber = aDecoder.decodeObject(forKey: Constants.UserDefaults.phoneNumber) as? String,
let storeDescription = aDecoder.decodeObject(forKey: Constants.UserDefaults.storeDescription) as? String,
let oneSignalID = aDecoder.decodeObject(forKey: Constants.UserDefaults.oneSignalID) as? String
else { return nil }
self.uid = uid
self.username = username
self.phoneNumber = phoneNumber
self.storeDescription = storeDescription
self.profilePictureURL = aDecoder.decodeObject(forKey: Constants.UserDefaults.profilePicture) as? String
self.oneSignalID = oneSignalID
super.init()
}
init?(snapshot: DataSnapshot){
guard let snapshotValue = snapshot.value as? [String: Any],
let username = snapshotValue["username"] as? String,
let phoneNumber = snapshotValue["phoneNumber"] as? String,
let oneSignalID = snapshotValue["oneSignalID"] as? String,
let storeDescription = snapshotValue["storeDescription"] as? String,
!username.isEmpty,
!phoneNumber.isEmpty else {
return nil
}
self.uid = snapshot.key
self.username = username
self.phoneNumber = phoneNumber
self.storeDescription = storeDescription
self.oneSignalID = oneSignalID
self.profilePictureURL = snapshotValue["profilePicture"] as? String
super.init()
}
class func setCurrentUser(_ user: User, writeToUserDefaults: Bool = false) {
// Write user to user default
if writeToUserDefaults {
// Turn user object into data
let data = NSKeyedArchiver.archivedData(withRootObject: user)
// Store the data
UserDefaults.standard.set(data, forKey: Constants.UserDefaults.currentUser)
}
_current = user
}
static var currentUser: User {
guard let currentUser = _current else {
fatalError("There is no current user found")
}
return currentUser
}
}
extension User: NSCoding {
// Encode our user information in User Default
func encode(with aCoder: NSCoder) {
aCoder.encode(uid, forKey: Constants.UserDefaults.uid)
aCoder.encode(username, forKey: Constants.UserDefaults.username)
aCoder.encode(phoneNumber, forKey: Constants.UserDefaults.phoneNumber)
aCoder.encode(storeDescription, forKey: Constants.UserDefaults.storeDescription)
aCoder.encode(profilePictureURL, forKey: Constants.UserDefaults.profilePicture)
aCoder.encode(oneSignalID, forKey: Constants.UserDefaults.oneSignalID)
}
}
| f099315c210761e24c290849f45af5c2 | 36.28 | 117 | 0.653165 | false | false | false | false |
devpunk/velvet_room | refs/heads/master | Source/View/Connecting/VConnectingError.swift | mit | 1 | import UIKit
final class VConnectingError:View<ArchConnecting>
{
private let kMarginHorizontal:CGFloat = 45
required init(controller:CConnecting)
{
super.init(controller:controller)
isUserInteractionEnabled = false
factoryViews()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func factoryViews()
{
guard
let message:NSAttributedString = factoryMessage()
else
{
return
}
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.textAlignment = NSTextAlignment.center
labelTitle.numberOfLines = 0
labelTitle.attributedText = message
addSubview(labelTitle)
NSLayoutConstraint.equalsVertical(
view:labelTitle,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:labelTitle,
toView:self,
margin:kMarginHorizontal)
}
private func factoryMessage() -> NSAttributedString?
{
guard
let subtitle:NSAttributedString = factorySubtitle()
else
{
return nil
}
let title:NSAttributedString = factoryTitle()
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(title)
mutableString.append(subtitle)
return mutableString
}
private func factoryTitle() -> NSAttributedString
{
let string:String = String.localizedView(
key:"VConnectingError_labelTitle")
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font:
UIFont.medium(size:22),
NSAttributedStringKey.foregroundColor:
UIColor.white]
let attributed:NSAttributedString = NSAttributedString(
string:string,
attributes:attributes)
return attributed
}
private func factorySubtitle() -> NSAttributedString?
{
guard
let status:MConnectingStatusError = controller.model.status as? MConnectingStatusError
else
{
return nil
}
let string:String = String.localizedView(
key:status.errorMessage)
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font:
UIFont.regular(size:15),
NSAttributedStringKey.foregroundColor:
UIColor(white:1, alpha:0.9)]
let attributed:NSAttributedString = NSAttributedString(
string:string,
attributes:attributes)
return attributed
}
}
| 4af76b4f7ba18a1de99221de19fd758c | 26.225225 | 98 | 0.585043 | false | false | false | false |
zgorawski/LoLSkins | refs/heads/master | LoLSkins/Presenters/ChampionsPresenter.swift | mit | 1 | //
// ChampionsPresenter.swift
// LoLSkins
//
// Created by Zbigniew Górawski on 17/04/2017.
// Copyright © 2017 Zbigniew Górawski. All rights reserved.
//
import Foundation
import ReactiveSwift
import Result
protocol ChampionsPresenterSubscriber: class {
func present(champions: [ChampionsVM])
func show(error: ErrorVM)
}
class ChampionsPresenter {
let championsVM = MutableProperty<[ChampionsVM]?>(nil)
private weak var subscriber: ChampionsPresenterSubscriber!
private let staticAPI: StaticDataAPI
private let producer: SignalProducer<([LoLChampion], LoLVersion), NoError>
init(subscriber: ChampionsPresenterSubscriber, staticAPI: StaticDataAPI = DIContainer.shared.staticDataAPI) {
self.subscriber = subscriber
self.staticAPI = staticAPI
producer = SignalProducer.combineLatest(
staticAPI.champions.producer.skipNil(),
staticAPI.latestVersion.producer.skipNil())
producer.startWithValues { [weak self] (champions, varsion) in
guard let vm = self?.convertToVM(champions: champions, version: varsion) else { return }
self?.championsVM.value = vm
self?.subscriber.present(champions: vm)
}
// TODO: Observe errors
}
// MARK: Private
private func convertToVM(champions: [LoLChampion], version: LoLVersion) -> [ChampionsVM] {
return champions.map { champion in
let url = URL(string: "https://ddragon.leagueoflegends.com/cdn/\(version)/img/champion/\(champion.key).png")!
return ChampionsVM(key: champion.key, imageUrl: url, model: champion)
}
}
private func convertToVM(error: APIError) -> ErrorVM {
return ErrorVM(title: "error", message: error.localizedDescription)
}
}
struct ChampionsVM {
let key: String
let imageUrl: URL
let model: LoLChampion // TOOD: make it better
}
struct ErrorVM {
let title: String
let message: String
}
| f8b84ec12d589719a0ca914b3e54c74b | 29 | 121 | 0.664216 | false | false | false | false |
AloneMonkey/RxSwiftStudy | refs/heads/develop | Code/RxSwiftTutorial/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift | apache-2.0 | 15 | //
// BehaviorSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents a value that changes over time.
///
/// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
public final class BehaviorSubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, SynchronizedUnsubscribeType
, Disposable {
public typealias SubjectObserverType = BehaviorSubject<Element>
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
_lock.lock()
let value = _observers.count > 0
_lock.unlock()
return value
}
let _lock = RecursiveLock()
// state
private var _isDisposed = false
private var _value: Element
private var _observers = Bag<(Event<Element>) -> ()>()
private var _stoppedEvent: Event<Element>?
/// Indicates whether the subject has been disposed.
public var isDisposed: Bool {
return _isDisposed
}
/// Initializes a new instance of the subject that caches its last value and starts with the specified value.
///
/// - parameter value: Initial value sent to observers when no other value has been received by the subject yet.
public init(value: Element) {
_value = value
}
/// Gets the current value or throws an error.
///
/// - returns: Latest value.
public func value() throws -> Element {
_lock.lock(); defer { _lock.unlock() } // {
if _isDisposed {
throw RxError.disposed(object: self)
}
if let error = _stoppedEvent?.error {
// intentionally throw exception
throw error
}
else {
return _value
}
//}
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<E>) {
_lock.lock()
dispatch(_synchronized_on(event), event)
_lock.unlock()
}
func _synchronized_on(_ event: Event<E>) -> Bag<(Event<Element>) -> ()> {
if _stoppedEvent != nil || _isDisposed {
return Bag()
}
switch event {
case .next(let value):
_value = value
case .error, .completed:
_stoppedEvent = event
}
return _observers
}
/// Subscribes an observer to the subject.
///
/// - parameter observer: Observer to subscribe to the subject.
/// - returns: Disposable object that can be used to unsubscribe the observer from the subject.
public override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock()
let subscription = _synchronized_subscribe(observer)
_lock.unlock()
return subscription
}
func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
if _isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
let key = _observers.insert(observer.on)
observer.on(.next(_value))
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock()
_synchronized_unsubscribe(disposeKey)
_lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if _isDisposed {
return
}
_ = _observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> BehaviorSubject<Element> {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
_lock.lock()
_isDisposed = true
_observers.removeAll()
_stoppedEvent = nil
_lock.unlock()
}
}
| b07084b957459fcb617ccc853131fbb6 | 28.537415 | 116 | 0.587748 | false | false | false | false |
jonnguy/HSTracker | refs/heads/master | HSTracker/Logging/Parsers/TagChangeHandler.swift | mit | 1 | /*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 13/02/16.
*/
import Foundation
import RegexUtil
class TagChangeHandler {
let ParseEntityIDRegex: RegexPattern = "id=(\\d+)"
let ParseEntityZonePosRegex: RegexPattern = "zonePos=(\\d+)"
let ParseEntityPlayerRegex: RegexPattern = "player=(\\d+)"
let ParseEntityNameRegex: RegexPattern = "name=(\\w+)"
let ParseEntityZoneRegex: RegexPattern = "zone=(\\w+)"
let ParseEntityCardIDRegex: RegexPattern = "cardId=(\\w+)"
let ParseEntityTypeRegex: RegexPattern = "type=(\\w+)"
private var creationTagActionQueue: [(id: Int, action: (() -> Void))] = []
private var tagChangeAction = TagChangeActions()
func tagChange(eventHandler: PowerEventHandler, rawTag: String, id: Int,
rawValue: String, isCreationTag: Bool = false) {
if let tag = GameTag(rawString: rawTag) {
let value = self.parseTag(tag: tag, rawValue: rawValue)
tagChange(eventHandler: eventHandler, tag: tag, id: id, value: value,
isCreationTag: isCreationTag)
} else {
//logger.warning("Can't parse \(rawTag) -> \(rawValue)")
}
}
func tagChange(eventHandler: PowerEventHandler, tag: GameTag, id: Int,
value: Int, isCreationTag: Bool = false) {
if eventHandler.entities[id] == .none {
eventHandler.entities[id] = Entity(id: id)
}
eventHandler.lastId = id
if let entity = eventHandler.entities[id] {
let prevValue = entity[tag]
entity[tag] = value
if isCreationTag {
if let action = tagChangeAction.findAction(eventHandler: eventHandler,
tag: tag,
id: id,
value: value,
prevValue: prevValue) {
entity.info.hasOutstandingTagChanges = true
creationTagActionQueue.append((id: id, action: action))
}
} else {
tagChangeAction.findAction(eventHandler: eventHandler, tag: tag,
id: id, value: value,
prevValue: prevValue)?()
}
}
}
func invokeQueuedActions(eventHandler: PowerEventHandler) {
while creationTagActionQueue.count > 0 {
let action = creationTagActionQueue.removeFirst()
action.action()
if creationTagActionQueue.all({ $0.id != action.id }) && eventHandler.entities[action.id] != nil {
eventHandler.entities[action.id]!.info.hasOutstandingTagChanges = false
}
}
}
func clearQueuedActions() {
if creationTagActionQueue.count > 0 {
logger.warning("Clearing tagActionQueue with \(creationTagActionQueue.count)"
+ " elements in it")
}
creationTagActionQueue.removeAll()
}
struct LogEntity {
var id: Int?
var zonePos: Int?
var player: Int?
var name: String?
var zone: String?
var cardId: String?
var type: String?
func isValid() -> Bool {
let a: [Any?] = [id, zonePos, player, name, zone, cardId, type]
return a.any { $0 != nil }
}
}
// parse an entity
func parseEntity(entity: String) -> LogEntity {
var id: Int?, zonePos: Int?, player: Int?
var name: String?, zone: String?, cardId: String?, type: String?
if entity.match(ParseEntityIDRegex) {
if let match = entity.matches(ParseEntityIDRegex).first {
id = Int(match.value)
}
}
if entity.match(ParseEntityZonePosRegex) {
if let match = entity.matches(ParseEntityZonePosRegex).first {
zonePos = Int(match.value)
}
}
if entity.match(ParseEntityPlayerRegex) {
if let match = entity.matches(ParseEntityPlayerRegex).first {
player = Int(match.value)
}
}
if entity.match(ParseEntityNameRegex) {
if let match = entity.matches(ParseEntityNameRegex).first {
name = match.value
}
}
if entity.match(ParseEntityZoneRegex) {
if let match = entity.matches(ParseEntityZoneRegex).first {
zone = match.value
}
}
if entity.match(ParseEntityCardIDRegex) {
if let match = entity.matches(ParseEntityCardIDRegex).first {
cardId = match.value
}
}
if entity.match(ParseEntityTypeRegex) {
if let match = entity.matches(ParseEntityTypeRegex).first {
type = match.value
}
}
return LogEntity(id: id, zonePos: zonePos, player: player,
name: name, zone: zone, cardId: cardId, type: type)
}
// check if the entity is a raw entity
func isEntity(rawEntity: String) -> Bool {
return parseEntity(entity: rawEntity).isValid()
}
func parseTag(tag: GameTag, rawValue: String) -> Int {
switch tag {
case .zone:
return Zone(rawString: rawValue)!.rawValue
case .mulligan_state:
return Mulligan(rawString: rawValue)!.rawValue
case .playstate:
return PlayState(rawString: rawValue)!.rawValue
case .cardtype:
return CardType(rawString: rawValue)!.rawValue
case .class:
return TagClass(rawString: rawValue)!.rawValue
case .state:
return State(rawString: rawValue)!.rawValue
case .step:
return Step(rawString: rawValue)!.rawValue
default:
if let value = Int(rawValue) {
return value
}
return 0
}
}
}
| c83fc904bc029328270cd7d9fc7e8f2c | 33.674033 | 110 | 0.548757 | false | false | false | false |
RxSwiftCommunity/RxWebKit | refs/heads/master | Example/ObservingJSEventViewController.swift | mit | 1 | //
// ObservingJSEventViewController.swift
// Example
//
// Created by Jesse Hao on 2019/4/1.
// Copyright © 2019 RxSwift Community. All rights reserved.
//
import UIKit
import WebKit
import RxWebKit
import RxSwift
import RxCocoa
fileprivate let html = """
<!DOCTYPE html>
<meta content="width=device-width,user-scalable=no" name="viewport">
<html>
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="sendScriptMessage()">Send!</button>
<p id="demo"></p>
<script>
function sendScriptMessage() {
window.webkit.messageHandlers.RxWebKitScriptMessageHandler.postMessage('Hello RxWebKit')
}
</script>
</body>
</html>
"""
class ObservingJSEventViewController : UIViewController {
let bag = DisposeBag()
let webview = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webview)
webview.configuration.userContentController.rx.scriptMessage(forName: "RxWebKitScriptMessageHandler").bind { [weak self] scriptMessage in
guard let message = scriptMessage.body as? String else { return }
let alert = UIAlertController(title: "JS Event Observed", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
self?.present(alert, animated: true)
}.disposed(by: self.bag)
webview.loadHTMLString(html, baseURL: nil)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let originY = UIApplication.shared.statusBarFrame.maxY
webview.frame = CGRect(x: 0, y: originY, width: view.bounds.width, height: view.bounds.height)
}
}
| 4ffe6b2e4ca599e40ac58894fa3e7fff | 27.440678 | 145 | 0.695471 | false | false | false | false |
realm/SwiftLint | refs/heads/main | Source/SwiftLintFramework/Extensions/QueuedPrint.swift | mit | 1 | import Dispatch
import Foundation
private let outputQueue: DispatchQueue = {
let queue = DispatchQueue(
label: "io.realm.swiftlint.outputQueue",
qos: .userInteractive,
target: .global(qos: .userInteractive)
)
defer {
setupAtExitHandler()
}
return queue
}()
private func setupAtExitHandler() {
atexit {
outputQueue.sync(flags: .barrier) {}
}
}
/**
A thread-safe version of Swift's standard `print()`.
- parameter object: Object to print.
*/
public func queuedPrint<T>(_ object: T) {
outputQueue.async {
print(object)
}
}
/**
A thread-safe, newline-terminated version of `fputs(..., stderr)`.
- parameter string: String to print.
*/
public func queuedPrintError(_ string: String) {
outputQueue.async {
fflush(stdout)
fputs(string + "\n", stderr)
}
}
/**
A thread-safe, newline-terminated version of `fatalError(...)` that doesn't leak
the source path from the compiled binary.
*/
public func queuedFatalError(_ string: String, file: StaticString = #file, line: UInt = #line) -> Never {
outputQueue.sync {
fflush(stdout)
let file = "\(file)".bridge().lastPathComponent
fputs("\(string): file \(file), line \(line)\n", stderr)
}
abort()
}
| 15427a1e842888bd3a77215b749a4847 | 21 | 105 | 0.627119 | false | false | false | false |
eofster/Telephone | refs/heads/master | Telephone/DefaultStoreViewEventTarget.swift | gpl-3.0 | 1 | //
// DefaultStoreViewEventTarget.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
import Foundation
final class DefaultStoreViewEventTarget {
private(set) var state: StoreViewState = StoreViewStateNoProducts()
private var products: [Product] = []
private var fetchError = ""
private let factory: StoreUseCaseFactory
private let restoration: UseCase
private let refresh: UseCase
private let presenter: StoreViewPresenter
init(factory: StoreUseCaseFactory, purchaseRestoration: UseCase, receiptRefresh: UseCase, presenter: StoreViewPresenter) {
self.factory = factory
self.restoration = purchaseRestoration
self.refresh = receiptRefresh
self.presenter = presenter
}
}
extension DefaultStoreViewEventTarget: StoreViewStateMachine {
func changeState(_ newState: StoreViewState) {
state = newState
}
func checkPurchase() {
presenter.showPurchaseCheckProgress()
factory.makePurchaseCheckUseCase(output: self).execute()
}
func fetchProducts() {
presenter.showProductsFetchProgress()
factory.makeProductsFetchUseCase(output: self).execute()
}
func show(_ products: [Product]) {
self.products = products
presenter.show(products)
}
func showProductsFetchError(_ error: String) {
fetchError = error
presenter.showProductsFetchError(error)
}
func purchaseProduct(withIdentifier identifier: String) {
do {
try factory.makeProductPurchaseUseCase(identifier: identifier).execute()
} catch {
print("Could not make purchase: \(error)")
}
}
func showPurchaseProgress() {
presenter.showPurchaseProgress()
}
func showCachedProductsAndPurchaseError(_ error: String) {
showCachedProducts()
presenter.showPurchaseError(error)
}
func showCachedProducts() {
presenter.show(products)
}
func restorePurchases() {
restoration.execute()
presenter.showPurchaseRestorationProgress()
}
func refreshReceipt() {
refresh.execute()
}
func showCachedProductsAndRestoreError(_ error: String) {
showCachedProducts()
presenter.showPurchaseRestorationError(error)
}
func showCachedFetchErrorAndRestoreError(_ error: String) {
showCachedFetchError()
presenter.showPurchaseRestorationError(error)
}
func showCachedFetchError() {
presenter.showProductsFetchError(fetchError)
}
func showThankYou(expiration: Date) {
presenter.showPurchased(until: expiration)
}
}
| 74fa68778d1abf75ab9a281ba0e6be92 | 27.981982 | 126 | 0.691638 | false | false | false | false |
alsfox/ZYJModel | refs/heads/master | ZYJModel/ZYJModel/ZYJIvar.swift | mit | 1 | //
// ZYJIvar.swift
// ZYJModel
//
// Created by 张亚举 on 16/6/14.
// Copyright © 2016年 张亚举. All rights reserved.
//
import UIKit
/// 转换为 Sql 数据库里的 类型
public enum ZYJSqlType: String {
/// 整数
case INTEGER_TYPE = "INTEGER DEFAULT 0"
case INTEGERKEY_TYPE = "INTEGER UNIQUE DEFAULT 0"
/// 文字
case TEXT_TYPE = "TEXT DEFAULT ''"
/// 小娄
case REAL_TYPE = "REAL DEFAULT 0.0"
case ARR_TYPE = "TEXT DEFAULT ''"
/// 空字符
case EmptyString = ""
}
class ZYJIvar: NSObject {
/// 变量名字
var ivarName : String = ""
var ivarValue: NSObject?
/// 变量转换的 Sql 数据库类型
var ivarSqlType : ZYJSqlType {
get{
if ivarName == "zyj_hostId" {
return ZYJSqlType.INTEGERKEY_TYPE
}
switch ivarType {
case is String?.Type:
return .TEXT_TYPE
case is Int?.Type:
return .INTEGER_TYPE
case is CGFloat?.Type:
return .REAL_TYPE
case is NSString?.Type:
return .TEXT_TYPE
case is Bool?.Type:
return .INTEGER_TYPE
case is NSArray?.Type:
return .ARR_TYPE
case is NSMutableArray?.Type:
return .ARR_TYPE
case is Double?.Type:
return .REAL_TYPE
case is String.Type:
return .TEXT_TYPE
case is Int.Type:
return .INTEGER_TYPE
case is CGFloat.Type:
return .REAL_TYPE
case is NSString.Type:
return .TEXT_TYPE
case is Bool.Type:
return .INTEGER_TYPE
case is NSArray.Type:
return .ARR_TYPE
case is NSMutableArray.Type:
return .ARR_TYPE
case is Double.Type:
return .REAL_TYPE
default:
return .EmptyString
}
}
}
var ivarCode = ""
/// 变量类型
var ivarType : Any.Type!
/// 判断是不是 String
var isString : Bool {
get {
switch ivarType {
case is String.Type:
return true
case is String?.Type:
return true;
case is NSString.Type:
return true
case is NSString?.Type:
return true
default:
return false
}
}
}
var isData : Bool {
get {
switch ivarType {
case is NSData.Type:
return true
case is NSData?.Type:
return true;
default:
return false
}
}
}
var isArr : Bool {
get {
switch ivarType {
case is NSArray.Type:
return true
case is NSArray?.Type:
return true;
default:
return false
}
}
}
}
| f0c7fd76ac02944afe711001c8b7f55c | 21 | 53 | 0.394225 | false | false | false | false |
congncif/PagingDataController | refs/heads/master | PagingDataController/UIExtension/PagingControllerProtocol+Extension.swift | mit | 1 | //
// PagingControllerProtocolExtension.swift
// PagingDataControllerExtension
//
// Created by NGUYEN CHI CONG on 3/16/19.
//
import Foundation
import UIKit
@objc public enum PagingFirstLoadingStyle: Int {
case none
case autoTrigger
case progressHUD // Heads-up Display
}
extension PagingControllerProtocol {
public func setupPagingDataSource(delegate: PageDataSourceDelegate?) {
dataSource.delegate = delegate
}
public func setupPullDownToRefresh(pagingView: PagingControllerViewable, nativeControl: Bool = false) {
if nativeControl {
let refreshControl = UIRefreshControl { [weak self] control in
self?.loadFirstPageWithCompletion { [weak pagingView] in
guard let pagingView = pagingView else { return }
pagingView.pagingScrollView.reloadContent(instantReloadContent: pagingView.instantReloadContent) {
control.endRefreshing()
}
}
}
if #available(iOS 10.0, *) {
pagingView.pagingScrollView.refreshControl = refreshControl
} else {
pagingView.pagingScrollView.addSubview(refreshControl)
}
} else {
pagingView.pagingScrollView.addPullToRefresh { [weak self] in
self?.loadFirstPageWithCompletion { [weak pagingView] in
guard let pagingView = pagingView else { return }
pagingView.pagingScrollView.reloadContent(instantReloadContent: pagingView.instantReloadContent) { [weak pagingView] in
pagingView?.pagingScrollView.pullToRefreshView.stopAnimating()
}
}
}
}
}
public func setupPullUpToLoadMore(pagingView: PagingControllerViewable) {
pagingView.pagingScrollView.addInfiniteScrolling { [weak self] in
self?.loadNextPageWithCompletion { [weak pagingView] in
guard let pagingView = pagingView else { return }
pagingView.pagingScrollView.reloadContent(instantReloadContent: pagingView.instantReloadContent) { [weak pagingView] in
pagingView?.pagingScrollView.infiniteScrollingView.stopAnimating()
}
}
}
pagingView.pagingScrollView.showsInfiniteScrolling = dataSource.hasMore
}
public func triggerRefresh(pagingView: PagingControllerViewable, nativeRefreshControl: Bool = false) {
if nativeRefreshControl {
if let control = pagingView.pagingScrollView.nativeRefreshControl {
control.beginRefreshing()
loadFirstPageWithCompletion { [weak pagingView] in
guard let pagingView = pagingView else { return }
pagingView.pagingScrollView.reloadContent(instantReloadContent: pagingView.instantReloadContent,
end: control.endRefreshing)
}
} else {
print("*** Refresh control not found ***")
}
} else {
pagingView.pagingScrollView.triggerPullToRefresh()
}
}
public func loadDataFirstPage(pagingView: PagingControllerViewable) {
pagingView.startLoading()
loadFirstPageWithCompletion { [weak pagingView] in
guard let pagingView = pagingView else { return }
pagingView.pagingScrollView.reloadContent(instantReloadContent: pagingView.instantReloadContent,
end: pagingView.stopLoading)
}
}
public func setupPagingControlling(pagingView: PagingControllerViewable,
nativeRefreshControl: Bool = false,
firstLoadingStyle style: PagingFirstLoadingStyle = .progressHUD) {
setupPullDownToRefresh(pagingView: pagingView, nativeControl: nativeRefreshControl)
setupPullUpToLoadMore(pagingView: pagingView)
switch style {
case .autoTrigger:
triggerRefresh(pagingView: pagingView, nativeRefreshControl: nativeRefreshControl)
case .progressHUD:
loadDataFirstPage(pagingView: pagingView)
default:
break
}
}
}
extension PagingControllerConfigurable where Self: PagingControllerProtocol {
public func setupForPaging() {
setupPagingControlling(pagingView: pagingView, nativeRefreshControl: true, firstLoadingStyle: .progressHUD)
}
public func refreshPaging() {
loadDataFirstPage(pagingView: pagingView)
}
}
extension PagingControllerProtocol where Self.PagingProvider == Self {
public var provider: PagingProvider {
return self
}
}
| 1bc40d447cfefc326e6ddd22fcaec51d | 39.658333 | 139 | 0.627998 | false | false | false | false |
aleclarson/emitter-kit | refs/heads/master | src/Helpers.swift | mit | 1 |
import Foundation
func WeakPointer <T: Any> (_ object: T) -> DynamicPointer<T> {
let ptr = DynamicPointer<T>()
ptr.weakPointer = object
return ptr
}
func StrongPointer <T: Any> (_ object: T) -> DynamicPointer<T> {
let ptr = DynamicPointer<T>()
ptr.strongPointer = object
return ptr
}
class DynamicPointer <T: AnyObject> {
var object: T! { return strongPointer ?? weakPointer ?? nil }
init () {}
var strongPointer: T!
weak var weakPointer: T!
}
/// Generate a unique identifier for an object.
/// 2nd slowest. Converts to String.
func getHash (_ object: AnyObject) -> String {
return String(identify(object))
}
/// Generate a unique identifier for an object.
/// Fastest. Every other function relies on this one.
func identify (_ object: AnyObject) -> UInt {
return UInt(bitPattern: ObjectIdentifier(object))
}
/// Generate a unique identifier for an object.
/// Slowest. Checks for nil and converts to String.
func getHash (_ object: AnyObject?) -> String {
return object == nil ? "0" : String(identify(object))
}
///// Generate a unique identifier for an object.
///// 2nd fastest. Checks for nil.
func identify (_ object: AnyObject?) -> UInt {
return object == nil ? 0 : identify(object!)
}
extension Array {
var nilIfEmpty: [Element]! { return count > 0 ? self : nil }
}
extension Dictionary {
var nilIfEmpty: [Key:Value]! { return count > 0 ? self : nil }
}
| 8e50f4fcdea4338829963ea3085acd8c | 23.701754 | 64 | 0.678977 | false | false | false | false |
ovenbits/ModelRocket | refs/heads/master | Sources/JSON.swift | mit | 1 | // JSON.swift
//
// Copyright (c) 2015 Oven Bits, LLC
//
// 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 struct JSON {
private var object: AnyObject?
public init() {
self.object = nil
}
public init(_ object: AnyObject?) {
self.object = object
}
public init(data: NSData?) {
if let data = data, let object: AnyObject = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) {
self.init(object)
}
else {
self.init()
}
}
public subscript(key: String) -> JSON {
set {
if let tempObject = object as? [String : AnyObject] {
var object = tempObject
object[key] = newValue.object
self.object = object
}
else {
var tempObject: [String : AnyObject] = [:]
tempObject[key] = newValue.object
self.object = tempObject
}
}
get {
/**
NSDictionary is used because it currently performs better than a native Swift dictionary.
The reason for this is that [String : AnyObject] is bridged to NSDictionary deep down the
call stack, and this bridging operation is relatively expensive. Until Swift is ABI stable
and/or doesn't require a bridge to Objective-C, NSDictionary will be used here
*/
if let dictionary = object as? NSDictionary {
return JSON(dictionary[key])
}
return JSON()
}
}
@available(*, deprecated=1.2, message="Use !hasKey instead.") public var isNil: Bool {
return (object == nil)
}
public var hasKey: Bool {
return object != nil
}
public var hasValue: Bool {
return object != nil && !(object is NSNull)
}
}
// MARK: - CustomStringConvertible
extension JSON: CustomStringConvertible {
public var description: String {
if let object: AnyObject = object {
switch object {
case is String, is NSNumber, is Float, is Double, is Int, is UInt, is Bool: return "\(object)"
case is [AnyObject], is [String : AnyObject]:
if let data = try? NSJSONSerialization.dataWithJSONObject(object, options: .PrettyPrinted) {
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String ?? ""
}
default: return ""
}
}
return "\(object)"
}
}
// MARK: - CustomDebugStringConvertible
extension JSON: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
// MARK: - NilLiteralConvertible
extension JSON: NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init()
}
}
// MARK: - StringLiteralConvertible
extension JSON: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
// MARK: - FloatLiteralConvertible
extension JSON: FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
// MARK: - IntegerLiteralConvertible
extension JSON: IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
// MARK: - BooleanLiteralConvertible
extension JSON: BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
// MARK: - ArrayLiteralConvertible
extension JSON: ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
// MARK: - DictionaryLiteralConvertible
extension JSON: DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
var object: [String : AnyObject] = [:]
for (key, value) in elements {
object[key] = value
}
self.init(object)
}
}
// MARK: - CollectionType
extension JSON: CollectionType {
public func generate() -> IndexingGenerator<[JSON]> {
return arrayValue.generate()
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return arrayValue.count
}
public subscript(position: Int) -> JSON {
return arrayValue[position]
}
}
// MARK: - String
extension JSON {
public var string: String? { return object as? String }
public var stringValue: String { return string ?? "" }
}
// MARK: - NSNumber
extension JSON {
public var number: NSNumber? { return object as? NSNumber }
public var numberValue: NSNumber { return number ?? 0 }
}
// MARK: - Float
extension JSON {
public var float: Float? { return object as? Float }
public var floatValue: Float { return float ?? 0 }
}
// MARK: - Double
extension JSON {
public var double: Double? { return object as? Double }
public var doubleValue: Double { return double ?? 0 }
}
// MARK: - Int
extension JSON {
public var int: Int? { return object as? Int }
public var intValue: Int { return int ?? 0 }
}
// MARK: - UInt
extension JSON {
public var uInt: UInt? { return object as? UInt }
public var uIntValue: UInt { return uInt ?? 0 }
}
// MARK: - Bool
extension JSON {
public var bool: Bool? { return object as? Bool }
public var boolValue: Bool { return bool ?? false }
}
// MARK: - NSURL
extension JSON {
public var URL: NSURL? {
if let urlString = string {
return NSURL(string: urlString)
}
return nil
}
}
// MARK: - Array
extension JSON {
public var array: [JSON]? {
if let array = object as? [AnyObject] {
return array.map { JSON($0) }
}
return nil
}
public var arrayValue: [JSON] { return array ?? [] }
}
// MARK: - Dictionary
extension JSON {
public var dictionary: [String : JSON]? {
if let dictionary = object as? [String : AnyObject] {
return Dictionary(dictionary.map { ($0, JSON($1)) })
}
return nil
}
public var dictionaryValue: [String : JSON] { return dictionary ?? [:] }
}
extension Dictionary {
private init(_ pairs: [Element]) {
self.init()
for (key, value) in pairs {
self[key] = value
}
}
}
// MARK: - Raw
extension JSON: RawRepresentable {
public enum DataError: ErrorType {
case MissingObject
case InvalidObject
}
public init?(rawValue: AnyObject) {
guard NSJSONSerialization.isValidJSONObject(rawValue) else { return nil }
self.init(rawValue)
}
public var rawValue: AnyObject {
return object ?? NSNull()
}
public func rawData(options: NSJSONWritingOptions = []) throws -> NSData {
guard let object = object else { throw DataError.MissingObject }
guard NSJSONSerialization.isValidJSONObject(object) else { throw DataError.InvalidObject }
return try NSJSONSerialization.dataWithJSONObject(object, options: options)
}
}
// MARK: - Equatable
extension JSON: Equatable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
guard let lhsObject: AnyObject = lhs.object, rhsObject: AnyObject = rhs.object else { return false }
switch (lhsObject, rhsObject) {
case (let left as String, let right as String):
return left == right
case (let left as Double, let right as Double):
return left == right
case (let left as Float, let right as Float):
return left == right
case (let left as Int, let right as Int):
return left == right
case (let left as UInt, let right as UInt):
return left == right
case (let left as Bool, let right as Bool):
return left == right
case (let left as NSURL, let right as NSURL):
return left == right
case (let left as NSNumber, let right as NSNumber):
return left == right
case (let left as [AnyObject], let right as [AnyObject]):
return left.map { JSON($0) } == right.map { JSON ($0) }
case (let left as [String : AnyObject], let right as [String : AnyObject]):
return Dictionary(left.map { ($0, JSON($1)) }) == Dictionary(right.map { ($0, JSON($1)) })
default: return false
}
}
| ae08b93f045918ab523aacdc617b6d9b | 26.509859 | 129 | 0.617448 | false | false | false | false |
grgcombs/PlayingCards-Swift | refs/heads/master | Pod/Classes/CardGlyphs.swift | mit | 1 | //
// CardGlyphs.swift
// Pods
//
// Created by Gregory Combs on 7/23/15.
// Copyright (c) 2015 PlayingCards (Swift). All rights reserved.
//
import Foundation
internal typealias CardGlyphMap = [CardType : String];
internal typealias SuitGlyphMap = [SuitType : CardGlyphMap];
internal class CardGlyphs {
static func glyphForSuit(suiteType:SuitType, cardType:CardType) -> String? {
if let glyphs = SharedCardGlyphs.cardGlyphs[suiteType] ?? nil {
return glyphs[cardType] ?? nil;
}
return nil;
}
}
/**
* The singleton ensures the (expensive) setup is completed only once,
* no matter how many times you need to access the card glyphs.
*/
private let SharedCardGlyphs : CardGlyphsPrivate = CardGlyphsPrivate();
private class CardGlyphsPrivate {
init() {
var emptyMap : SuitGlyphMap = [:];
cardGlyphs = SuitType.allValues.map({
($0, $0.cardGlyphMap)
}).reduce(emptyMap, combine: {
var map : SuitGlyphMap = $0;
let tuple : GlyphTuple = $1;
map[tuple.suiteType] = tuple.cardGlyphs;
return map;
});
}
private typealias GlyphTuple = (suiteType: SuitType, cardGlyphs: CardGlyphMap);
private let cardGlyphs : SuitGlyphMap;
}
private extension SuitType {
private typealias IndexedCardTypeTuple = (index: Int, element: CardType);
private typealias RangeWithExclusion = (range: Range<Int>, exclude: Int);
private var cardGlyphRange : RangeWithExclusion {
get {
switch self {
case .Spades:
return (0x1F0A1...0x1F0AE, 0x1F0AC);
case .Hearts:
return (0x1F0B1...0x1F0BE, 0x1F0BC);
case .Diamonds:
return (0x1F0C1...0x1F0CE, 0x1F0CC);
case .Clubs:
return (0x1F0D1...0x1F0DE, 0x1F0DC);
}
}
}
private var cardGlyphMap : CardGlyphMap {
get {
var cardTypes = EnumerateGenerator(CardType.allValues.generate())
let range = cardGlyphRange;
var glyphs : CardGlyphMap = [:];
for code in range.range {
if code == range.exclude {
continue;
}
let scalar = UnicodeScalar(code);
let char = Character(scalar);
if let tuple : IndexedCardTypeTuple = cardTypes.next() {
let cardType = tuple.element;
glyphs[cardType] = "\(char)";
continue;
}
break; // no more next()'s, time to quit
}
return glyphs;
}
}
}
| e2afa20a06e539a2f63842e431651cb6 | 27.723404 | 83 | 0.566667 | false | false | false | false |
pawrsccouk/Stereogram | refs/heads/master | Stereogram-iPad/StereogramViewController.swift | mit | 1 | //
// StereogramViewController.swif
// Stereogram-iPad
//
// Created by Patrick Wallace on 22/01/2015.
// Copyright (c) 2015 Patrick Wallace. All rights reserved.
//
import UIKit
import MobileCoreServices
/// Protocol for delegates of the stereogram view controller.
///
/// Contains notifications sent during the stereogram taking process
/// and provides the stereogram to the user once it has been taken.
@objc protocol StereogramViewControllerDelegate {
/// Triggered when the controller starts displaying the camera view.
///
/// :param: controller - The controller that sent this message.
/// :param: photoNumber - Will be 1 or 2 depending on which photo is being taken.
optional func stereogramViewController(controller: StereogramViewController,
takingPhoto photoNumber: Int)
/// Called when the stereogram has been taken.
///
/// The delegate must save the image and dismiss the view controller.
///
/// :param: stereogram - The stereogram the user has just finished taking.
/// :param: controller - The controller that sent this message.
func stereogramViewController(controller: StereogramViewController
, createdStereogram stereogram: Stereogram)
/// Called if the user cancels the view controller and doesn't want to create a stereogram.
///
/// The delegate must dismiss the view controller.
///
/// :param: controller - The controller that sent this message.
func stereogramViewControllerWasCancelled(controller: StereogramViewController)
}
/// This class manages the stereogram view, creating the camera overlay controller,
/// presenting them both and acting as delegate for the camera.
///
/// It encapsulates the state needed to take a stereogram and just holds the completed stereogram.
class StereogramViewController: NSObject {
/// The stereogram the user has taken, if any.
var stereogram: Stereogram? {
switch state {
case .Complete(let stereogram): return stereogram
default: return nil
}
}
/// The delegate to notify when the view completes or is cancelled.
var delegate: StereogramViewControllerDelegate = NullDelegate()
/// The state we are in, i.e. where we are in the stereogram process.
private var state = State.Ready
/// The controller that presented this one.
private weak var parentViewController: UIViewController!
/// The camera overlay with help text and crosshairs.
private let cameraOverlayController = CameraOverlayViewController()
/// The camera view controller.
private var pickerController: UIImagePickerController?
/// The photo store where we will save the stereogram.
private let photoStore: PhotoStore
/// Initialize with a photo store.
///
/// :param: photoStore - The photo store to work with.
init(photoStore: PhotoStore) {
self.photoStore = photoStore
super.init()
}
/// Reset the controller back to the default state.
/// If we stored a stereogram from a previous run it will be released,
/// so you must have a reference to it already.
func reset() {
state = .Ready
cameraOverlayController.helpText = "Take the first photo"
}
/// Display the camera, take the user through the specified steps to produce a stereogram image
/// and put the result in self.stereogram.
///
/// :param: parentViewController - The view controller handling the currently visible view.
/// This controller will put its view on top of that view.
func takePicture(parentViewController: UIViewController) {
if !UIImagePickerController.isSourceTypeAvailable(.Camera) {
let alertView = UIAlertView(title: "No camera"
, message: "This device does not have a camera attached"
, delegate: nil
, cancelButtonTitle: "Close")
alertView.show()
return
}
switch state {
case .Ready, .Complete:
self.parentViewController = parentViewController
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.mediaTypes = [kUTTypeImage] // Only accept still images, not movies.
picker.delegate = self
picker.showsCameraControls = false
pickerController = picker
// Set up a custom overlay view for the camera.
// Ensure our custom view frame fits within the camera view's frame.
cameraOverlayController.view.frame = picker.view.frame
picker.cameraOverlayView = cameraOverlayController.view
cameraOverlayController.imagePickerController = pickerController
cameraOverlayController.helpText = "Take the first photo"
parentViewController.presentViewController(picker, animated: true, completion: nil)
state = .TakingFirstPhoto
delegate.stereogramViewController?(self, takingPhoto: 1)
case .TakingFirstPhoto, .TakingSecondPhoto:
fatalError("State \(state) was invalid. Another photo operation already in progress.")
}
}
/// Dismisses the view controller that was presented modally by the receiver.
///
/// :param: animated - Pass YES to animate the transition.
/// :param: completion - The block to execute after the view controller is dismissed.
func dismissViewControllerAnimated(animated: Bool, completion: (() -> Void)?) {
if let picker = pickerController {
picker.dismissViewControllerAnimated(animated, completion: completion)
}
pickerController = nil
}
}
// MARK: - Navigation Controller Delegate
// We need to express that we support the delegate protocol even if we don't care about
// any of the options it gives us.
extension StereogramViewController: UINavigationControllerDelegate {
}
// MARK: Image Picker Delegate
extension StereogramViewController: UIImagePickerControllerDelegate {
func imagePickerController( picker: UIImagePickerController
, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
switch state {
case .TakingFirstPhoto:
state = .TakingSecondPhoto(firstPhoto: imageFromPickerInfoDict(info))
cameraOverlayController.helpText = "Take the second photo"
delegate.stereogramViewController?(self, takingPhoto: 2)
case .TakingSecondPhoto(let firstPhoto):
let secondPhoto = imageFromPickerInfoDict(info)
cameraOverlayController.showWaitIcon = true
// Make the stereogram on a separate thread to avoid blocking the UI thread.
// The UI shows the wait indicator.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let result = self.photoStore.createStereogramFromLeftImage(firstPhoto
, rightImage: secondPhoto)
// Once the stereogram is made, update the UI code back on the main thread.
dispatch_async(dispatch_get_main_queue()) {
switch result {
case .Success(let image):
self.state = .Complete(stereogram: image.value)
self.cameraOverlayController.showWaitIcon = false
self.delegate.stereogramViewController(self, createdStereogram: image.value)
case .Error(let error):
if let parent = self.parentViewController {
error.showAlertWithTitle("Error creating the stereogram image"
, parentViewController: parent)
} else {
NSLog("Error returned from makeStereogram() "
+ "and no parent controller to display it on: \(error)")
}
}
self.state = .Ready
}
}
default:
fatalError("\(state) should be TakingFirstPhoto or TakingSecondPhoto")
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
state = .Ready
delegate.stereogramViewControllerWasCancelled(self)
}
}
// MARK: - Private data
extension StereogramViewController {
/// This controller can be in multiple states. Capture these here.
///
/// - Ready: The process has not started yet.
/// - TakingFirstPhoto: We are currently taking the first photo.
/// - TakingSecondPhoto: We are currently taking the second photo.
/// - Complete: We have taken both photos and composited them into a stereogram.
private enum State {
/// The photo process has not started yet.
case Ready
/// We are currently taking the first photo
case TakingFirstPhoto
/// We are currently taking the second photo.
///
/// :param: firstPhoto - Contains the first photo we took
case TakingSecondPhoto(firstPhoto: UIImage)
/// We have taken both photos and composited them into a stereogram.
///
/// :param: sterogram - The stereogram we've just created.
case Complete(stereogram: Stereogram)
/// Standard initializer. Defaults this object to the Ready state.
init() {
self = .Ready
}
/// Description of the enumeration in human-readable text.
var description: String {
switch self {
case .Ready: return "Ready"
case .TakingFirstPhoto: return "TakingFirstPhoto"
case .TakingSecondPhoto: return "TakingSecondPhoto"
case .Complete: return "Complete"
}
}
}
/// Get the edited photo from the info dictionary if the user has edited it.
/// If there is no edited photo, get the original photo.
///
/// :param: infoDict - The userInfo dictionary returned from the image picker controller
/// with the selected image in it.
/// :returns: The UIImage taken from the dictionary.
///
/// If there is no original photo, terminate with an error.
private func imageFromPickerInfoDict(infoDict: [NSObject : AnyObject]) -> UIImage {
if let photo = infoDict[UIImagePickerControllerEditedImage] as? UIImage {
return photo
}
if let d = infoDict[UIImagePickerControllerOriginalImage] as? UIImage {
return d
} else {
assert(false, "Image for key \(UIImagePickerControllerOriginalImage) "
+ "not found in dict \(infoDict)")
return UIImage()
}
}
}
/// A Do-nothing delegate object which by default just dismisses the view controller
/// without caring about the stereogram.
private class NullDelegate: NSObject, StereogramViewControllerDelegate {
@objc private func stereogramViewController(controller: StereogramViewController
, createdStereogram stereogram: Stereogram) {
controller.dismissViewControllerAnimated(false, completion: nil)
}
@objc private func stereogramViewControllerWasCancelled(controller: StereogramViewController) {
controller.dismissViewControllerAnimated(false, completion: nil)
}
}
| ec734802d98d0d3cf8c764a2e00f2b6a | 37.09396 | 100 | 0.656536 | false | false | false | false |
Eonil/PseudoTeletypewriter.Swift | refs/heads/master | EonilPTYDemo/Data.extension.swift | mit | 1 | //
// Data.extension.swift
// EonilPTYDemo
//
// Created by Henry on 2018/10/08.
// Copyright © 2018 Eonil. All rights reserved.
//
import Foundation
extension Data {
func toUInt8Array() -> [UInt8] {
let p = (self as NSData).bytes
var bs = [] as [UInt8]
for i in 0..<self.count {
let dataPtr = p.advanced(by: i)
let datum = dataPtr.load(as: UInt8.self)
bs.append(datum)
}
return bs
}
func toString() -> String {
return NSString(data: self, encoding: String.Encoding.utf8.rawValue)! as String
}
static func fromUInt8Array(_ bs:[UInt8]) -> Data {
var r = nil as Data?
bs.withUnsafeBufferPointer { (p:UnsafeBufferPointer<UInt8>) -> () in
let p1 = UnsafeRawPointer(p.baseAddress)!
let opPtr = OpaquePointer(p1)
r = Data(bytes: UnsafePointer<UInt8>(opPtr), count: p.count)
}
return r!
}
/// Assumes `cCharacters` is C-string.
static func fromCCharArray(_ cCharacters:[CChar]) -> Data {
precondition(cCharacters.count == 0 || cCharacters[(cCharacters.endIndex - 1)] == 0)
var r = nil as Data?
cCharacters.withUnsafeBufferPointer { (p:UnsafeBufferPointer<CChar>) -> () in
let p1 = UnsafeRawPointer(p.baseAddress)!
let opPtr = OpaquePointer(p1)
r = Data(bytes: UnsafePointer<UInt8>(opPtr), count: p.count)
}
return r!
}
}
| 72a23068e6d0405b10c72c1fff1b1def | 30.041667 | 92 | 0.579195 | false | false | false | false |
White-Label/Swift-SDK | refs/heads/master | WhiteLabel/PagingGenerator.swift | mit | 1 | //
// PagingGenerator.swift
//
// Based on code by by Marcin Krzyzanowski on 22/06/15.
// Copyright (c) 2015 Marcin Krzyżanowski. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
open class PagingGenerator {
open var next: ((_ page: Int, _ completionMarker: @escaping ((_ success: Bool) -> Void) ) -> Void)!
open var page: Int
open var startPage: Int = 1
open var didReachEnd: Bool = false
open var isFetchingPage: Bool = false
public init(startPage: Int) {
self.startPage = startPage
self.page = startPage
}
open func getNext(_ complete: (() -> Void)? = nil) {
if didReachEnd { return }
isFetchingPage = true
next(page) { success in
if success {
self.page += 1
}
self.isFetchingPage = false
complete?()
}
}
open func reachedEnd() {
didReachEnd = true
}
open func reset() {
didReachEnd = false
page = startPage
}
}
| 5dd19cf6aba167e998cf04a23abf2149 | 33.145161 | 103 | 0.659896 | false | false | false | false |
morbrian/udacity-nano-onthemap | refs/heads/master | OnTheMap/StudentMapViewController.swift | mit | 1 | //
// StudentMapViewController.swift
// OnTheMap
//
// Created by Brian Moriarty on 4/28/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import UIKit
import MapKit
// StudentMapViewController
// Displays a map showing geo-positions of all student study locations
class StudentMapViewController: OnTheMapBaseViewController {
@IBOutlet weak var mapView: MKMapView!
var activitySpinner: SpinnerPanelView!
// MARK: ViewController Lifecycle
override func viewDidLoad() {
activitySpinner = produceSpinner()
view.addSubview(activitySpinner)
mapView.mapType = .Satellite
mapView.delegate = self
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateDisplayFromModel()
centerMapOnCurrentUser()
}
// a custom spinner used during network activity
private func produceSpinner() -> SpinnerPanelView {
let activitySpinner = SpinnerPanelView(frame: view.bounds, spinnerImageView: UIImageView(image: UIImage(named: "Udacity")))
activitySpinner.backgroundColor = UIColor.orangeColor()
activitySpinner.alpha = CGFloat(0.5)
return activitySpinner
}
// MARK: Overrides From OnTheMapBaseViewController
// clear existing annotations and reload from datamanager cache
override func updateDisplayFromModel() {
if let studentLocations = dataManager?.studentLocations {
let optionalAnnotations = studentLocations.map() { StudentAnnotation(student: $0) }
let filteredAnnotations = optionalAnnotations.filter() { $0 != nil }
let studentAnnotations = filteredAnnotations.map() { $0! as StudentAnnotation }
dispatch_async(dispatch_get_main_queue()) {
self.mapView.removeAnnotations(self.mapView.annotations)
self.mapView.addAnnotations(studentAnnotations)
if let willCenterOnUser = self.dataManager?.loggedInUserDoesHaveLocation()
where !willCenterOnUser {
self.mapView.showAnnotations(studentAnnotations, animated: true)
}
}
}
}
// display custom spinner
override func networkActivity(active: Bool, intrusive: Bool = true) {
dispatch_async(dispatch_get_main_queue()) {
if (intrusive) {
self.activitySpinner.spinnerActivity(active)
} else {
super.networkActivity(active)
}
}
}
// after user data downloaded, center map on that location
override func currentUserDataNowAvailable() {
dispatch_async(dispatch_get_main_queue()) {
self.centerMapOnCurrentUser()
}
}
// center on the default location previously entered by user, if available
func centerMapOnCurrentUser() {
if let currentUserLocations = self.dataManager?.userLocations
where currentUserLocations.count > 0 {
let firstLocation = currentUserLocations[0]
if let latitude = firstLocation.latitude,
longitude = firstLocation.longitude {
let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
let distance = Constants.MapSpanDistanceMeters
let region = MKCoordinateRegionMakeWithDistance(coordinate, distance, distance)
self.mapView.setRegion(region, animated: true)
}
}
}
}
// MARK: - MKMapViewDelegate
extension StudentMapViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.StudentLocationAnnotationReuseIdentifier)
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.StudentLocationAnnotationReuseIdentifier)
view?.canShowCallout = true
} else {
view?.annotation = annotation
}
if let studentAnnotation = annotation as? StudentAnnotation {
if let urlString = studentAnnotation.student.mediaUrl,
_ = NSURL(string: urlString) {
let detailButton = UIButton(type: UIButtonType.DetailDisclosure)
_ = UIImageView(image: detailButton.imageForState(UIControlState.Highlighted))
view?.rightCalloutAccessoryView = detailButton
}
}
return view
}
// open the URL for the tapped Student Location pin if it is valid
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
// TODO: verify URL and network connectivity before sending to Safari
if let studentAnnotation = view.annotation as? StudentAnnotation,
urlString = studentAnnotation.student.mediaUrl {
self.sendToUrlString(urlString)
}
}
}
// MARK: - Extension StudentLocation, MKAnnotation
// StudentAnnotation
// wrap StudentInformation with Annotation for display on map
class StudentAnnotation: NSObject, MKAnnotation {
let student: StudentInformation
init?(student: StudentInformation) {
self.student = student
super.init()
if student.latitude == nil || student.longitude == nil {
return nil
}
}
@objc var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: CLLocationDegrees(student.latitude!), longitude: CLLocationDegrees(student.longitude!))
}
var title: String? {
return student.fullname
}
var subtitle: String? {
return student.mediaUrl
}
}
| f752f81f3adbe676f6fe32ea110f97c8 | 36.240741 | 143 | 0.650091 | false | false | false | false |
alexjohnj/gyoutube-dl | refs/heads/master | gyoutube-dl/DownloadViewController.swift | mit | 1 | //
// DownloadViewController.swift
// gyoutube-dl
//
// Created by Alex Jackson on 16/08/2015.
// Copyright © 2015 Alex Jackson. All rights reserved.
//
import Cocoa
class DownloadViewController: NSViewController {
var videoLinks: [URL]?
var downloadOperation: VideoDownloadOperation?
// MARK: Outlets
@IBOutlet weak var statusField: NSTextField!
@IBOutlet weak var videoTitleField: NSTextField!
@IBOutlet weak var progressBar: NSProgressIndicator!
@IBOutlet weak var cancelCloseButton: NSButton!
// MARK: Object Life Cycle
deinit {
guard downloadOperation != nil else {
return
}
downloadOperation!.removeObserver(self, forKeyPath: "isExecuting")
downloadOperation!.removeObserver(self, forKeyPath: "isFinished")
downloadOperation!.removeObserver(self, forKeyPath: "currentTitleProgress")
downloadOperation!.removeObserver(self, forKeyPath: "currentTitle")
downloadOperation!.removeObserver(self, forKeyPath: "currentVideoIndex")
}
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
progressBar.maxValue = 1.0
progressBar.minValue = 0
}
override func viewDidAppear() {
super.viewDidAppear()
guard let videoLinks = videoLinks else {
print("Nil links provided to DownloadViewController (in viewDidAppear())")
return
}
downloadOperation = VideoDownloadOperation(videoLinks: videoLinks)
downloadOperation!.addObserver(self, forKeyPath: "isExecuting", options: .new, context: nil)
downloadOperation!.addObserver(self, forKeyPath: "isFinished", options: .new, context: nil)
downloadOperation!.addObserver(self, forKeyPath: "currentTitleProgress", options: .new, context: nil)
downloadOperation!.addObserver(self, forKeyPath: "currentTitle", options: .new, context: nil)
downloadOperation!.addObserver(self, forKeyPath: "currentVideoIndex", options: .new, context: nil)
downloadOperation!.start()
}
@IBAction func cancelDownloadOperation(_ sender: AnyObject) {
defer {
dismiss(self)
}
guard let downloadOperation = downloadOperation else {
return
}
if downloadOperation.isFinished {
return
}
downloadOperation.cancel()
}
// MARK: KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else { return }
guard let change = change else { return }
guard let newValue = change[.newKey] else { return }
switch keyPath {
case "isExecuting":
if newValue as! Bool == true {
progressBar.startAnimation(self)
}
case "isFinished":
if newValue as! Bool == true {
progressBar.stopAnimation(self)
cancelCloseButton.title = "Close"
}
print("Finished downloading")
case "currentTitleProgress":
let currentProgress = newValue as! Double
progressBar.doubleValue = currentProgress
case "currentTitle":
let currentTitle = newValue as! String
videoTitleField.stringValue = currentTitle
case "currentVideoIndex":
let currentVideoIndex = newValue as! Int
statusField.stringValue = "Downloading \(currentVideoIndex) of \(videoLinks!.count)"
default:
break
}
}
}
| 2512bf3a0a5e0f011539146b6dcf6687 | 35.107843 | 151 | 0.638067 | false | false | false | false |
ijaureguialzo/GooglePlacesRow | refs/heads/master | Sources/GooglePlacesTableCell.swift | mit | 1 | //
// GooglePlacesTableCell.swift
// GooglePlacesRow
//
// Created by Mathias Claassen on 4/14/16.
//
//
import Foundation
import UIKit
open class GooglePlacesTableCell<TableViewCell: UITableViewCell>: GooglePlacesCell, UITableViewDelegate, UITableViewDataSource where TableViewCell: EurekaGooglePlacesTableViewCell {
/// callback that can be used to cuustomize the appearance of the UICollectionViewCell in the inputAccessoryView
public var customizeTableViewCell: ((TableViewCell) -> Void)?
/// UICollectionView that acts as inputAccessoryView.
public var tableView: UITableView?
/// Maximum number of candidates to be shown
public var numberOfCandidates: Int = 5
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
tableView = UITableView(frame: CGRect.zero, style: .plain)
tableView?.autoresizingMask = .flexibleHeight
tableView?.isHidden = true
tableView?.delegate = self
tableView?.dataSource = self
tableView?.backgroundColor = UIColor.white
tableView?.register(TableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
}
open func showTableView() {
if let controller = formViewController() {
if tableView?.superview == nil {
controller.view.addSubview(tableView!)
}
let frame = controller.tableView?.convert(self.frame, to: controller.view) ?? self.frame
tableView?.frame = CGRect(x: 0, y: frame.origin.y + frame.height, width: contentView.frame.width, height: 44 * CGFloat(numberOfCandidates))
tableView?.isHidden = false
}
}
open func hideTableView() {
tableView?.isHidden = true
}
override func reload() {
tableView?.reloadData()
}
open override func textFieldDidChange(_ textField: UITextField) {
super.textFieldDidChange(textField)
if textField.text?.isEmpty == false {
showTableView()
}
}
open override func textFieldDidEndEditing(_ textField: UITextField) {
super.textFieldDidEndEditing(textField)
hideTableView()
}
//MARK: UITableViewDelegate and Datasource
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return predictions?.count ?? 0
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TableViewCell
if let prediction = predictions?[(indexPath as NSIndexPath).row] {
cell.setTitle(prediction)
}
customizeTableViewCell?(cell)
return cell
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let prediction = predictions?[(indexPath as NSIndexPath).row] {
row.value = GooglePlace.prediction(prediction: prediction)
_ = cellResignFirstResponder()
}
}
open func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
}
| faf1e740f47f5f91898b257d8781b083 | 33.818182 | 181 | 0.665506 | false | false | false | false |
cplaverty/KeitaiWaniKani | refs/heads/master | WaniKaniKit/Derived/SubjectProgression.swift | mit | 1 | //
// SubjectProgression.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
public struct SubjectProgression {
public let subjectID: Int
public let subject: Subject
public let assignment: Assignment?
public let percentComplete: Float
private let earliestGuruDate: Date?
private let earliestBurnDate: Date?
public var isLocked: Bool {
return assignment == nil || assignment!.srsStage == 0
}
public var isPassed: Bool {
return assignment?.isPassed ?? false
}
public var availableAt: NextReviewTime {
return NextReviewTime(date: assignment?.availableAt)
}
public var guruTime: NextReviewTime {
return NextReviewTime(date: earliestGuruDate)
}
public var burnTime: NextReviewTime {
return NextReviewTime(date: earliestBurnDate)
}
public init(subjectID: Int, subject: Subject, assignment: Assignment?, getAssignmentForSubjectID: (Int) -> Assignment?) {
self.subjectID = subjectID
self.subject = subject
self.assignment = assignment
self.earliestGuruDate = subject.earliestGuruDate(assignment: assignment, getAssignmentForSubjectID: getAssignmentForSubjectID)
self.earliestBurnDate = subject.earliestBurnDate(assignment: assignment, getAssignmentForSubjectID: getAssignmentForSubjectID)
self.percentComplete = min(Float(assignment?.srsStage ?? 0) / Float(SRSStage.guru.numericLevelRange.lowerBound), 1.0)
}
}
| 822ac6270ab376c762f4584e48b54966 | 33.066667 | 134 | 0.700587 | false | false | false | false |
modum-io/ios_client | refs/heads/master | PharmaSupplyChain/SettingsViewController.swift | apache-2.0 | 1 | //
// SettingsTableViewController.swift
// PharmaSupplyChain
//
// Created by Yury Belevskiy on 09.03.17.
// Copyright © 2017 Modum. All rights reserved.
//
import UIKit
import AMPopTip
import Spring
class SettingsViewController : UIViewController {
// MARK: Properties
fileprivate var companyDefaults: CompanyDefaults?
fileprivate var currentTipView: AMPopTip?
// MARK: Outlets
@IBOutlet weak fileprivate var infoView: UIView!
@IBOutlet weak fileprivate var usernameLabel: UILabel!
@IBOutlet weak fileprivate var companyNameLabel: UILabel!
@IBOutlet weak fileprivate var modeInfoButton: UIButton!
@IBOutlet weak fileprivate var modeView: UIView!
@IBOutlet weak fileprivate var modeLabel: UILabel!
@IBOutlet weak fileprivate var modeSwitchButton: UIButton!
@IBOutlet weak fileprivate var logoutView: UIView!
// MARK: Actions
@IBAction fileprivate func modeInfoIconTouchUpInside(_ sender: UIButton) {
if let currentTipView = currentTipView {
currentTipView.hide()
self.currentTipView = nil
return
} else {
let tipView = AMPopTip()
tipView.shouldDismissOnTap = true
tipView.popoverColor = UIColor.white.withAlphaComponent(0.7)
tipView.dismissHandler = {
[weak self] in
if let settingsViewController = self {
settingsViewController.currentTipView = nil
settingsViewController.modeSwitchButton.layer.removeAllAnimations()
}
}
let attributedTipText = NSAttributedString(string: "Set operation mode to \"Sender\" to be able to send parcels or set operation mode to \"Receiver\" to receive parcels", attributes: [NSFontAttributeName : UIFont(name: "OpenSans-Light", size: 14.0)!])
tipView.showAttributedText(attributedTipText, direction: .up, maxWidth: 300.0, in: view, fromFrame: modeView.frame)
currentTipView = tipView
/* add animation to mode switch button */
let colorAnimation = CABasicAnimation(keyPath: "opacity")
colorAnimation.fromValue = 1.0
colorAnimation.toValue = 0.0
colorAnimation.duration = 1
colorAnimation.autoreverses = true
colorAnimation.repeatCount = Float.greatestFiniteMagnitude
modeSwitchButton.layer.add(colorAnimation, forKey: "animateOpacity")
}
}
@IBAction fileprivate func modeSwitchButtonTouchUpInside(_ sender: UIButton) {
sender.layer.removeAllAnimations()
if let currentTipView = currentTipView {
currentTipView.hide()
self.currentTipView = nil
}
if let springButton = sender as? SpringButton {
let isSenderMode = UserDefaults.standard.bool(forKey: "isSenderMode")
UserDefaults.standard.set(!isSenderMode, forKey: "isSenderMode")
let timer = Timer(timeInterval: 0.7, repeats: false, block: {
[weak self]
timer in
timer.invalidate()
if let settingsController = self {
if isSenderMode {
settingsController.modeLabel.text = "Receiver Mode"
} else {
settingsController.modeLabel.text = "Sender Mode"
}
}
})
RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
springButton.animation = "pop"
springButton.curve = "easeInSine"
springButton.force = 1.0
springButton.velocity = 0.7
springButton.duration = 1.0
springButton.animate()
}
}
@IBAction fileprivate func logoutButtonTouchUpInside(_ sender: UIButton) {
LoginManager.shared.clear()
if let loginViewController = storyboard!.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController {
present(loginViewController, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
/* adding gradient background */
let leftColor = TEMPERATURE_LIGHT_BLUE.cgColor
let middleColor = ROSE_COLOR.cgColor
let rightColor = LIGHT_BLUE_COLOR.cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
gradientLayer.colors = [leftColor, middleColor, rightColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
view.layer.insertSublayer(gradientLayer, at: 0)
infoView.layer.cornerRadius = 10.0
modeView.layer.cornerRadius = 10.0
logoutView.layer.cornerRadius = 10.0
/* navigation bar configuration */
navigationItem.title = "Settings"
if let openSansFont = UIFont(name: "OpenSans-Light", size: 20.0) {
navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : openSansFont]
}
if let navigationController = navigationController {
navigationController.navigationBar.tintColor = UIColor.black
}
/* filling the content */
let currentMode = UserDefaults.standard.bool(forKey: "isSenderMode")
if currentMode {
modeLabel.text = "Sender Mode"
} else {
modeLabel.text = "Receiver Mode"
}
usernameLabel.text = LoginManager.shared.getUsername() ?? "-"
companyNameLabel.text = LoginManager.shared.getCompanyName() ?? "-"
}
}
| 830d41290548086a44fdfe7bf547f636 | 38.304054 | 263 | 0.619048 | false | false | false | false |
bravelocation/yeltzland-ios | refs/heads/main | yeltzland/Models/TeamMapMarker.swift | mit | 1 | //
// TeamMapMarker.swift
// Yeltzland
//
// Created by John Pollard on 18/06/2022.
// Copyright © 2022 John Pollard. All rights reserved.
//
import Foundation
import MapKit
struct TeamMapMarker: Identifiable {
let id = UUID()
let team: String
let coordinate: CLLocationCoordinate2D
init(location: Location) {
self.team = location.team
self.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
}
init (team: String, coordinate: CLLocationCoordinate2D) {
self.team = team
self.coordinate = coordinate
}
}
| c9210158f512b6d1b1a52f04f92db4b1 | 22.259259 | 108 | 0.671975 | false | false | false | false |
annatovstyga/REA-Schedule | refs/heads/master | Raspisaniye/kConstant.swift | mit | 1 | //
// kConstant.swift
// SideMenuSwiftDemo
//
// Created by Kiran Patel on 1/2/16.Mod by Ivan Gulakov.
// Copyright © 2016 SOTSYS175. All rights reserved.
//
import Foundation
import UIKit
let sideMenuVC = KSideMenuVC()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
class kConstant {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
func SetIntialMainViewController(_ aStoryBoardID: String)->(KSideMenuVC){
let sideMenuObj = mainStoryboard.instantiateViewController(withIdentifier: "leftMenu")
let mainVcObj = mainStoryboard.instantiateViewController(withIdentifier: aStoryBoardID)
let navigationController : UINavigationController = UINavigationController(rootViewController: mainVcObj)
navigationController.isNavigationBarHidden = true
sideMenuVC.view.frame = UIScreen.main.bounds
sideMenuVC.RGsetMainViewController(navigationController)
sideMenuVC.RGsetMenuViewController(sideMenuObj)
return sideMenuVC
}
func SetMainViewController(_ aStoryBoardID: String)->(KSideMenuVC){
let mainVcObj = mainStoryboard.instantiateViewController(withIdentifier: aStoryBoardID)
let navigationController : UINavigationController = UINavigationController(rootViewController: mainVcObj)
navigationController.isNavigationBarHidden = true
sideMenuVC.view.frame = UIScreen.main.bounds
sideMenuVC.RGsetMainViewController(navigationController)
return sideMenuVC
}
}
| 81279bd8ceb18403dc4ea9be7667068f | 41.194444 | 113 | 0.761685 | false | false | false | false |
rzrasel/iOS-Swift | refs/heads/master | SwiftUIPageViewControllerOne/SwiftUIPageViewControllerOne/ViewController.swift | apache-2.0 | 2 | //
// ViewController.swift
// SwiftUIPageViewControllerOne
//
// Created by NextDot on 2/14/16.
// Copyright © 2016 RzRasel. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPageViewControllerDataSource {
//|------------------------------------|
var pageImages: NSArray!
var pageViewController: UIPageViewController!
//|------------------------------------|
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pageImages = NSArray(objects: "image_001", "image_002", "image_003", "image_004")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("RzPageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let initialContentViewController = self.pageContentHolderAtIndex(0) as UvcPageContentHolder
let viewControllers = NSArray(object: initialContentViewController)
//var pageViewController.se = NSArray(object: initialContentViewController as [AnyObject], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
@IBAction func sysOnClickBarItemNext(sender: AnyObject) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewControllerWithIdentifier("UvcTheNext") as! UvcTheNext
//self.presentViewController(viewController, animated: true, completion: nil);
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewController = viewController
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func pageContentHolderAtIndex(index: Int) -> UvcPageContentHolder
{
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UvcPageContentHolder") as! UvcPageContentHolder
pageContentViewController.imageFileName = pageImages[index] as! String
pageContentViewController.pageIndex = index
return pageContentViewController
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?
{
let viewController = viewController as! UvcPageContentHolder
var index = viewController.pageIndex as Int
if(index == 0 || index == NSNotFound)
{
return nil
}
index--
return self.pageContentHolderAtIndex(index)
/*if let controller = viewController as? UvcPageContentHolder {
if controller.itemIndex > 0 {
return controllers[controller.itemIndex - 1]
}
}
return nil*/
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?
{
let viewController = viewController as! UvcPageContentHolder
var index = viewController.pageIndex as Int
if(index == NSNotFound)
{
return nil
}
index++
if(index == pageImages.count)
{
return nil
}
return self.pageContentHolderAtIndex(index)
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int
{
return pageImages.count
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int
{
return 0
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
} | 4c22d64fb22a0aff57cbd044fbb7cc73 | 44.70297 | 191 | 0.639003 | false | false | false | false |
OneupNetwork/SQRichTextEditor | refs/heads/master | Example/SQRichTextEditor/EFColorPicker/EFSliderView.swift | mit | 1 | //
// EFSliderView.swift
// EFColorPicker
//
// Created by EyreFree on 2017/9/28.
//
// Copyright (c) 2017 EyreFree <[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 Foundation
import CoreGraphics
import QuartzCore
import UIKit
public class EFSliderView: EFControl {
let EFSliderViewHeight: CGFloat = 28.0
let EFSliderViewMinWidth: CGFloat = 150.0
let EFSliderViewTrackHeight: CGFloat = 6.0
let EFThumbViewEdgeInset: CGFloat = -10.0
private let thumbView: EFThumbView = EFThumbView()
private let trackLayer: CAGradientLayer = CAGradientLayer()
// The slider's current value. The default value is 0.0.
private(set) var value: CGFloat = 0
// The minimum value of the slider. The default value is 0.0.
var minimumValue: CGFloat = 0
// The maximum value of the slider. The default value is 1.0.
var maximumValue: CGFloat = 1
// Indicates if the user touches the control at the moment
var isTouched = false
override init(frame: CGRect) {
super.init(frame: frame)
self.accessibilityLabel = "color_slider"
minimumValue = 0.0
maximumValue = 1.0
value = 0.0
self.layer.delegate = self
trackLayer.cornerRadius = EFSliderViewTrackHeight / 2.0
trackLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
trackLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
self.layer.addSublayer(trackLayer)
thumbView.hitTestEdgeInsets = UIEdgeInsets(
top: EFThumbViewEdgeInset, left: EFThumbViewEdgeInset,
bottom: EFThumbViewEdgeInset, right: EFThumbViewEdgeInset
)
thumbView.gestureRecognizer.addTarget(self, action: #selector(ef_didPanThumbView(gestureRecognizer:)))
self.addSubview(thumbView)
let color = UIColor.blue
self.setColors(colors: [color, color])
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open class var requiresConstraintBasedLayout: Bool {
get {
return true
}
}
override public var intrinsicContentSize: CGSize {
get {
return CGSize(width: EFSliderViewMinWidth, height: EFSliderViewHeight)
}
}
func setValue(value: CGFloat) {
if (value < minimumValue) {
self.value = minimumValue
} else if (value > maximumValue) {
self.value = maximumValue
} else {
self.value = value
}
self.ef_updateThumbPositionWithValue(value: self.value)
}
// Sets the array of CGColorRef objects defining the color of each gradient stop on the track.
// The location of each gradient stop is evaluated with formula: i * width_of_the_track / number_of_colors.
// @param colors An array of CGColorRef objects.
func setColors(colors: [UIColor]) {
let cgColors = colors.map { color -> CGColor in
return color.cgColor
}
if cgColors.count <= 1 {
fatalError("‘colors: [CGColor]’ at least need to have 2 elements")
}
trackLayer.colors = cgColors
self.ef_updateLocations()
}
override public func layoutSubviews() {
self.ef_updateThumbPositionWithValue(value: self.value)
self.ef_updateTrackLayer()
}
// MARK:- UIControl touch tracking events
@objc func ef_didPanThumbView(gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizer.State.ended {
self.isTouched = false
} else if gestureRecognizer.state == UIGestureRecognizer.State.began {
self.isTouched = true
}
if gestureRecognizer.state != UIGestureRecognizer.State.began
&& gestureRecognizer.state != UIGestureRecognizer.State.changed {
return
}
let translation = gestureRecognizer.translation(in: self)
gestureRecognizer.setTranslation(CGPoint.zero, in: self)
self.ef_setValueWithTranslation(translation: translation.x)
}
func ef_updateTrackLayer() {
let height: CGFloat = EFSliderViewHeight
let width: CGFloat = self.bounds.width
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
trackLayer.bounds = CGRect(x: 0, y: 0, width: width, height: EFSliderViewTrackHeight)
trackLayer.position = CGPoint(x: self.bounds.width / 2, y: height / 2)
CATransaction.commit()
}
// MARK:- Private methods
private func ef_setValueWithTranslation(translation: CGFloat) {
let width: CGFloat = self.bounds.width - thumbView.bounds.width
let valueRange: CGFloat = maximumValue - minimumValue
let value: CGFloat = self.value + valueRange * translation / width
self.setValue(value: value)
self.sendActions(for: UIControl.Event.valueChanged)
}
private func ef_updateLocations() {
let size: Int = trackLayer.colors?.count ?? 2
if size == trackLayer.locations?.count {
return
}
let step: CGFloat = 1.0 / (CGFloat(size) - 1)
var locations: [NSNumber] = [0]
var i: Int = 1
while i < size - 1 {
locations.append(NSNumber(value: Double(CGFloat(i) * step)))
i += 1
}
locations.append(1.0)
trackLayer.locations = locations
}
private func ef_updateThumbPositionWithValue(value: CGFloat) {
let thumbWidth: CGFloat = thumbView.bounds.width
let thumbHeight: CGFloat = thumbView.bounds.height
let width: CGFloat = self.bounds.width - thumbWidth
if width == 0 {
return
}
let percentage: CGFloat = (value - minimumValue) / (maximumValue - minimumValue)
let position: CGFloat = width * percentage
thumbView.frame = CGRect(x: position, y: 0, width: thumbWidth, height: thumbHeight)
}
}
| a40b24090a85adc368e4497220646d4e | 34.27 | 111 | 0.662461 | false | false | false | false |
BoomTownROI/SSASideMenu | refs/heads/master | SSASideMenuExample/SSASideMenuExample/RightMenuViewController.swift | mit | 1 | //
// RightMenuViewController.swift
// SSASideMenuExample
//
// Created by Sebastian S. Andersen on 06/03/15.
// Copyright (c) 2015 SebastianAndersen. All rights reserved.
//
import Foundation
import UIKit
import SSASideMenu
class RightMenuViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(180, (self.view.frame.size.height - 54 * 2) / 2.0, self.view.frame.size.width, 54 * 2)
tableView.autoresizingMask = .FlexibleTopMargin | .FlexibleBottomMargin | .FlexibleWidth
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
return tableView
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension RightMenuViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let titles: [String] = ["Home", "Calendar"]
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
sideMenuViewController?.contentViewController = UINavigationController(rootViewController: FirstViewController())
sideMenuViewController?.hideMenuViewController()
break
case 1:
sideMenuViewController?.contentViewController = UINavigationController(rootViewController: SecondViewController())
sideMenuViewController?.hideMenuViewController()
break
default:
break
}
}
}
| d61b3eb89d938726f7bb46cb86f34708 | 29.403846 | 126 | 0.648845 | false | false | false | false |
tkremenek/swift | refs/heads/master | test/Interop/Cxx/operators/non-member-inline-typechecker.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-cxx-interop
import NonMemberInline
var lhs = LoadableIntWrapper(value: 42)
var rhs = LoadableIntWrapper(value: 23)
let resultPlus = lhs + rhs
let resultMinus = lhs - rhs
let resultStar = lhs * rhs
let resultSlash = lhs / rhs
let resultPercent = lhs % rhs
let resultAmp = lhs & rhs
let resultPipe = lhs | rhs
let resultLessLess = lhs << rhs
let resultGreaterGreater = lhs >> rhs
let resultLess = lhs < rhs
let resultGreater = lhs > rhs
let resultEqualEqual = lhs == rhs
let resultExclaimEqual = lhs != rhs
let resultLessEqual = lhs <= rhs
let resultGreaterEqual = lhs >= rhs
var lhsBool = LoadableBoolWrapper(value: true)
var rhsBool = LoadableBoolWrapper(value: false)
let resultAmpAmp = lhsBool && rhsBool
let resultPipePipe = lhsBool && rhsBool
| 5b01ac5b101edd971832c9857bd14c29 | 28 | 71 | 0.746305 | false | false | false | false |
azimin/Rainbow | refs/heads/master | Rainbow/ColorDifference.swift | mit | 1 | //
// ColorDifference.swift
// Rainbow
//
// Created by Alex Zimin on 20/03/16.
// Copyright © 2016 Alex Zimin. All rights reserved.
//
// Thanks to Indragie Karunaratne ( https://github.com/indragiek )
import GLKit.GLKMath
internal protocol ColorDifference {
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float
}
internal struct CIE76SquaredColorDifference: ColorDifference {
// From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE76.html
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float {
return CIE76SquaredColorDifferenceFunction(lab1.toVector(), lab2: lab2.toVector())
}
}
internal func CIE76SquaredColorDifferenceFunction(lab1: Vector3D, lab2: Vector3D) -> Float {
let (L1, a1, b1) = lab1.toFloatTuple()
let (L2, a2, b2) = lab2.toFloatTuple()
return pow(L2 - L1, 2) + pow(a2 - a1, 2) + pow(b2 - b1, 2)
}
internal struct CIE94SquaredColorDifference: ColorDifference {
private(set) var kL: Float
private(set) var kC: Float
private(set) var kH: Float
private(set) var K1: Float
private(set) var K2: Float
init(kL: Float = 1, kC: Float = 1, kH: Float = 1, K1: Float = 0.045, K2: Float = 0.015) {
self.kL = kL
self.kC = kC
self.kH = kH
self.K1 = K1
self.K2 = K2
}
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float {
return CIE94SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, K1: K1, K2: K2, lab1: lab1, lab2: lab2)
}
}
// From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html
// Created for optimization
internal func CIE94SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, K1: Float = 0.045, K2: Float = 0.015, lab1: LABColor, lab2: LABColor) -> Float {
return CIE94SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, K1: K1, K2: K2, lab1: lab1.toVector(), lab2: lab1.toVector())
}
internal func CIE94SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, K1: Float = 0.045, K2: Float = 0.015, lab1: Vector3D, lab2: Vector3D) -> Float {
let (L1, a1, b1) = lab1.toFloatTuple()
let (L2, a2, b2) = lab2.toFloatTuple()
let ΔL = L1 - L2
let (C1, C2) = (C(a1, b: b1), C(a2, b: b2))
let ΔC = C1 - C2
let ΔH = sqrt(pow(a1 - a2, 2) + pow(b1 - b2, 2) - pow(ΔC, 2))
let Sl: Float = 1
let Sc = 1 + K1 * C1
let Sh = 1 + K2 * C1
return pow(ΔL / (kL * Sl), 2) + pow(ΔC / (kC * Sc), 2) + pow(ΔH / (kH * Sh), 2)
}
internal struct CIE2000SquaredColorDifference: ColorDifference {
private(set) var kL: Float
private(set) var kC: Float
private(set) var kH: Float
init(kL: Float = 1, kC: Float = 1, kH: Float = 1) {
self.kL = kL
self.kC = kC
self.kH = kH
}
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float {
return CIE2000SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, lab1: lab1, lab2: lab2)
}
}
// From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE2000.html
// Created for optimization
internal func CIE2000SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, lab1: LABColor, lab2: LABColor) -> Float {
return CIE2000SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, lab1: lab1.toVector(), lab2: lab2.toVector())
}
internal func CIE2000SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, lab1: Vector3D, lab2: Vector3D) -> Float {
let (L1, a1, b1) = lab1.toFloatTuple()
let (L2, a2, b2) = lab2.toFloatTuple()
let ΔLp = L2 - L1
let Lbp = (L1 + L2) / 2
let (C1, C2) = (C(a1, b: b1), C(a2, b: b2))
let Cb = (C1 + C2) / 2
let G = (1 - sqrt(pow(Cb, 7) / (pow(Cb, 7) + pow(25, 7)))) / 2
let ap: Float -> Float = { a in
return a * (1 + G)
}
let (a1p, a2p) = (ap(a1), ap(a2))
let (C1p, C2p) = (C(a1p, b: b1), C(a2p, b: b2))
let ΔCp = C2p - C1p
let Cbp = (C1p + C2p) / 2
let hp: (Float, Float) -> Float = { ap, b in
if ap == 0 && b == 0 { return 0 }
let θ = GLKMathRadiansToDegrees(atan2(b, ap))
return fmod(θ < 0 ? (θ + 360) : θ, 360)
}
let (h1p, h2p) = (hp(a1p, b1), hp(a2p, b2))
let Δhabs = abs(h1p - h2p)
let Δhp: Float = {
if (C1p == 0 || C2p == 0) {
return 0
} else if Δhabs <= 180 {
return h2p - h1p
} else if h2p <= h1p {
return h2p - h1p + 360
} else {
return h2p - h1p - 360
}
}()
let ΔHp = 2 * sqrt(C1p * C2p) * sin(GLKMathDegreesToRadians(Δhp / 2))
let Hbp: Float = {
if (C1p == 0 || C2p == 0) {
return h1p + h2p
} else if Δhabs > 180 {
return (h1p + h2p + 360) / 2
} else {
return (h1p + h2p) / 2
}
}()
var T = 1 - 0.17 * cos(GLKMathDegreesToRadians(Hbp - 30))
T += 0.24 * cos(GLKMathDegreesToRadians(2 * Hbp))
T += 0.32 * cos(GLKMathDegreesToRadians(3 * Hbp + 6))
T -= 0.20 * cos(GLKMathDegreesToRadians(4 * Hbp - 63))
let Sl = 1 + (0.015 * pow(Lbp - 50, 2)) / sqrt(20 + pow(Lbp - 50, 2))
let Sc = 1 + 0.045 * Cbp
let Sh = 1 + 0.015 * Cbp * T
let Δθ = 30 * exp(-pow((Hbp - 275) / 25, 2))
let Rc = 2 * sqrt(pow(Cbp, 7) / (pow(Cbp, 7) + pow(25, 7)))
let Rt = -Rc * sin(GLKMathDegreesToRadians(2 * Δθ))
let Lterm = ΔLp / (kL * Sl)
let Cterm = ΔCp / (kC * Sc)
let Hterm = ΔHp / (kH * Sh)
return pow(Lterm, 2) + pow(Cterm, 2) + pow(Hterm, 2) + Rt * Cterm * Hterm
}
| 80d16e1e72fd57867f5d549515d89669 | 30.164706 | 175 | 0.605512 | false | false | false | false |
xiaomudegithub/viossvc | refs/heads/master | viossvc/AppAPI/SocketAPI/SocketConst.swift | apache-2.0 | 1 | //
// SockOpcode.swift
// viossvc
//
// Created by yaowang on 2016/11/22.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import Foundation
class SocketConst: NSObject {
enum OPCode:UInt16 {
// 心跳包
case Heart = 1000
// 请求登录
case Login = 1001
//验证手机短信
case SMSVerify = 1019
//验证手机验证码
case VerifyCode = 1101
//注册
case Register = 1021
//重置密码
case NodifyPasswrod = 1011
//修改用户信息
case NodifyUserInfo = 1023
//获取图片token
case GetImageToken = 1047
//获取用户余额
case UserCash = 1067
//认证用户头像
case AuthUserHeader = 1091
//获取用户的银行卡信息
case UserBankCards = 1097
//校验提现密码
case CheckDrawCashPassword = 1087
//提现
case DrawCash = 1103
//提现详情
case DrawCashDetail = 0004
//提现记录
case DrawCashRecord = 1105
//设置默认银行卡
case DefaultBankCard = 1099
//添加新的银行卡
case NewBankCard = 1095
//获取所有技能标签
case AllSkills = 1041
//获取身份认证进度
case AuthStatus = 1057
//上传身份认证信息
case AuthUser = 1055
//设置/修改支付密码
case DrawCashPassword = 1089
//V领队服务
case ServiceList = 1501
//更新V领队服务
case UpdateServiceList = 1503
//技能分享列表
case SkillShareList = 1071
//技能分享详情
case SkillShareDetail = 1073
//技能分享评论列表
case SkillShareComment = 1075
//技能分享预约
case SkillShareEnroll = 1077
/**
订单列表
*/
case OrderList = 1505
//订单详情
case OrderDetail = 1507
/**
操作技能标签
*/
case HandleSkills = 1509
//商务分享类别
case TourShareType = 1059
//商务分享列表
case TourShareList = 1061
//商务分享详情
case TourShareDetail = 1065
//上传照片到照片墙
case UploadPhoto2Wall = 1107
//获取照片墙
case PhotoWall = 1109
/**
修改订单状态
*/
case ModfyOrderStatus = 2011
case LoginRet = 1002
case UserInfo = 1013
//发送chat消息
case ChatSendMessage = 2003
//收到chat消息
case ChatReceiveMessage = 2004
//获取chat离线消息
case ChatOfflineRequestMessage = 2025
case ChatOfflineReceiveMessage = 2006
case UpdateDeviceToken = 1031
}
enum type:UInt8 {
case Error = 0
case User = 1
case Chat = 2
}
class Key {
static let last_id = "last_id_"
static let count = "count_"
static let share_id = "share_id_"
static let page_type = "page_type_"
static let uid = "uid_"
static let from_uid = "from_uid_"
static let to_uid = "to_uid_"
static let order_id = "order_id_"
static let order_status = "order_status_"
static let change_type = "change_type_"
static let skills = "skills_"
}
}
| cdf610dca18b003f42c00fd34a21f67a | 23.354839 | 59 | 0.526821 | false | false | false | false |
apple/swift-numerics | refs/heads/main | Sources/_TestSupport/RealTestSupport.swift | apache-2.0 | 1 | //===--- RealTestSupport.swift --------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import RealModule
public protocol FixedWidthFloatingPoint: BinaryFloatingPoint
where Exponent: FixedWidthInteger,
RawSignificand: FixedWidthInteger { }
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, watchOS 14.0, tvOS 7.0, *)
extension Float16: FixedWidthFloatingPoint { }
#endif
extension Float: FixedWidthFloatingPoint { }
extension Double: FixedWidthFloatingPoint { }
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
extension Float80: FixedWidthFloatingPoint { }
#endif
extension FloatingPointSign {
static func random<G: RandomNumberGenerator>(using g: inout G) -> FloatingPointSign {
[.plus,.minus].randomElement(using: &g)!
}
}
| dd043cd3243031cc65d590189ea6191e | 34.636364 | 87 | 0.664116 | false | false | false | false |
tapglue/ios_sdk | refs/heads/master | Sources/Internal/UserStore.swift | apache-2.0 | 2 | //
// UserStore.swift
// Tapglue
//
// Created by John Nilsen on 7/20/16.
// Copyright © 2016 Tapglue. All rights reserved.
//
import Foundation
class UserStore {
static let tapglueDefaults = "tapglueDefaults"
static let currentUserTag = "currentUser"
var user: User? {
get {
let userDictionary = UserDefaults(suiteName: UserStore.tapglueDefaults)?.dictionary(forKey: UserStore.currentUserTag)
if let userDictionary = userDictionary {
return User(JSON: userDictionary)
}
return nil
}
set {
if let user = newValue {
UserDefaults(suiteName: UserStore.tapglueDefaults)?.set(user.toJSON(), forKey: UserStore.currentUserTag)
} else {
// NSUserDefaults(suiteName: UserStore.tapglueDefaults)?
// .setObject(nil, forKey: UserStore.currentUserTag)
UserDefaults(suiteName: UserStore.tapglueDefaults)?
.removeObject(forKey: UserStore.currentUserTag)
}
}
}
}
| 5273774785d9ecebed1530bc07fbe8a8 | 30.166667 | 129 | 0.585561 | false | false | false | false |
dasdom/Poster | refs/heads/master | ADN/ImageService.swift | mit | 1 | //
// ImageService.swift
// Jupp
//
// Created by dasdom on 05.12.14.
// Copyright (c) 2014 Dominik Hauser. All rights reserved.
//
import Cocoa
public class ImageService: NSObject {
public func saveImageToUpload(image: NSImage, name: String) -> NSURL? {
return saveImage(image, name: name, imageUrl: imagesToUploadDirectoryURL())
}
public func saveImage(image: NSImage, name: String, imageUrl: NSURL) -> NSURL? {
var imageDirectoryURL = imageUrl
imageDirectoryURL = imageDirectoryURL.URLByAppendingPathComponent(name)
imageDirectoryURL = imageDirectoryURL.URLByAppendingPathExtension("jpg")
if let imageData = image.jpegDataWithCompressionFactor(0.5) {
let saved = imageData.writeToFile(imageDirectoryURL.path!, atomically: true)
return imageDirectoryURL
}
return nil
}
private func imagesToUploadDirectoryURL() -> NSURL {
return urlForDirectoryWithName("Uploads")
}
private func urlForDirectoryWithName(name: String) -> NSURL! {
if let containerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.de.dasdom.Jupp") {
var contairURLWithName = containerURL.URLByAppendingPathComponent(name)
if !NSFileManager.defaultManager().fileExistsAtPath(contairURLWithName.path!) {
NSFileManager.defaultManager().createDirectoryAtPath(containerURL.path!, withIntermediateDirectories: false, attributes: nil, error: nil)
}
return containerURL } else {
fatalError("Unable to obtain container URL for app group, verify your app group settings.")
return nil
}
}
}
| c0b765b438f3ed791cedbd2ab0dc35f1 | 36.045455 | 145 | 0.733742 | false | false | false | false |
tadija/AEImage | refs/heads/master | Sources/AEImage/ImageScrollView.swift | mit | 1 | /**
* https://github.com/tadija/AEImage
* Copyright © 2016-2019 Marko Tadić
* Licensed under the MIT license
*/
import UIKit
/// This is base class which consists from `UIStackView`
/// (contanining `UIImageView`) inside of a `UIScrollView`.
/// It will automatically update to the correct zoom scale
/// (depending on `displayMode`) whenever its `frame` changes.
///
/// It may be used directly from code or from storyboard with auto layout,
/// just set its `image` and `displayMode` properties and it will do the rest.
///
/// It's also possible to enable `infiniteScroll` effect by property
/// (which may be useful for 360 panorama images or similar).
open class ImageScrollView: UIScrollView, UIScrollViewDelegate {
// MARK: Types
/// Modes for calculating zoom scale.
public enum DisplayMode {
/// switches between `fit` and `fill` depending of the image ratio.
case automatic
/// Fits entire image.
case fit
/// Fills entire `imageView`.
case fill
/// Fills width of the `imageView`.
case fillWidth
/// Fills height of the `imageView`.
case fillHeight
}
/// Modes for infinite scroll effect.
public enum InfiniteScroll {
/// Disabled infinite scroll effect.
case disabled
/// Horizontal infinite scroll effect.
case horizontal
/// Vertical infinite scroll effect.
case vertical
}
// MARK: Outlets
/// Stack view is placeholder for imageView.
public let stackView = UIStackView()
/// Image view which displays the image.
public let imageView = UIImageView()
/// Duplicated image views for faking `infiniteScroll` effect.
private let leadingImageView = UIImageView()
private let trailingImageView = UIImageView()
// MARK: Properties
/// Image to be displayed. UI will be updated whenever you set this property.
@IBInspectable open var image: UIImage? {
didSet {
updateUI()
}
}
/// Mode to be used when calculating zoom scale. Default value is `.automatic`.
open var displayMode: DisplayMode = .automatic {
didSet {
if displayMode != oldValue, let image = image {
updateZoomScales(with: image)
}
}
}
/// Infinite scroll effect (think of 360 panorama). Defaults to `.disabled`.
open var infiniteScroll: InfiniteScroll = .disabled {
didSet {
if infiniteScroll != oldValue {
resetStackView()
}
}
}
/// Flag that determines if vertical scrolling of image is enabled. Defaults to true.
open var isVerticalScrollEnabled: Bool = true
/// Flag that determines if horizontal scrolling of image is enabled. Defaults to true.
open var isHorizontalScrollEnabled: Bool = true
/// Flag for toggling infinite scroll effect (ie. during zoom or some custom animation).
open var isInfiniteScrollEnabled = true
// MARK: Override
/// Whenever frame property is changed zoom scales are gonna be re-calculated.
override open var frame: CGRect {
willSet {
if !frame.size.equalTo(newValue.size) {
prepareToResize()
}
}
didSet {
if !frame.size.equalTo(oldValue.size), let image = image {
updateZoomScales(with: image)
recoverFromResizing()
}
}
}
/// Whenever bounds are changed zoom scales are gonna be re-calculated.
override open var bounds: CGRect {
willSet {
if !bounds.size.equalTo(newValue.size) {
prepareToResize()
}
}
didSet {
if !bounds.size.equalTo(oldValue.size), let image = image {
updateZoomScales(with: image)
recoverFromResizing()
}
}
}
// MARK: Helpers
private var pointToCenterAfterResize: CGPoint?
private func prepareToResize() {
let boundsCenter = CGPoint(x: bounds.midX, y: bounds.midY)
pointToCenterAfterResize = convert(boundsCenter, to: stackView)
}
private func recoverFromResizing() {
if let pointToCenter = pointToCenterAfterResize {
// calculate min and max content offset
let minimumContentOffset = CGPoint.zero
let maxOffsetX = contentSize.width - bounds.size.width
let maxOffsetY = contentSize.height - bounds.size.height
let maximumContentOffset = CGPoint(x: maxOffsetX, y: maxOffsetY)
// convert our desired center point back to our own coordinate space
let boundsCenter = convert(pointToCenter, from: stackView)
// calculate the content offset that would yield that center point
let offsetX = boundsCenter.x - bounds.size.width / 2.0
let offsetY = boundsCenter.y - bounds.size.height / 2.0
var offset = CGPoint(x: offsetX, y: offsetY)
// calculate offset, adjusted to be within the allowable range
var realMaxOffset = min(maximumContentOffset.x, offset.x)
offset.x = max(minimumContentOffset.x, realMaxOffset)
realMaxOffset = min(maximumContentOffset.y, offset.y)
offset.y = max(minimumContentOffset.y, realMaxOffset)
// restore offset
contentOffset = offset
}
}
// MARK: Init
override public init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
public init() {
super.init(frame: CGRect.zero)
configure()
}
private func configure() {
configureScrollView()
configureStackView()
updateUI()
}
// MARK: Lifecycle
open override func layoutSubviews() {
super.layoutSubviews()
guard isInfiniteScrollEnabled else {
return
}
fakeContentOffsetIfNeeded()
}
// MARK: UIScrollViewDelegate
/// View used for zooming must be `stackView`.
/// Be sure to keep this logic in case of custom `UIScrollViewDelegate` implementation.
open func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return stackView
}
// MARK: API
/// This will center content offset horizontally and verticaly.
/// It's also called whenever `image` property is set.
open func centerContentOffset() {
let centerX = (stackView.frame.size.width - bounds.size.width) / 2.0
let centerY = (stackView.frame.size.height - bounds.size.height) / 2.0
let offset = CGPoint(x: centerX, y: centerY)
setContentOffset(offset, animated: false)
}
// MARK: Helpers
private func configureScrollView() {
backgroundColor = UIColor.black
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
bouncesZoom = true
delegate = self
}
private func configureStackView() {
resetStackView()
addSubview(stackView)
}
private func resetStackView() {
stackView.arrangedSubviews.forEach {
stackView.removeArrangedSubview($0)
}
switch infiniteScroll {
case .disabled:
stackView.addArrangedSubview(imageView)
case .horizontal:
stackView.axis = .horizontal
stackView.addArrangedSubview(leadingImageView)
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(trailingImageView)
case .vertical:
stackView.axis = .vertical
stackView.addArrangedSubview(leadingImageView)
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(trailingImageView)
}
}
private func updateUI() {
resetImage()
resetZoomScales()
if let image = image {
updateImage(image)
updateContentSize(with: image)
updateZoomScales(with: image)
}
centerContentOffset()
}
private func resetImage() {
contentSize = CGSize.zero
imageView.image = nil
leadingImageView.image = nil
trailingImageView.image = nil
}
private func resetZoomScales() {
minimumZoomScale = 1.0
maximumZoomScale = 1.0
zoomScale = 1.0
}
private func updateImage(_ image: UIImage) {
imageView.image = image
if infiniteScroll != .disabled {
leadingImageView.image = image
trailingImageView.image = image
}
}
private func updateContentSize(with image: UIImage) {
let size: CGSize
switch infiniteScroll {
case .disabled:
size = CGSize(
width: image.size.width,
height: image.size.height
)
case .horizontal:
size = CGSize(
width: image.size.width * 3,
height: image.size.height
)
case .vertical:
size = CGSize(
width: image.size.width,
height: image.size.height * 3
)
}
let frame = CGRect(
x: 0, y: 0,
width: size.width, height: size.height
)
stackView.frame = frame
contentSize = size
}
private func updateZoomScales(with image: UIImage) {
// get scales needed to perfectly fit the image
let xScale = bounds.size.width / image.size.width
let yScale = bounds.size.height / image.size.height
let scale: CGFloat
// calculate minimum zoom scale
switch displayMode {
case .automatic:
let automaticZoomToFill = abs(xScale - yScale) < 0.15
scale = automaticZoomToFill ? max(xScale, yScale) : min(xScale, yScale)
case .fit:
scale = min(xScale, yScale)
case .fill:
scale = max(xScale, yScale)
case .fillWidth:
scale = xScale
case .fillHeight:
scale = yScale
}
// set minimum and maximum scale for scrollView
minimumZoomScale = scale
maximumZoomScale = minimumZoomScale * 3.0
zoomScale = minimumZoomScale
if !isVerticalScrollEnabled {
disableVerticalScroll()
}
if !isHorizontalScrollEnabled {
disableHorizontalScroll()
}
}
private func disableVerticalScroll() {
let newContentSize = CGSize(
width: contentSize.width,
height: frame.size.height
)
contentSize = newContentSize
}
private func disableHorizontalScroll() {
let newContentSize = CGSize(
width: frame.size.width,
height: contentSize.height
)
contentSize = newContentSize
}
private func fakeContentOffsetIfNeeded() {
var newOffset: CGPoint?
let xOffset = contentOffset.x
let yOffset = contentOffset.y
let width = contentSize.width / 3
let height = contentSize.height / 3
switch infiniteScroll {
case .disabled:
break
case .horizontal:
let maxOffset = width * 2
if xOffset > maxOffset {
let diff = xOffset - maxOffset
let newX = width + diff
newOffset = CGPoint(x: newX, y: yOffset)
}
let minOffset = width - bounds.width
if xOffset < minOffset {
let diff = minOffset - xOffset
let newX = width + minOffset - diff
newOffset = CGPoint(x: newX, y: yOffset)
}
case .vertical:
let maxOffset = height * 2
if yOffset > maxOffset {
let diff = yOffset - maxOffset
let newY = height + diff
newOffset = CGPoint(x: xOffset, y: newY)
}
let minOffset = height - bounds.height
if yOffset < minOffset {
let diff = minOffset - yOffset
let newY = height + minOffset - diff
newOffset = CGPoint(x: xOffset, y: newY)
}
}
if let newOffset = newOffset {
UIView.performWithoutAnimation {
contentOffset = newOffset
}
}
}
}
| d3b260ec5ca3a10ac4bc0be264747cf9 | 30.124088 | 92 | 0.579112 | false | false | false | false |
bitrise-io/sample-test-ios-xctest | refs/heads/master | BitriseTestingSample/BitriseTestingSample/ConnectionHelper.swift | mit | 1 | //
// ConnectionHelper.swift
// BitriseTestingSample
//
// Created by Tamás Bazsonyi on 6/19/15.
// Copyright (c) 2015 Bitrise. All rights reserved.
//
import UIKit
class ConnectionHelper: NSObject {
static func pingServer() -> Bool {
let urlPath: String = "http://google.com"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: NSURLResponse?
var error: NSError?
let urlData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)
if let httpResponse = response as? NSHTTPURLResponse {
if(httpResponse.statusCode == 200)
{
return true
} else {
return false
}
}
return false
}
}
| 5a314227d784816a4b0fbfde3bb9bf96 | 27.033333 | 115 | 0.602854 | false | false | false | false |
DikeyKing/WeCenterMobile-iOS | refs/heads/master | WeCenterMobile/Controller/FeaturedObjectListViewController.swift | gpl-2.0 | 1 | //
// FeaturedObjectListViewController.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/3/13.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import MJRefresh
import UIKit
@objc protocol FeaturedObjectCell: class {
optional var questionUserButton: UIButton! { get }
optional var questionButton: UIButton! { get }
optional var answerUserButton: UIButton? { get }
optional var answerButton: UIButton? { get }
optional var articleButton: UIButton! { get }
optional var articleUserButton: UIButton! { get }
func update(#object: FeaturedObject)
}
extension FeaturedArticleCell: FeaturedObjectCell {}
extension FeaturedQuestionAnswerCell: FeaturedObjectCell {}
class FeaturedObjectListViewController: UITableViewController {
var type: FeaturedObjectListType
var firstSelected = true
var page = 1
var objects: [FeaturedObject] = []
var shouldReloadAfterLoadingMore = true
let count = 10
let objectTypes: [FeaturedObject.Type] = [FeaturedQuestionAnswer.self, FeaturedQuestionAnswer.self, FeaturedArticle.self]
let identifiers = ["FeaturedQuestionAnswerCellA", "FeaturedQuestionAnswerCellB", "FeaturedArticleCell"]
let nibNames = ["FeaturedQuestionAnswerCellA", "FeaturedQuestionAnswerCellB", "FeaturedArticleCell"]
init(type: FeaturedObjectListType) {
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")
for i in 0..<nibNames.count {
tableView.registerNib(UINib(nibName: nibNames[i], bundle: NSBundle.mainBundle()), forCellReuseIdentifier: identifiers[i])
}
}
func segmentedViewControllerDidSelectSelf(segmentedViewController: MSRSegmentedViewController) {
if firstSelected {
firstSelected = false
tableView.header.beginRefreshing()
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let object = objects[indexPath.row]
if var index = find(map(objectTypes) { object.classForCoder === $0 }, true) {
if let o = object as? FeaturedQuestionAnswer {
index += o.answers.count == 0 ? 1 : 0
}
let cell = tableView.dequeueReusableCellWithIdentifier(identifiers[index], forIndexPath: indexPath) as! FeaturedObjectCell
cell.answerButton??.addTarget(self, action: "didPressAnswerButton:", forControlEvents: .TouchUpInside)
cell.answerUserButton??.addTarget(self, action: "didPressUserButton:", forControlEvents: .TouchUpInside)
cell.articleButton?.addTarget(self, action: "didPressArticleButton:", forControlEvents: .TouchUpInside)
cell.articleUserButton?.addTarget(self, action: "didPressUserButton:", forControlEvents: .TouchUpInside)
cell.questionButton?.addTarget(self, action: "didPressQuestionButton:", forControlEvents: .TouchUpInside)
cell.questionUserButton?.addTarget(self, action: "didPressUserButton:", forControlEvents: .TouchUpInside)
cell.update(object: object)
return cell as! UITableViewCell
} else {
return UITableViewCell() // Needs specification
}
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func didPressUserButton(sender: UIButton) {
if let user = sender.msr_userInfo as? User {
msr_navigationController!.pushViewController(UserViewController(user: user), animated: true)
}
}
func didPressQuestionButton(sender: UIButton) {
if let question = sender.msr_userInfo as? Question {
msr_navigationController!.pushViewController(QuestionViewController(question: question), animated: true)
}
}
func didPressAnswerButton(sender: UIButton) {
if let answer = sender.msr_userInfo as? Answer {
msr_navigationController!.pushViewController(ArticleViewController(dataObject: answer), animated: true)
}
}
func didPressArticleButton(sender: UIButton) {
if let article = sender.msr_userInfo as? Article {
msr_navigationController!.pushViewController(ArticleViewController(dataObject: article), animated: true)
}
}
func refresh() {
shouldReloadAfterLoadingMore = false
tableView.footer?.endRefreshing()
FeaturedObject.fetchFeaturedObjects(page: 1, count: count, type: type,
success: {
[weak self] objects in
if let self_ = self {
self_.page = 1
self_.objects = objects
self_.tableView.reloadData()
self_.tableView.header.endRefreshing()
if self_.tableView.footer == nil {
self_.tableView.wc_addRefreshingFooterWithTarget(self_, action: "loadMore")
}
}
return
},
failure: {
[weak self] error in
self?.tableView.header.endRefreshing()
return
})
}
func loadMore() {
if tableView.header.isRefreshing() {
tableView.footer.endRefreshing()
return
}
shouldReloadAfterLoadingMore = true
FeaturedObject.fetchFeaturedObjects(page: page + 1, count: count, type: type,
success: {
[weak self] objects in
if let self_ = self {
if self_.shouldReloadAfterLoadingMore {
++self_.page
self_.objects.extend(objects)
self_.tableView.reloadData()
self_.tableView.footer.endRefreshing()
}
}
return
},
failure: {
[weak self] error in
self?.tableView.footer.endRefreshing()
return
})
}
}
| 25625e1fc58009b0faa816e22d4ec1da | 43.4375 | 134 | 0.645851 | false | false | false | false |
leannenorthrop/markdown-swift | refs/heads/master | Markdown/Renderer.swift | gpl-2.0 | 1 | //
// Renderer.swift
// Markdown
//
// Created by Leanne Northrop on 22/06/2015.
// Copyright (c) 2015 Leanne Northrop. All rights reserved.
//
import Foundation
public class Renderer {
public init() {}
func escapeHTML(text:String) -> String {
if !text.isBlank() {
return text.replace("&", replacement: "&")
.replace("<", replacement: "<")
.replace(">", replacement: ">")
.replace("\"", replacement: """)
.replace("\'", replacement: "'")
} else {
return ""
}
}
func render_tree(jsonml:String) -> String {
return escapeHTML(jsonml)
}
func render_tree(var jsonml: [AnyObject]) -> String {
if jsonml.isEmpty { return "" }
var tag: AnyObject = jsonml.removeAtIndex(0)
if tag is [AnyObject] {
return render_tree(tag as! [AnyObject])
}
var tagName : String = tag as! String
var attributes : [String:String] = [:]
var content : [String] = []
if jsonml.count > 0 {
if jsonml[0] is Dictionary<String,String> {
attributes = jsonml.removeAtIndex(0) as! Dictionary<String,String>
}
}
while jsonml.count > 0 {
var node: AnyObject = jsonml.removeAtIndex(0)
if node is [AnyObject] {
content.append(render_tree(node as! [AnyObject]))
} else if node is String {
content.append(render_tree(node as! String))
} else if node is [String:AnyObject] {
// to do ?
} else {
println("Render warning: " + node.description)
}
}
var tag_attrs : String = ""
if attributes.indexForKey("src") != nil {
tag_attrs += " src=\"" + escapeHTML(attributes["src"]!) + "\""
attributes.removeValueForKey("src")
}
for (key,value) in attributes {
var escaped = escapeHTML(value)
if !escaped.isBlank() {
tag_attrs += " " + key + "=\"" + escaped + "\""
}
}
// be careful about adding whitespace here for inline elements
var str : String = "<"
str += tag as! String
str += tag_attrs
if (tagName == "img" || tagName == "br" || tagName == "hr") {
str += "/>"
}
else {
str += ">"
str += "".join(content)
str += "</" + tagName + ">"
}
return str
}
} | edbdb64c79497e53b7d6913d0efe3da9 | 29.337079 | 82 | 0.465728 | false | false | false | false |
sportlabsMike/XLForm | refs/heads/master | Examples/Swift/SwiftExample/CustomRows/InlineSegmentedCell/InlineSegmentedCell.swift | mit | 1 | //
// InlineSegmentedCell.swift
// SwiftExample
//
// Created by mathias Claassen on 16/12/15.
// Copyright © 2015 Xmartlabs. All rights reserved.
//
import Foundation
let XLFormRowDescriptorTypeSegmentedInline = "XLFormRowDescriptorTypeSegmentedInline"
let XLFormRowDescriptorTypeSegmentedControl = "XLFormRowDescriptorTypeSegmentedControl"
class InlineSegmentedCell : XLFormBaseCell {
override var canBecomeFirstResponder : Bool {
return true
}
override func becomeFirstResponder() -> Bool {
if isFirstResponder {
return super.becomeFirstResponder()
}
let result = super.becomeFirstResponder()
if result {
let inlineRowDescriptor : XLFormRowDescriptor = XLFormRowDescriptor(tag: nil, rowType: XLFormViewController.inlineRowDescriptorTypesForRowDescriptorTypes()![rowDescriptor!.rowType] as! String)
let cell = inlineRowDescriptor.cell(forForm: formViewController())
let inlineCell = cell as? XLFormInlineRowDescriptorCell
inlineCell?.inlineRowDescriptor = rowDescriptor
rowDescriptor?.sectionDescriptor.addFormRow(inlineRowDescriptor, afterRow: rowDescriptor!)
formViewController().ensureRowIsVisible(inlineRowDescriptor)
}
return result
}
override func resignFirstResponder() -> Bool {
if !isFirstResponder {
return super.resignFirstResponder()
}
let selectedRowPath : IndexPath = formViewController().form.indexPath(ofFormRow: rowDescriptor!)!
let nextRowPath = IndexPath(row: (selectedRowPath as NSIndexPath).row + 1, section: (selectedRowPath as NSIndexPath).section)
let nextFormRow = formViewController().form.formRow(atIndex: nextRowPath)
let section : XLFormSectionDescriptor = formViewController().form.formSection(at: UInt((nextRowPath as NSIndexPath).section))!
let result = super.resignFirstResponder()
if result {
section.removeFormRow(nextFormRow!)
}
return result
}
//Mark: - XLFormDescriptorCell
override func formDescriptorCellCanBecomeFirstResponder() -> Bool {
return rowDescriptor?.isDisabled() == false
}
override func formDescriptorCellBecomeFirstResponder() -> Bool {
if isFirstResponder {
_ = resignFirstResponder()
return false
}
return becomeFirstResponder()
}
override func update() {
super.update()
accessoryType = .none
editingAccessoryType = .none
selectionStyle = .none
textLabel?.text = rowDescriptor?.title
detailTextLabel?.text = valueDisplayText()
}
override func formDescriptorCellDidSelected(withForm controller: XLFormViewController!) {
controller.tableView.deselectRow(at: controller.form.indexPath(ofFormRow: rowDescriptor!)!, animated: true)
}
func valueDisplayText() -> String? {
if let value = rowDescriptor?.value {
return (value as AnyObject).displayText()
}
return rowDescriptor?.noValueDisplayText
}
}
class InlineSegmentedControl : XLFormBaseCell, XLFormInlineRowDescriptorCell {
var inlineRowDescriptor : XLFormRowDescriptor?
lazy var segmentedControl : UISegmentedControl = {
return UISegmentedControl.autolayoutView() as! UISegmentedControl
}()
override func configure() {
super.configure()
selectionStyle = .none
contentView.addSubview(segmentedControl)
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: ["segmentedControl": segmentedControl]))
segmentedControl.addTarget(self, action: #selector(InlineSegmentedControl.valueChanged), for: .valueChanged)
}
override func update() {
super.update()
updateSegmentedControl()
segmentedControl.selectedSegmentIndex = selectedIndex()
segmentedControl.isEnabled = rowDescriptor?.isDisabled() == false
}
//MARK: Actions
@objc func valueChanged() {
inlineRowDescriptor!.value = inlineRowDescriptor!.selectorOptions![segmentedControl.selectedSegmentIndex]
formViewController().updateFormRow(inlineRowDescriptor)
}
//MARK: Helpers
func getItems() -> NSMutableArray {
let result = NSMutableArray()
for option in inlineRowDescriptor!.selectorOptions! {
result.add((option as AnyObject).displayText())
}
return result
}
func updateSegmentedControl() {
segmentedControl.removeAllSegments()
getItems().enumerateObjects({ [weak self] (object, index, stop) in
self?.segmentedControl.insertSegment(withTitle: (object as AnyObject).displayText(), at: index, animated: false)
})
}
func selectedIndex() -> Int {
let formRow = inlineRowDescriptor ?? rowDescriptor
if let value = formRow?.value as? NSObject {
for option in (formRow?.selectorOptions)! {
if ((option as! NSObject).valueData() as AnyObject) === (value.valueData() as AnyObject) {
return formRow?.selectorOptions?.index(where: { ($0 as! NSObject) == (option as! NSObject) } ) ?? -1
}
}
}
return -1
}
}
| fb62732d93d09bdf98cea7ddc833a63a | 36.881944 | 204 | 0.668928 | false | false | false | false |
criticalmaps/criticalmaps-ios | refs/heads/main | CriticalMapsKit/Sources/SharedModels/TwitterFeedFeature/TwitterUser.swift | mit | 2 | import Foundation
/// A structure to represent a twitter user.
public struct TwitterUser: Codable, Hashable {
public var name: String
public var screenName: String
public var profileImageUrl: String
public var profileImage: URL? {
URL(string: profileImageUrl)
}
public init(name: String, screenName: String, profileImageUrl: String) {
self.name = name
self.screenName = screenName
self.profileImageUrl = profileImageUrl
}
private enum CodingKeys: String, CodingKey {
case name
case screenName = "screen_name"
case profileImageUrl = "profile_image_url_https"
}
}
| 0d5b47ebecdfe4f9a4212966f0064acf | 24.75 | 74 | 0.716828 | false | false | false | false |
coffeestats/coffeestats-ios | refs/heads/master | Coffeestats/Classes/ViewController.swift | mit | 1 | //
// ViewController.swift
// Coffeestats
//
// Created by Danilo Bürger on 16/03/2017.
// Copyright © 2017 Danilo Bürger. All rights reserved.
//
import UIKit
import Locksmith
class ViewController: UIViewController, QRCodeScannerDelegate {
@IBOutlet weak var loginButton: UIBarButtonItem!
@IBOutlet weak var webView: UIWebView!
var onTheRun: String? {
didSet {
if let onTheRun = onTheRun {
loginButton.title = "Logout"
webView.loadRequest(URLRequest(url: URL(string: onTheRun)!))
try? Locksmith.saveData(data: ["onTheRun": onTheRun], forUserAccount: "coffeestats")
} else {
loginButton.title = "Login"
webView.loadRequest(URLRequest(url: URL(string: "about:blank")!))
try? Locksmith.deleteDataForUserAccount(userAccount: "coffeestats")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let dictionary = Locksmith.loadDataForUserAccount(userAccount: "coffeestats"),
let onTheRun = dictionary["onTheRun"] as? String {
self.onTheRun = onTheRun
}
}
func isAcceptable(_ qrCode: String) -> Bool {
return qrCode.hasPrefix("https://coffeestats.org/ontherun/")
}
func didScan(_ qrCode: String) {
_ = navigationController?.popToViewController(self, animated: true)
login(qrCode)
}
@IBAction func handleLogin() {
if onTheRun != nil {
logout()
} else {
let vc = QRCodeScannerViewController()
vc.delegate = self
navigationController?.pushViewController(vc, animated: true)
}
}
func login(_ onTheRun: String) {
self.onTheRun = onTheRun
}
func logout() {
onTheRun = nil
}
}
| 5569e15dfb768ce4f31948433b542957 | 26.716418 | 100 | 0.597738 | false | false | false | false |
darrarski/SwipeToReveal-iOS | refs/heads/master | Example/UI/Menu/ViewModels/MainMenuViewModel.swift | mit | 1 | import UIKit
class MainMenuViewModel: MenuViewModel, MenuItemViewModelDelegate {
init(assembly: MenuAssembly) {
self.assembly = assembly
tableViewExample.delegate = self
}
weak var delegate: MenuViewModelDelegate?
private let assembly: MenuAssembly
private let tableViewExample = MainMenuItemViewModel(title: "Table View Cell Example")
// MARK: MenuViewModel
let title = "SwipeToReveal"
var items: [MenuItemViewModel] {
return [tableViewExample]
}
// MARK: MenuItemViewModelDelegate
func menuItemViewModelDidSelect(_ viewModel: MenuItemViewModel) {
if viewModel === tableViewExample {
let viewController = assembly.tableExampleViewController
delegate?.menuViewModel(self, presentViewController: viewController)
} else {
fatalError()
}
}
}
| ccc4f70c98916e47fb3b0c822ad99c6d | 25.666667 | 90 | 0.685227 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/largest-time-for-given-digits.swift | mit | 2 | /**
* https://leetcode.com/problems/largest-time-for-given-digits/
*
*
*/
// Date: Tue Sep 1 12:21:49 PDT 2020
class Solution {
/// Permutation of 4 digits.
func largestTimeFromDigits(_ A: [Int]) -> String {
func perm(_ result: [Int], from cand: [Int]) -> String? {
if result.count == 4 {
let hour = result[0] * 10 + result[1]
let minute = result[2] * 10 + result[3]
if hour >= 0, hour < 24, minute >= 0, minute < 60 {
return String(format: "%02d:%02d", hour, minute)
} else {
return nil
}
}
var cand2 = cand
for index in 0 ..< cand.count {
let c = cand2.remove(at: index)
let result2 = result + [c]
if let text = perm(result2, from: cand2) {
return text
}
cand2.insert(c, at: index)
}
return nil
}
return perm([], from: A.sorted(by: >)) ?? ""
}
} | dce7cdcc809a6f720b06f711f3541cb1 | 31.176471 | 68 | 0.432754 | false | false | false | false |
mercadopago/px-ios | refs/heads/develop | MercadoPagoSDK/MercadoPagoSDK/Config/External/3DSecure/PXThreeDSConfig.swift | mit | 1 | import Foundation
/**
Whe use this object to store properties related to ESC module.
Check PXESCProtocol methods.
*/
@objcMembers
open class PXThreeDSConfig: NSObject {
public let flowIdentifier: String
public let sessionId: String
public let privateKey: String?
init(flowIdentifier: String, sessionId: String, privateKey: String?) {
self.flowIdentifier = flowIdentifier
self.sessionId = sessionId
self.privateKey = privateKey
}
}
// MARK: Internals (Only PX)
extension PXThreeDSConfig {
static func createConfig(privateKey: String? = nil) -> PXThreeDSConfig {
let flowIdentifier = MPXTracker.sharedInstance.getFlowName() ?? "PX"
let sessionId = MPXTracker.sharedInstance.getSessionID()
let defaultConfig = PXThreeDSConfig(flowIdentifier: flowIdentifier, sessionId: sessionId, privateKey: privateKey)
return defaultConfig
}
}
| c6a24b630346bcc5575edc6cf46c8d8b | 31.678571 | 121 | 0.72459 | false | true | false | false |
getSenic/nuimo-swift | refs/heads/master | SDK/NuimoController.swift | mit | 1 | //
// NuimoController.swift
// Nuimo
//
// Created by Lars Blumberg on 10/9/15.
// Copyright © 2015 Senic. All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
public protocol NuimoController: class {
var uuid: UUID {get}
var delegate: NuimoControllerDelegate? {get set}
var connectionState: NuimoConnectionState {get}
/// Display interval in seconds
var defaultMatrixDisplayInterval: TimeInterval {get set}
/// Brightness 0..1 (1=max)
var matrixBrightness: Float {get set}
var hardwareVersion: String? {get}
var firmwareVersion: String? {get}
var color: String? {get}
func connect(autoReconnect: Bool)
func disconnect()
/// Displays an LED matrix for an interval with options (options is of type Int for compatibility with Objective-C)
func display(matrix: NuimoLEDMatrix, interval: TimeInterval, options: Int)
}
public extension NuimoController {
public func connect() {
self.connect(autoReconnect: false)
}
/// Displays an LED matrix with options defaulting to ResendsSameMatrix and WithWriteResponse
public func display(matrix: NuimoLEDMatrix, interval: TimeInterval) {
display(matrix: matrix, interval: interval, options: 0)
}
/// Displays an LED matrix using the default display interval and with options defaulting to ResendsSameMatrix and WithWriteResponse
public func display(matrix: NuimoLEDMatrix) {
display(matrix: matrix, interval: defaultMatrixDisplayInterval)
}
/// Displays an LED matrix for an interval and with options
public func display(matrix: NuimoLEDMatrix, interval: TimeInterval, options: NuimoLEDMatrixWriteOptions) {
display(matrix: matrix, interval: interval, options: options.rawValue)
}
/// Displays an LED matrix using the default display interval and with options defaulting to ResendsSameMatrix and WithWriteResponse
public func display(matrix: NuimoLEDMatrix, options: NuimoLEDMatrixWriteOptions) {
display(matrix: matrix, interval: defaultMatrixDisplayInterval, options: options)
}
}
public enum NuimoLEDMatrixWriteOption: Int {
case ignoreDuplicates = 1
case withFadeTransition = 2
case withoutWriteResponse = 4
}
public struct NuimoLEDMatrixWriteOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let IgnoreDuplicates = NuimoLEDMatrixWriteOptions(rawValue: NuimoLEDMatrixWriteOption.ignoreDuplicates.rawValue)
public static let WithFadeTransition = NuimoLEDMatrixWriteOptions(rawValue: NuimoLEDMatrixWriteOption.withFadeTransition.rawValue)
public static let WithoutWriteResponse = NuimoLEDMatrixWriteOptions(rawValue: NuimoLEDMatrixWriteOption.withoutWriteResponse.rawValue)
}
public enum NuimoConnectionState {
case connecting
case connected
case disconnecting
case disconnected
case invalidated
}
public protocol NuimoControllerDelegate: class {
func nuimoController(_ controller: NuimoController, didChangeConnectionState state: NuimoConnectionState, withError error: Error?)
func nuimoController(_ controller: NuimoController, didUpdateBatteryLevel batteryLevel: Int)
func nuimoController(_ controller: NuimoController, didReceiveGestureEvent event: NuimoGestureEvent)
func nuimoControllerDidDisplayLEDMatrix(_ controller: NuimoController)
}
public extension NuimoControllerDelegate {
func nuimoController(_ controller: NuimoController, didChangeConnectionState state: NuimoConnectionState, withError error: Error?) {}
func nuimoController(_ controller: NuimoController, didUpdateBatteryLevel batteryLevel: Int) {}
func nuimoController(_ controller: NuimoController, didReceiveGestureEvent event: NuimoGestureEvent) {}
func nuimoControllerDidDisplayLEDMatrix(_ controller: NuimoController) {}
}
| e307c498ff3da2115150708c5d59de9f | 40.134021 | 138 | 0.761404 | false | false | false | false |
ja-mes/experiments | refs/heads/master | iOS/TableViewsAPp/TableViewsAPp/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// TableViewsAPp
//
// Created by James Brown on 8/14/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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: "TableViewsAPp")
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)")
}
}
}
}
| 6e575430574c472d58cf6bd85be37d56 | 48.301075 | 285 | 0.685278 | false | false | false | false |
chschroeda/BlennyTV | refs/heads/master | BlennyTV/PreferencesViewController.swift | mit | 1 | //
// PreferencesViewController.swift
// BlennyTV
//
// Created by Christian Schroeder on 21.06.17.
// Copyright © 2017 Christian Schroeder. All rights reserved.
//
import Cocoa
import Foundation
class PreferencesViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var nameLabel: NSTextField!
@IBOutlet weak var nameTextField: NSTextField!
@IBOutlet weak var urlLabel: NSTextField!
@IBOutlet weak var urlTextField: NSTextField!
@IBOutlet weak var saveButton: NSButton!
@IBOutlet weak var cancelButton: NSButton!
@IBOutlet weak var orderTextField: NSTextField!
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var deleteButton: NSButton!
@IBOutlet weak var helpLabel: NSTextField!
@IBOutlet weak var streamForm: NSTextField!
var channels: [Channel] = []
override func viewDidLoad() {
super.viewDidLoad()
deleteButton.isEnabled = false
hideForm()
tableView.headerView = nil
tableView.register(forDraggedTypes: ["public.data"])
getchannels()
}
func hideForm() {
nameLabel.isHidden = true
nameTextField.isHidden = true
urlLabel.isHidden = true
urlTextField.isHidden = true
saveButton.isHidden = true
cancelButton.isHidden = true
helpLabel.isHidden = true
// orderTextField.isHidden = true // debug
}
func showForm() {
nameLabel.isHidden = false
nameTextField.isHidden = false
urlLabel.isHidden = false
urlTextField.isHidden = false
saveButton.isHidden = false
cancelButton.isHidden = false
// orderTextField.isHidden = false // debug
}
func getchannels() {
channels = ChannelManager.getChannels()
tableView.reloadData()
}
func numberOfRows(in tableView: NSTableView) -> Int {
return channels.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.make(withIdentifier: "nameCell", owner: self) as? NSTableCellView {
let channel = channels[row]
cell.textField?.stringValue = channel.name!
return cell
}
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
if tableView.selectedRow >= 0 {
deleteButton.isEnabled = true
saveButton.title = "Save"
helpLabel.stringValue = "Drag & drop to sort Channels"
helpLabel.isHidden = false
showForm()
let channel = channels[tableView.selectedRow]
nameTextField.stringValue = channel.name!
urlTextField.stringValue = channel.url!
orderTextField.stringValue = String(channel.order)
}
}
// MARK - Drag 'n Drop
let dragDropTypeId = "public.data" // or any other UTI you want/need
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
let item = NSPasteboardItem()
item.setString(String(row), forType: dragDropTypeId)
return item
}
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation {
if dropOperation == .above {
return .move
}
return []
}
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableViewDropOperation) -> Bool {
var oldIndexes = [Int]()
info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) {
if let str = ($0.0.item as! NSPasteboardItem).string(forType: self.dragDropTypeId), let index = Int(str) {
oldIndexes.append(index)
}
}
for oldIndex in oldIndexes {
for i in row ..< channels.count {
ChannelManager.updateChannel(index: i, name: nil, url: nil, order: Int16(i+1))
}
ChannelManager.updateChannel(index: oldIndex, name: nil, url: nil, order: Int16(row))
}
ChannelManager.cleanOrder()
getchannels()
return true
}
func importJson(filePath: String) {
let jsonData = FileManager.default.contents(atPath: filePath)
do {
let jsonResult: NSArray = try JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
for channel in jsonResult as Array<AnyObject> {
let channelName: String = channel["channel"] as! String
let channelUrl: String = channel["url"] as! String
ChannelManager.addChannel(name: channelName, url: channelUrl)
}
ChannelManager.cleanOrder()
getchannels()
} catch {}
}
// MARK - action handler
@IBAction func saveClicked(_ sender: Any) {
if nameTextField.stringValue != "" && urlTextField.stringValue != "" {
if tableView.selectedRow >= 0 {
ChannelManager.updateChannel(index: tableView.selectedRow, name: nameTextField.stringValue, url: urlTextField.stringValue, order: nil)
} else {
ChannelManager.addChannel(name: nameTextField.stringValue, url: urlTextField.stringValue)
}
nameTextField.stringValue = ""
urlTextField.stringValue = ""
hideForm()
getchannels()
}
}
@IBAction func deleteChannelClicked(_ sender: Any) {
let alertDialog = NSAlert()
alertDialog.messageText = "Are you sure you want to delete the channel?"
alertDialog.informativeText = ""
alertDialog.addButton(withTitle: "Delete")
alertDialog.addButton(withTitle: "Cancel")
alertDialog.alertStyle = NSAlertStyle.warning
alertDialog.beginSheetModal(for: self.view.window!, completionHandler: { (modalResponse) -> Void in
if modalResponse == NSAlertFirstButtonReturn {
ChannelManager.deleteChannel(index: self.tableView.selectedRow)
self.getchannels()
self.deleteButton.isEnabled = false
}
self.tableView.deselectRow(self.tableView.selectedRow)
self.nameTextField.stringValue = ""
self.urlTextField.stringValue = ""
self.orderTextField.stringValue = ""
self.hideForm()
})
}
@IBAction func addChannelClicked(_ sender: Any) {
tableView.deselectRow(tableView.selectedRow)
saveButton.title = "Add"
nameTextField.stringValue = ""
urlTextField.stringValue = ""
orderTextField.stringValue = ""
helpLabel.stringValue = ""
helpLabel.isHidden = false
showForm()
}
@IBAction func cancelButtonClicked(_ sender: Any) {
self.tableView.deselectRow(self.tableView.selectedRow)
self.hideForm()
}
@IBAction func importJsonListClicked(_ sender: Any) {
let dialog = NSOpenPanel();
dialog.title = "Choose a .json file";
dialog.showsResizeIndicator = true;
dialog.showsHiddenFiles = false;
dialog.canChooseDirectories = true;
dialog.canCreateDirectories = false;
dialog.allowsMultipleSelection = false;
dialog.allowedFileTypes = ["json"];
if (dialog.runModal() == NSModalResponseOK) {
let result = dialog.url
if (result != nil) {
let path = result!.path
self.importJson(filePath: path)
}
} else {
return
}
}
}
| a21d61beb175a7a4781064f287b0afdb | 34.928889 | 185 | 0.608362 | false | false | false | false |
Candyroot/DesignPattern | refs/heads/master | observer/observer/WeatherData.swift | apache-2.0 | 1 | //
// WeatherData.swift
// Chapter2
//
// Created by Bing Liu on 10/27/14.
// Copyright (c) 2014 UnixOSS. All rights reserved.
//
import Foundation
class WeatherData: Subject {
private var observers : [Observer]
private var temperature : Float?
private var humidity : Float?
private var pressure: Float?
init() {
observers = [Observer]()
}
func registerObserver(o: Observer) {
observers.append(o)
}
func removeObserver(o: Observer) {
var i: Int?
for (index, value) in enumerate(observers) {
if value === o {
i = index
}
}
if let index = i {
observers.removeAtIndex(index)
}
}
func notifyObservers() {
for observer in observers {
observer.update(temperature!, humidity!, pressure!)
}
}
func measurementsChanged() {
notifyObservers()
}
func setMeasurements(temperature: Float, _ humidity: Float, _ pressure: Float) {
self.temperature = temperature
self.humidity = humidity
self.pressure = pressure
measurementsChanged()
}
}
| 324fe5914c6b5fa61a9c7a4cc82e32d5 | 21.603774 | 84 | 0.563439 | false | false | false | false |
ProfileCreator/ProfileCreator | refs/heads/master | ProfileCreator/ProfileCreator/Profile Editor/ProfileEditorExtensionOutlineView.swift | mit | 1 | //
// ProfileEditorOutlineView.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
extension ProfileEditor {
func updateOutlineView(payloadPlaceholder: PayloadPlaceholder) {
var payloadContent = [String: Any]()
if payloadPlaceholder.payloadType == .custom, let payloadCustom = payloadPlaceholder.payload as? PayloadCustom {
if
let payloadCustomContents = payloadCustom.payloadContent,
self.selectedPayloadIndex < payloadCustomContents.count {
payloadContent = payloadCustomContents[self.selectedPayloadIndex]
payloadContent.removeValue(forKey: PayloadKey.payloadEnabled)
}
} else {
let profileExport = ProfileExport(exportSettings: self.profile.settings)
profileExport.ignoreErrorInvalidValue = true
profileExport.ignoreSave = true
do {
payloadContent = try profileExport.content(forPayload: payloadPlaceholder.payload, payloadIndex: self.selectedPayloadIndex)
profileExport.updateManagedPreferences(domain: payloadPlaceholder.domain, type: payloadPlaceholder.payloadType, payloadContent: &payloadContent)
} catch {
Log.shared.error(message: "Source view export failed with error: \(error)", category: String(describing: self))
}
}
self.outlineViewController.updateSourceView(payloadContent)
}
}
| bad5b900ae82e3f05b658739108b249b | 37.243902 | 160 | 0.684949 | false | false | false | false |
nasust/LeafViewer | refs/heads/master | LeafViewer/classes/ImageFileManager/ImageFileSystemManager.swift | gpl-3.0 | 1 | //
// Created by hideki on 2017/06/20.
// Copyright (c) 2017 hideki. All rights reserved.
//
import Foundation
import Cocoa
class ImageFileSystemManager: ImageFileManagerProto {
static let typeExtensions: [String] = ["jpg", "jpeg", "png", "gif", "bmp"]
static func isTargetFile(fileName: String) -> Bool {
let fileManager = FileManager.default
var isDir: ObjCBool = false
if fileManager.fileExists(atPath: fileName, isDirectory: &isDir) {
if isDir.boolValue {
do {
let files = try fileManager.contentsOfDirectory(atPath: fileName)
for file in files {
for fileType in ImageFileSystemManager.typeExtensions {
if NSString(string: file).pathExtension.caseInsensitiveCompare(fileType) == .orderedSame {
return true
}
}
}
} catch {
return false
}
} else {
for fileType in typeExtensions {
if NSString(string: fileName).pathExtension.caseInsensitiveCompare(fileType) == .orderedSame {
return true
}
}
}
}
return false
}
private var directoryImageFiles = [String]()
private var currentImageIndex = 0
var currentImage: NSImage? {
get {
if self.directoryImageFiles.count > 0 {
let image = NSImage(contentsOfFile: directoryImageFiles[currentImageIndex])
var width = 0
var height = 0
for imageRep in image!.representations {
if imageRep.pixelsWide > width {
width = imageRep.pixelsWide
}
if imageRep.pixelsHigh > height {
height = imageRep.pixelsHigh
}
}
let viewImage = NSImage(size: NSMakeSize(CGFloat(width), CGFloat(height)))
viewImage.addRepresentations(image!.representations)
return viewImage
} else {
return nil
}
}
}
var currentImageFileName: String? {
get {
if self.directoryImageFiles.count > 0 {
return directoryImageFiles[currentImageIndex]
} else {
return nil
}
}
}
var currentIndex: Int {
get {
return self.currentImageIndex
}
}
var totalCount: Int {
get {
return self.directoryImageFiles.count
}
}
func doNext() -> Bool {
if (self.currentImageIndex + 1 < directoryImageFiles.count) {
self.currentImageIndex += 1
return true
}
return false
}
func doPrev() -> Bool {
if (self.currentImageIndex - 1 >= 0) {
self.currentImageIndex -= 1
return true
}
return false
}
func doFirst() -> Bool {
if self.directoryImageFiles.count > 0 {
self.currentImageIndex = 0
return true
}
return true
}
func doLast() -> Bool {
if self.directoryImageFiles.count > 0 {
self.currentImageIndex = self.directoryImageFiles.count - 1
return true
}
return true
}
func hasNext() -> Bool {
return self.currentImageIndex + 1 < directoryImageFiles.count
}
func hasPrev() -> Bool {
return self.currentImageIndex - 1 >= 0
}
init() {
}
func processFile(fileName: String) -> Bool {
let fileManager = FileManager.default
var isDir: ObjCBool = false
if fileManager.fileExists(atPath: fileName, isDirectory: &isDir) {
if isDir.boolValue {
return self.processImageDirectory(directory: fileName)
} else {
return self.processImageFile(fileName: fileName)
}
}
return false
}
private func processImageFile(fileName: String) -> Bool {
let directoryPath = NSString(string: fileName).deletingLastPathComponent
if self.processImageDirectory(directory: directoryPath) {
self.currentImageIndex = self.directoryImageFiles.index(of: fileName)!
return true
}
return false
}
private func processImageDirectory(directory: String) -> Bool {
let fileManager = FileManager.default
var currentDirectoryImageFiles = [String]()
do {
let files = try fileManager.contentsOfDirectory(atPath: directory)
for file in files {
var hit = false;
for fileType in ImageFileSystemManager.typeExtensions {
if NSString(string: file).pathExtension.caseInsensitiveCompare(fileType) == .orderedSame {
hit = true
break
}
}
if hit {
currentDirectoryImageFiles.append(directory + "/" + file)
}
}
} catch {
return false
}
self.directoryImageFiles = currentDirectoryImageFiles.sorted()
self.currentImageIndex = 0
return true
}
func imageData(fileName: String) -> Data?{
return NSData(contentsOfFile: fileName) as Data!
}
}
| 8106953c1dd248c745c15b1320ebcb7a | 26.732673 | 118 | 0.52517 | false | false | false | false |
mlilback/rc2SwiftClient | refs/heads/master | MacClient/session/sidebar/SpreadsheetVariableDetailController.swift | isc | 1 | //
// SpreadsheetVariableDetailController.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import Model
import ClientCore
import SigmaSwiftStatistics
fileprivate extension NSUserInterfaceItemIdentifier {
static let ssheetHead = NSUserInterfaceItemIdentifier("ssheetHead")
static let ssheetCell = NSUserInterfaceItemIdentifier("ssheetValue")
static let rowHeaderColumn = NSUserInterfaceItemIdentifier("rowHeader")
}
class SpreadsheetVariableDetailController: NSViewController {
@IBOutlet var ssheetTable: NSTableView!
private(set) var variable: Variable!
private var ssheetSource: SpreadsheetDataSource?
private var columnIndexes = [NSTableColumn: Int]()
private var colOffset = 1
func set(variable: Variable, source: SpreadsheetDataSource) -> NSSize {
self.variable = variable
self.ssheetSource = source
ssheetTable.tableColumns.forEach { ssheetTable.removeTableColumn($0) }
var estWidth: CGFloat = 0
let font = NSFont.userFont(ofSize: 14.0)
let fontAttrs: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font as Any]
// create row header column
if source.rowNames != nil {
let headColumn = NSTableColumn(identifier: .rowHeaderColumn)
headColumn.width = 40.0
headColumn.title = ""
ssheetTable.addTableColumn(headColumn)
columnIndexes[headColumn] = 0
colOffset = 0
estWidth += headColumn.width
}
// create data columns
for colIdx in 0..<source.columnCount {
//var colWidth: CGFloat = 40.0
let widths = source.values(forColumn: colIdx).map { Double(($0 as NSString).size(withAttributes: fontAttrs).width) }
let aColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: String(colIdx + colOffset)))
var headerWidth: Double = 0
if let colName = source.columnNames?[colIdx] {
aColumn.title = colName
// colWidth = max(colWidth, (colName as NSString).size(withAttributes: fontAttrs).width)
headerWidth = Double((colName as NSString).size(withAttributes: fontAttrs).width)
}
let avgWidth = Sigma.average(widths) ?? 20 // if average return nil (which it will if there are no widths) use 20
let maxWidth = max(headerWidth, Sigma.max(widths)!)
let stdDev = Sigma.standardDeviationPopulation(widths) ?? 0 // if stdDev returns nil, use 0 as the value
let desiredWidth = min(maxWidth, avgWidth + (2.0 * stdDev))
aColumn.width = CGFloat(min(desiredWidth.rounded(), 40)) + 16 //16 is std offset (8) for each side of label
ssheetTable.addTableColumn(aColumn)
columnIndexes[aColumn] = colIdx + colOffset
estWidth += aColumn.width
}
if source.columnNames == nil {
ssheetTable.headerView = nil
} else {
ssheetTable.headerView = NSTableHeaderView()
}
ssheetTable.reloadData()
let idealHeight = CGFloat(80 + (source.rowCount * 32))
let sz = NSSize(width: min(max(estWidth, 200), 500), height: min(max(idealHeight, 240), 600))
print("df \(estWidth) x \(idealHeight), actual = \(sz)")
return sz
}
}
extension SpreadsheetVariableDetailController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return ssheetSource?.rowCount ?? 0
}
}
extension SpreadsheetVariableDetailController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let column = tableColumn, let columnIndex = columnIndexes[column] else { return nil }
var cellIdent = NSUserInterfaceItemIdentifier.ssheetCell
var cellString = ""
if tableColumn?.identifier == .rowHeaderColumn {
cellIdent = .ssheetHead
if let rowName = ssheetSource?.rowNames?[row] {
cellString = rowName
}
} else {
cellString = ssheetSource?.value(atRow: row, column: columnIndex - colOffset) ?? ""
}
guard let cellView = tableView.makeView(withIdentifier: cellIdent, owner: nil) as? NSTableCellView
else { fatalError("failed to load table cell view") }
cellView.textField?.stringValue = cellString
return cellView
}
}
| cbe2fc0b888b2d9c6da706dc9e9ec57d | 39.09 | 119 | 0.743577 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | refs/heads/master | AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/Review/ReviewCell.swift | mit | 1 | import Foundation
@objc protocol ReviewCellDelegate: class {
func gateLogoClicked(review: HDKReview)
}
class ReviewCell: UITableViewCell {
private struct Consts {
static let gateLogoWidth: CGFloat = 100
static let gateLogoHeight: CGFloat = 15
}
let ratingView = ReviewRatingView()
let authorLabel = UILabel()
let dateLabel = UILabel()
let gateLogo = GateLogoView()
let separatorView = SeparatorView()
var review: HDKReview?
let reviewTextsView = ReviewTextsContainerView()
weak var delegate: ReviewCellDelegate?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
createSubviews()
createConstraints()
addEventHandlers()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createSubviews() {
contentView.addSubview(ratingView)
authorLabel.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)
authorLabel.textColor = JRColorScheme.darkTextColor()
contentView.addSubview(authorLabel)
dateLabel.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)
dateLabel.textColor = JRColorScheme.darkTextColor()
contentView.addSubview(dateLabel)
contentView.addSubview(gateLogo)
contentView.addSubview(reviewTextsView)
separatorView.attachToView(contentView, edge: .bottom, insets: UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15))
}
private func createConstraints() {
let ratingViewSize: CGFloat = 30
ratingView.autoSetDimensions(to: CGSize(width: ratingViewSize, height: ratingViewSize))
ratingView.autoPinEdge(toSuperviewEdge: .leading, withInset: 15)
ratingView.autoPinEdge(.top, to: .top, of: authorLabel, withOffset: 1)
ratingView.layer.cornerRadius = ratingViewSize / 2.0
authorLabel.autoPinEdge(toSuperviewEdge: .top, withInset: 20)
authorLabel.autoPinEdge(.top, to: .top, of: ratingView, withOffset: -1)
authorLabel.autoPinEdge(.leading, to: .trailing, of: ratingView, withOffset: 7)
authorLabel.autoPinEdge(.trailing, to: .leading, of: gateLogo)
dateLabel.autoPinEdge(.leading, to: .leading, of: authorLabel)
dateLabel.autoPinEdge(.top, to: .bottom, of: authorLabel)
gateLogo.autoPinEdge(toSuperviewEdge: .trailing, withInset: 15)
gateLogo.autoAlignAxis(.horizontal, toSameAxisOf: ratingView)
gateLogo.autoSetDimensions(to: CGSize(width: Consts.gateLogoWidth, height: Consts.gateLogoHeight))
reviewTextsView.autoPinEdge(toSuperviewEdge: .leading, withInset: 15)
reviewTextsView.autoPinEdge(toSuperviewEdge: .trailing, withInset: 15)
reviewTextsView.autoPinEdge(.top, to: .bottom, of: dateLabel, withOffset: 15)
NSLayoutConstraint.autoSetPriority(UILayoutPriority(rawValue: 900)) {
self.reviewTextsView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 20)
}
}
func configure(forReview review: HDKReview, shouldHideSeparator: Bool) {
self.review = review
authorLabel.text = review.author
dateLabel.text = StringUtils.reviewDate(date: review.createdAt)
ratingView.configure(forRating: review.rating)
gateLogo.configure(forGate: review.gate, maxImageSize: CGSize(width: Consts.gateLogoWidth, height: Consts.gateLogoHeight), alignment: .right)
reviewTextsView.configure(review: review)
separatorView.isHidden = shouldHideSeparator
}
@objc func gateLogoClicked() {
guard let review = review else { return }
delegate?.gateLogoClicked(review: review)
}
private func addEventHandlers() {
let tap = UITapGestureRecognizer(target: self, action: #selector(gateLogoClicked))
gateLogo.isUserInteractionEnabled = true
gateLogo.addGestureRecognizer(tap)
}
static func preferredHeight() -> CGFloat {
return UITableView.automaticDimension
}
}
| b117530a4212986317de7c5a7b7cf4e4 | 36.908257 | 149 | 0.703533 | false | false | false | false |
fnazarios/weather-app | refs/heads/master | Carthage/Checkouts/Moya/Source/Moya.swift | apache-2.0 | 2 | import Foundation
import Alamofire
/// General-purpose class to store some enums and class funcs.
public class Moya {
/// Closure to be executed when a request has completed.
public typealias Completion = (data: NSData?, statusCode: Int?, response: NSURLResponse?, error: ErrorType?) -> ()
/// Represents an HTTP method.
public enum Method {
case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT
func method() -> Alamofire.Method {
switch self {
case .GET:
return .GET
case .POST:
return .POST
case .PUT:
return .PUT
case .DELETE:
return .DELETE
case .HEAD:
return .HEAD
case .OPTIONS:
return .OPTIONS
case PATCH:
return .PATCH
case TRACE:
return .TRACE
case .CONNECT:
return .CONNECT
}
}
}
/// Choice of parameter encoding.
public enum ParameterEncoding {
case URL
case JSON
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
func parameterEncoding() -> Alamofire.ParameterEncoding {
switch self {
case .URL:
return .URL
case .JSON:
return .JSON
case .PropertyList(let format, let options):
return .PropertyList(format, options)
case .Custom(let closure):
return .Custom(closure)
}
}
}
public enum StubBehavior {
case Never
case Immediate
case Delayed(seconds: NSTimeInterval)
}
}
/// Protocol to define the base URL, path, method, parameters and sample data for a target.
public protocol MoyaTarget {
var baseURL: NSURL { get }
var path: String { get }
var method: Moya.Method { get }
var parameters: [String: AnyObject]? { get }
var sampleData: NSData { get }
}
/// Protocol to define the opaque type returned from a request
public protocol Cancellable {
func cancel()
}
/// Request provider class. Requests should be made through this class only.
public class MoyaProvider<Target: MoyaTarget> {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = Target -> Endpoint<Target>
/// Closure that resolves an Endpoint into an NSURLRequest.
public typealias RequestClosure = (Endpoint<Target>, NSURLRequest -> Void) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = Target -> Moya.StubBehavior
public let endpointClosure: EndpointClosure
public let requestClosure: RequestClosure
public let stubClosure: StubClosure
public let manager: Manager
/// A list of plugins
/// e.g. for logging, network activity indicator or credentials
public let plugins: [Plugin<Target>]
/// Initializes a provider.
public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = Alamofire.Manager.sharedInstance,
plugins: [Plugin<Target>] = []) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.manager = manager
self.plugins = plugins
}
/// Returns an Endpoint based on the token, method, and parameters by invoking the endpointsClosure.
public func endpoint(token: Target) -> Endpoint<Target> {
return endpointClosure(token)
}
/// Designated request-making method. Returns a Cancellable token to cancel the request later.
public func request(target: Target, completion: Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
var cancellableToken = CancellableWrapper()
let performNetworking = { (request: NSURLRequest) in
if cancellableToken.isCancelled { return }
switch stubBehavior {
case .Never:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, completion: completion)
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
}
/// Mark: Defaults
public extension MoyaProvider {
// These functions are default mappings to endpoings and requests.
public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: NSURLRequest -> Void) {
return closure(endpoint.urlRequest)
}
}
/// Mark: Stubbing
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
public final class func NeverStub(_: Target) -> Moya.StubBehavior {
return .Never
}
public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior {
return .Immediate
}
public final class func DelayedStub(seconds: NSTimeInterval)(_: Target) -> Moya.StubBehavior {
return .Delayed(seconds: seconds)
}
}
private extension MoyaProvider {
func sendRequest(target: Target, request: NSURLRequest, completion: Moya.Completion) -> CancellableToken {
let request = manager.request(request)
let plugins = self.plugins
// Give plugins the chance to alter the outgoing request
plugins.forEach { $0.willSendRequest(request, provider: self, target: target) }
// Perform the actual request
let alamoRequest = request.response { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in
let statusCode = response?.statusCode
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(data, statusCode: statusCode, response: response, error: error, provider: self, target: target) }
completion(data: data, statusCode: statusCode, response: response, error: error)
}
return CancellableToken(request: alamoRequest)
}
func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken {
var canceled = false
let cancellableToken = CancellableToken { canceled = true }
let request = manager.request(request)
let plugins = self.plugins
plugins.forEach { $0.willSendRequest(request, provider: self, target: target) }
let stub: () -> () = {
if (canceled) {
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)
plugins.forEach { $0.didReceiveResponse(nil, statusCode: nil, response: nil, error: error, provider: self, target: target) }
completion(data: nil, statusCode: nil, response: nil, error: error)
return
}
switch endpoint.sampleResponseClosure() {
case .NetworkResponse(let statusCode, let data):
plugins.forEach { $0.didReceiveResponse(data, statusCode: statusCode, response: nil, error: nil, provider: self, target: target) }
completion(data: data, statusCode: statusCode, response: nil, error: nil)
case .NetworkError(let error):
plugins.forEach { $0.didReceiveResponse(nil, statusCode: nil, response: nil, error: error, provider: self, target: target) }
completion(data: nil, statusCode: nil, response: nil, error: error)
}
}
switch stubBehavior {
case .Immediate:
stub()
case .Delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset)
dispatch_after(killTime, dispatch_get_main_queue()) {
stub()
}
case .Never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
}
/// Private token that can be used to cancel requests
private struct CancellableToken: Cancellable , CustomDebugStringConvertible{
let cancelAction: () -> Void
let request : Request?
func cancel() {
cancelAction()
}
init(action: () -> Void){
self.cancelAction = action
self.request = nil
}
init(request : Request){
self.request = request
self.cancelAction = {
request.cancel()
}
}
var debugDescription: String {
guard let request = self.request else {
return "Empty Request"
}
return request.debugDescription
}
}
private struct CancellableWrapper: Cancellable {
var innerCancellable: CancellableToken? = nil
private var isCancelled = false
func cancel() {
innerCancellable?.cancel()
}
}
/// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins.
extension Request: MoyaRequest { }
| 3c133af96ad52d327c8aa0351f942a76 | 34.424561 | 171 | 0.638966 | false | false | false | false |
amolloy/LinkAgainstTheWorld | refs/heads/master | Frameworks/TileMap/TileMap/TlleMapSKRenderer.swift | mit | 2 | //
// TlleMapSKRenderer.swift
// TileMap
//
// Created by Andrew Molloy on 8/13/15.
// Copyright © 2015 Andrew Molloy. All rights reserved.
//
import Foundation
import SpriteKit
public class TileMapSKRenderer
{
let tileMap : TileMap
var textureAtlas : SKTextureAtlas?
enum Error : ErrorType
{
case MissingTileMapHeader
case MissingBlockGraphics
case MissingBlockData
case MissingColorMap
case InvalidBlockImage
case UnsupportedColorDepth
case CannotCreateDataProvider
case CannotCreateImageFromData
case MissingTextureAtlas
}
public init(tileMap: TileMap)
{
self.tileMap = tileMap
textureAtlas = nil
}
func createTextureAtlas() throws
{
guard let mapHeader = tileMap.mapHeader else
{
throw Error.MissingTileMapHeader
}
guard let buffer = tileMap.blockGraphics?.buffer else
{
throw Error.MissingBlockGraphics
}
let blockWidth = Int(mapHeader.blockSize.width)
let blockHeight = Int(mapHeader.blockSize.height)
let blockDepth = mapHeader.blockColorDepth
let bytesPerPixel = (blockDepth + 1) / 8
let blockDataSize = blockWidth * blockHeight * bytesPerPixel
let blockCount = buffer.count / blockDataSize
let cs = CGColorSpaceCreateDeviceRGB()!
var atlasInfo = [String: AnyObject]()
for i in 0..<blockCount
{
let offset = i * blockDataSize
let subBuffer = buffer[offset..<(offset + blockDataSize)]
let cgImage : CGImageRef
if mapHeader.blockColorDepth == 8
{
guard let colorMap = tileMap.colorMap else
{
throw Error.MissingColorMap
}
cgImage = try create8BitTexture(mapHeader.blockSize,
colorSpace: cs,
buffer: subBuffer,
colorMap: colorMap,
keyColor: mapHeader.keyColor8Bit)
}
else if mapHeader.blockColorDepth == 15 || mapHeader.blockColorDepth == 16
{
// TODO
throw Error.UnsupportedColorDepth
}
else if mapHeader.blockColorDepth == 24
{
cgImage = try create24BitTexture(mapHeader.blockSize,
colorSpace:cs,
buffer: subBuffer,
keyColor: mapHeader.keyColor)
}
else if mapHeader.blockColorDepth == 32
{
// TODO
throw Error.UnsupportedColorDepth
}
else
{
throw Error.UnsupportedColorDepth
}
atlasInfo[String(i)] = NSImage(CGImage: cgImage, size: NSSize(mapHeader.blockSize))
}
textureAtlas = SKTextureAtlas(dictionary: atlasInfo)
}
func create8BitTexture(blockSize: MapHeader.Size,
colorSpace: CGColorSpaceRef,
buffer: ArraySlice<UInt8>,
colorMap: ColorMap,
keyColor: UInt8) throws -> CGImageRef
{
var rgbBuffer = [UInt8]()
rgbBuffer.reserveCapacity(buffer.count * 4)
for key in buffer
{
if keyColor == key
{
rgbBuffer.append(0);
rgbBuffer.append(0);
rgbBuffer.append(0);
rgbBuffer.append(0);
}
else
{
let (r, g, b) = colorMap.palette[Int(key)]
rgbBuffer.append(r);
rgbBuffer.append(g);
rgbBuffer.append(b);
rgbBuffer.append(0xFF);
}
}
let rgbData = NSData(bytes: &rgbBuffer, length: rgbBuffer.count)
guard let provider = CGDataProviderCreateWithCFData(rgbData) else
{
throw Error.CannotCreateDataProvider
}
guard let cgImage = CGImageCreate(blockSize.width,
blockSize.height,
8,
32,
blockSize.width * 4,
colorSpace,
CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue),
provider,
nil,
true,
CGColorRenderingIntent.RenderingIntentDefault) else
{
throw Error.InvalidBlockImage
}
return cgImage
}
func create24BitTexture(blockSize: MapHeader.Size,
colorSpace: CGColorSpaceRef,
buffer: ArraySlice<UInt8>,
keyColor: TileMap.Color) throws -> CGImageRef
{
assert(buffer.count % 3 == 0)
var rgbBuffer = [UInt8]()
rgbBuffer.reserveCapacity((buffer.count / 3) * 4)
for i in 0..<(buffer.count / 3)
{
let r = buffer[i * 3 + 0]
let g = buffer[i * 3 + 1]
let b = buffer[i * 3 + 2]
let color : TileMap.Color = TileMap.Color(r: r, g: g, b: b)
rgbBuffer.append(r)
rgbBuffer.append(g)
rgbBuffer.append(b)
if keyColor == color
{
rgbBuffer.append(0);
}
else
{
rgbBuffer.append(0xFF);
}
}
let rgbData = NSData(bytes: &rgbBuffer, length: rgbBuffer.count)
guard let provider = CGDataProviderCreateWithCFData(rgbData) else
{
throw Error.CannotCreateDataProvider
}
guard let cgImage = CGImageCreate(blockSize.width,
blockSize.height,
8,
32,
blockSize.width * 4,
colorSpace,
CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue),
provider,
nil,
true,
CGColorRenderingIntent.RenderingIntentDefault) else
{
throw Error.InvalidBlockImage
}
return cgImage
}
public func node() throws -> TileMapSKNode?
{
if self.textureAtlas == nil
{
do
{
try createTextureAtlas()
}
catch let e
{
assertionFailure("Couldn't create texture atlas: \(e)")
return nil
}
}
guard let textureAtlas = self.textureAtlas else
{
throw Error.MissingTextureAtlas
}
let node = TileMapSKNode(tileMap: tileMap, textureAtlas: textureAtlas)
// TODO this api is all wrong.
var i = 0
for layer in tileMap.layers
{
let sn = node.buildTilesForLayer(layer)
if let sn = sn
{
sn.zPosition = CGFloat(i * 100)
node.addChild(sn)
}
++i
}
return node
}
}
| 0c5f20ebc2164b9fca0c0d9015b5c208 | 20.534694 | 86 | 0.691433 | false | false | false | false |
oleander/bitbar | refs/heads/master | Tests/PluginTests/PluginTests.swift | mit | 1 | import Quick
import Nimble
import Async
import PathKit
import Config
@testable import SharedTests
@testable import Plugin
class PluginTests: QuickSpec {
override func spec() {
describe("plugin") {
var manager: Manager!
var folder: Path!
var plugin: PluginFile!
var events: [Tray.Event]!
beforeEach {
folder = Path.tmp
manager = Manager(Config(home: folder))
try! manager.dump(.plugin, as: "plugin1.10s.sh")
try! manager.dump(.plugin, as: "invalid")
manager.refresh()
plugin = manager.findPlugin(byName: "plugin1.10s.sh")!
events = [
.title("…"),
.title("Hello")
]
}
afterEach {
try? folder.delete()
}
it("has a name") {
expect(plugin.name).to(equal("plugin1.10s.sh"))
}
describe("show") {
it("visible by default") {
after(3) {
expect(plugin.tray.events).to(equal(events))
}
}
}
describe("hide") {
it("is now hiden") {
after(1) {
plugin.hide()
}
after(3) {
expect(plugin.tray.events).to(equal(events << .hide))
}
}
}
describe("refresh") {
it("is now refreshed") {
after(1) {
plugin.refresh()
}
after(3) {
expect(plugin.tray.events).to(equal(events))
}
}
}
describe("invoke") {
it("invokes with arguments") {
after(1) {
plugin.invoke(["1"])
}
after(3) {
expect(plugin.tray.events).to(equal(events << .title("1")))
}
}
}
describe("rotate") {
beforeEach {
let name = "rotate.10s.sh"
manager = Manager(Config(home: .tmp))
try! manager.dump(.rotate, as: name)
manager.refresh()
plugin = manager.findPlugin(byName: name)!
events = [.title("…")]
}
it("it rotates between multiply arguments") {
after(3) {
expect(plugin.tray.events).to(
beCyclicSubset(
of: [.title("A"), .title("B")],
from: 1
)
)
}
}
it("it stops rotating on hide") {
plugin.hide()
after(3) {
expect(plugin.tray.events).to(equal(events << .hide))
}
}
it("it does nothing on show") {
plugin.show()
after(3) {
expect(plugin.tray.events).to(beginWith(events << .show))
expect(plugin.tray.events).to(
beCyclicSubset(
of: [.title("A"), .title("B")],
from: 2
)
)
}
}
it("it restarts loop in refresh") {
after(1) {
plugin.refresh()
}
after(3) {
expect(plugin.tray.events).to(beginWith(events))
expect(plugin.tray.events).to(
beCyclicSubset(
of: [.title("A"), .title("B")],
from: 1
)
)
}
}
}
describe("error") {
beforeEach {
let name = "error.10s.sh"
folder = Path.tmp
try? Path.error.copy(folder + Path(name))
manager = Manager(Config(home: folder))
manager.refresh()
plugin = manager.findPlugin(byName: name)!
events = [.title("…")]
}
xit("should fail") {
after(3) {
expect(plugin.tray.events).to(equal(events << .error(["output(\"generic(Optional(\"\n\"))\")"])))
}
}
}
describe("didReceiveError") {
it("handles error") {
plugin.plugin(didReceiveError: "an error")
}
it("handles blank inout") {
plugin.plugin(didReceiveError: "")
}
}
describe("didReceiveOutput") {
it("handles blank input") {
plugin.plugin(didReceiveOutput: "")
}
it("handles success") {
plugin.plugin(didReceiveOutput: "a message")
}
}
}
}
}
| 6ce2d673ffca4374baa696e3925b4b9a | 22.436464 | 109 | 0.457331 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.